diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..29bdb9f --- /dev/null +++ b/LICENSE @@ -0,0 +1,226 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------------------------------------------------------------------- + +This product bundles ActionScript and MXML syntax definitions from +Sublime Text 2 Actionscript 3 Package, which is available under the following +license: + +Copyright (C) 2012 Calvin Wylie + +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. \ No newline at end of file diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000..947bae3 --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: eclipse-as3mxml +Bundle-SymbolicName: com.as3mxml.eclipse;singleton:=true +Bundle-Version: 1.0.0.alpha +Bundle-Activator: com.as3mxml.eclipse.Activator +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.tm4e.core;bundle-version="0.4.1", + org.eclipse.tm4e.registry;bundle-version="0.4.0", + org.eclipse.tm4e.ui;bundle-version="0.4.1", + org.eclipse.ui.genericeditor;bundle-version="1.2.0", + org.eclipse.lsp4e;bundle-version="0.13.6", + org.eclipse.tm4e.languageconfiguration;bundle-version="0.3.5" +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Automatic-Module-Name: com.as3mxml.eclipse +Bundle-ActivationPolicy: lazy diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..8112c1d --- /dev/null +++ b/NOTICE @@ -0,0 +1,2 @@ +ActionScript & MXML plugin for Eclipse +Copyright 2021 Bowler Hat LLC \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3522b82 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# ActionScript & MXML language plugin for Eclipse + +**Experimental** plugin that uses the ActionScript & MXML language server to provide code intelligence in Eclipse IDE. \ No newline at end of file diff --git a/build.properties b/build.properties new file mode 100644 index 0000000..9e6cb64 --- /dev/null +++ b/build.properties @@ -0,0 +1,8 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + syntaxes/,\ + language-server/,\ + language-configurations/ diff --git a/language-configurations/actionscript.configuration.json b/language-configurations/actionscript.configuration.json new file mode 100644 index 0000000..c720868 --- /dev/null +++ b/language-configurations/actionscript.configuration.json @@ -0,0 +1,69 @@ +{ + "comments": + { + "lineComment": "//", + "blockComment": [ "/*", "*/" ] + }, + "brackets": + [ + [ "{", "}" ], + [ "[", "]" ], + [ "(", ")" ] + ], + "autoClosingPairs": + [ + { + "open": "{", + "close": "}" + }, + { + "open": "[", + "close": "]" + }, + { + "open": "(", + "close": ")" + }, + { + "open": "\"", + "close": "\"", + "notIn": + [ + "string" + ] + }, + { + "open": "'", + "close": "'", + "notIn": + [ + "string", + "comment" + ] + }, + { + "open": "/**", + "close": " */", + "notIn": + [ + "string" + ] + } + ], + "surroundingPairs": + [ + ["(", ")"], + ["[", "]"], + ["{", "}"], + ["'", "'"], + ["\"", "\""] + ], + "folding": + { + "markers": + { + "start": "^\\s*//\\s*#?region", + "end": "^\\s*//\\s*#?endregion" + } + } +} \ No newline at end of file diff --git a/language-configurations/mxml.configuration.json b/language-configurations/mxml.configuration.json new file mode 100644 index 0000000..7655bb7 --- /dev/null +++ b/language-configurations/mxml.configuration.json @@ -0,0 +1,68 @@ +{ + "comments": + { + "lineComment": "", + "blockComment": [ "" ] + }, + "brackets": + [ + [ "<", ">" ], + [ "{", "}" ], + [ "[", "]" ], + [ "(", ")" ] + ], + "autoClosingPairs": + [ + { + "open": "{", + "close": "}" + }, + { + "open": "[", + "close": "]" + }, + { + "open": "(", + "close": ")" + }, + { + "open": "\"", + "close": "\"", + "notIn": + [ + "string" + ] + }, + { + "open": "'", + "close": "'", + "notIn": + [ + "string", + "comment" + ] + }, + { + "open": "/**", + "close": " */", + "notIn": + [ + "string" + ] + } + ], + "surroundingPairs": + [ + ["<", ">"], + ["'", "'"], + ["\"", "\""] + ], + "folding": + { + "markers": + { + "start": "^\\s*", + "end": "^\\s*" + } + } +} \ No newline at end of file diff --git a/language-server/bin/ASCSH-LICENSE b/language-server/bin/ASCSH-LICENSE new file mode 100644 index 0000000..3c1c7e9 --- /dev/null +++ b/language-server/bin/ASCSH-LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Jeff Ward + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/language-server/bin/asconfigc.jar b/language-server/bin/asconfigc.jar new file mode 100644 index 0000000..7934885 Binary files /dev/null and b/language-server/bin/asconfigc.jar differ diff --git a/language-server/bin/ascsh.jar b/language-server/bin/ascsh.jar new file mode 100644 index 0000000..9e563a1 Binary files /dev/null and b/language-server/bin/ascsh.jar differ diff --git a/language-server/bin/check-java-version.jar b/language-server/bin/check-java-version.jar new file mode 100644 index 0000000..4a4e7db Binary files /dev/null and b/language-server/bin/check-java-version.jar differ diff --git a/language-server/bin/check-royale-version.jar b/language-server/bin/check-royale-version.jar new file mode 100644 index 0000000..3f37e7d Binary files /dev/null and b/language-server/bin/check-royale-version.jar differ diff --git a/language-server/bin/commons-cli-1.4.jar b/language-server/bin/commons-cli-1.4.jar new file mode 100644 index 0000000..22deb30 Binary files /dev/null and b/language-server/bin/commons-cli-1.4.jar differ diff --git a/language-server/bin/commons-io-2.4.jar b/language-server/bin/commons-io-2.4.jar new file mode 100644 index 0000000..90035a4 Binary files /dev/null and b/language-server/bin/commons-io-2.4.jar differ diff --git a/language-server/bin/commons-lang3-3.7.jar b/language-server/bin/commons-lang3-3.7.jar new file mode 100644 index 0000000..f37ded6 Binary files /dev/null and b/language-server/bin/commons-lang3-3.7.jar differ diff --git a/language-server/bin/dom4j-1.6.1.jar b/language-server/bin/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/language-server/bin/dom4j-1.6.1.jar differ diff --git a/language-server/bin/dom4j-2.1.3.jar b/language-server/bin/dom4j-2.1.3.jar new file mode 100644 index 0000000..9a4f5d2 Binary files /dev/null and b/language-server/bin/dom4j-2.1.3.jar differ diff --git a/language-server/bin/gson-2.8.8.jar b/language-server/bin/gson-2.8.8.jar new file mode 100644 index 0000000..4707d40 Binary files /dev/null and b/language-server/bin/gson-2.8.8.jar differ diff --git a/language-server/bin/jackson-annotations-2.12.1.jar b/language-server/bin/jackson-annotations-2.12.1.jar new file mode 100644 index 0000000..bb8bdc7 Binary files /dev/null and b/language-server/bin/jackson-annotations-2.12.1.jar differ diff --git a/language-server/bin/jackson-core-2.12.1.jar b/language-server/bin/jackson-core-2.12.1.jar new file mode 100644 index 0000000..6886c08 Binary files /dev/null and b/language-server/bin/jackson-core-2.12.1.jar differ diff --git a/language-server/bin/jackson-databind-2.12.1.jar b/language-server/bin/jackson-databind-2.12.1.jar new file mode 100644 index 0000000..f6aacc7 Binary files /dev/null and b/language-server/bin/jackson-databind-2.12.1.jar differ diff --git a/language-server/bin/json-schema-validator-1.0.53.jar b/language-server/bin/json-schema-validator-1.0.53.jar new file mode 100644 index 0000000..4be436d Binary files /dev/null and b/language-server/bin/json-schema-validator-1.0.53.jar differ diff --git a/language-server/bin/language-server.jar b/language-server/bin/language-server.jar new file mode 100644 index 0000000..90ed110 Binary files /dev/null and b/language-server/bin/language-server.jar differ diff --git a/language-server/bin/org.eclipse.lsp4j-0.12.0.jar b/language-server/bin/org.eclipse.lsp4j-0.12.0.jar new file mode 100644 index 0000000..c4295b2 Binary files /dev/null and b/language-server/bin/org.eclipse.lsp4j-0.12.0.jar differ diff --git a/language-server/bin/org.eclipse.lsp4j.generator-0.12.0.jar b/language-server/bin/org.eclipse.lsp4j.generator-0.12.0.jar new file mode 100644 index 0000000..555c83d Binary files /dev/null and b/language-server/bin/org.eclipse.lsp4j.generator-0.12.0.jar differ diff --git a/language-server/bin/org.eclipse.lsp4j.jsonrpc-0.12.0.jar b/language-server/bin/org.eclipse.lsp4j.jsonrpc-0.12.0.jar new file mode 100644 index 0000000..7f17321 Binary files /dev/null and b/language-server/bin/org.eclipse.lsp4j.jsonrpc-0.12.0.jar differ diff --git a/language-server/bin/org.eclipse.xtend.lib-2.24.0.jar b/language-server/bin/org.eclipse.xtend.lib-2.24.0.jar new file mode 100644 index 0000000..62491df Binary files /dev/null and b/language-server/bin/org.eclipse.xtend.lib-2.24.0.jar differ diff --git a/language-server/bin/org.eclipse.xtend.lib.macro-2.24.0.jar b/language-server/bin/org.eclipse.xtend.lib.macro-2.24.0.jar new file mode 100644 index 0000000..e9ade4d Binary files /dev/null and b/language-server/bin/org.eclipse.xtend.lib.macro-2.24.0.jar differ diff --git a/language-server/bin/org.eclipse.xtext.xbase.lib-2.24.0.jar b/language-server/bin/org.eclipse.xtext.xbase.lib-2.24.0.jar new file mode 100644 index 0000000..afc2704 Binary files /dev/null and b/language-server/bin/org.eclipse.xtext.xbase.lib-2.24.0.jar differ diff --git a/language-server/bin/rcsh.jar b/language-server/bin/rcsh.jar new file mode 100644 index 0000000..6fe95ab Binary files /dev/null and b/language-server/bin/rcsh.jar differ diff --git a/language-server/bin/slf4j-api-1.7.30.jar b/language-server/bin/slf4j-api-1.7.30.jar new file mode 100644 index 0000000..29ac26f Binary files /dev/null and b/language-server/bin/slf4j-api-1.7.30.jar differ diff --git a/language-server/bin/slf4j-nop-1.7.30.jar b/language-server/bin/slf4j-nop-1.7.30.jar new file mode 100644 index 0000000..d4f5c08 Binary files /dev/null and b/language-server/bin/slf4j-nop-1.7.30.jar differ diff --git a/language-server/bundled-compiler/antlr-2.7.7.jar b/language-server/bundled-compiler/antlr-2.7.7.jar new file mode 100644 index 0000000..5e5f14b Binary files /dev/null and b/language-server/bundled-compiler/antlr-2.7.7.jar differ diff --git a/language-server/bundled-compiler/antlr-3.3.jar b/language-server/bundled-compiler/antlr-3.3.jar new file mode 100644 index 0000000..42aed12 Binary files /dev/null and b/language-server/bundled-compiler/antlr-3.3.jar differ diff --git a/language-server/bundled-compiler/antlr-complete-3.5.2.jar b/language-server/bundled-compiler/antlr-complete-3.5.2.jar new file mode 100644 index 0000000..260de76 Binary files /dev/null and b/language-server/bundled-compiler/antlr-complete-3.5.2.jar differ diff --git a/language-server/bundled-compiler/antlr-runtime-3.5.2.jar b/language-server/bundled-compiler/antlr-runtime-3.5.2.jar new file mode 100644 index 0000000..d48e3e8 Binary files /dev/null and b/language-server/bundled-compiler/antlr-runtime-3.5.2.jar differ diff --git a/language-server/bundled-compiler/commons-cli-1.2.jar b/language-server/bundled-compiler/commons-cli-1.2.jar new file mode 100644 index 0000000..ce4b9ff Binary files /dev/null and b/language-server/bundled-compiler/commons-cli-1.2.jar differ diff --git a/language-server/bundled-compiler/commons-codec-1.6.jar b/language-server/bundled-compiler/commons-codec-1.6.jar new file mode 100644 index 0000000..ee1bc49 Binary files /dev/null and b/language-server/bundled-compiler/commons-codec-1.6.jar differ diff --git a/language-server/bundled-compiler/commons-compress-1.11.jar b/language-server/bundled-compiler/commons-compress-1.11.jar new file mode 100644 index 0000000..71c92ce Binary files /dev/null and b/language-server/bundled-compiler/commons-compress-1.11.jar differ diff --git a/language-server/bundled-compiler/commons-io-2.4.jar b/language-server/bundled-compiler/commons-io-2.4.jar new file mode 100644 index 0000000..90035a4 Binary files /dev/null and b/language-server/bundled-compiler/commons-io-2.4.jar differ diff --git a/language-server/bundled-compiler/commons-lang-2.6.jar b/language-server/bundled-compiler/commons-lang-2.6.jar new file mode 100644 index 0000000..98467d3 Binary files /dev/null and b/language-server/bundled-compiler/commons-lang-2.6.jar differ diff --git a/language-server/bundled-compiler/commons-lang3-3.7.jar b/language-server/bundled-compiler/commons-lang3-3.7.jar new file mode 100644 index 0000000..f37ded6 Binary files /dev/null and b/language-server/bundled-compiler/commons-lang3-3.7.jar differ diff --git a/language-server/bundled-compiler/commons-logging-1.1.3.jar b/language-server/bundled-compiler/commons-logging-1.1.3.jar new file mode 100644 index 0000000..ab51254 Binary files /dev/null and b/language-server/bundled-compiler/commons-logging-1.1.3.jar differ diff --git a/language-server/bundled-compiler/compiler-0.9.8.jar b/language-server/bundled-compiler/compiler-0.9.8.jar new file mode 100644 index 0000000..3cc7d9d Binary files /dev/null and b/language-server/bundled-compiler/compiler-0.9.8.jar differ diff --git a/language-server/bundled-compiler/compiler-common-0.9.8.jar b/language-server/bundled-compiler/compiler-common-0.9.8.jar new file mode 100644 index 0000000..6647c74 Binary files /dev/null and b/language-server/bundled-compiler/compiler-common-0.9.8.jar differ diff --git a/language-server/bundled-compiler/compiler-externc-0.9.8.jar b/language-server/bundled-compiler/compiler-externc-0.9.8.jar new file mode 100644 index 0000000..0666e60 Binary files /dev/null and b/language-server/bundled-compiler/compiler-externc-0.9.8.jar differ diff --git a/language-server/bundled-compiler/compiler-jburg-types-1.1.0.jar b/language-server/bundled-compiler/compiler-jburg-types-1.1.0.jar new file mode 100644 index 0000000..96a82b3 Binary files /dev/null and b/language-server/bundled-compiler/compiler-jburg-types-1.1.0.jar differ diff --git a/language-server/bundled-compiler/compiler-jx-0.9.8.jar b/language-server/bundled-compiler/compiler-jx-0.9.8.jar new file mode 100644 index 0000000..0bcad65 Binary files /dev/null and b/language-server/bundled-compiler/compiler-jx-0.9.8.jar differ diff --git a/language-server/bundled-compiler/compiler-playerglobalc-0.9.8.jar b/language-server/bundled-compiler/compiler-playerglobalc-0.9.8.jar new file mode 100644 index 0000000..70003d9 Binary files /dev/null and b/language-server/bundled-compiler/compiler-playerglobalc-0.9.8.jar differ diff --git a/language-server/bundled-compiler/guava-25.1-jre.jar b/language-server/bundled-compiler/guava-25.1-jre.jar new file mode 100644 index 0000000..babc175 Binary files /dev/null and b/language-server/bundled-compiler/guava-25.1-jre.jar differ diff --git a/language-server/bundled-compiler/jburg-1.10.3.jar b/language-server/bundled-compiler/jburg-1.10.3.jar new file mode 100644 index 0000000..96005fd Binary files /dev/null and b/language-server/bundled-compiler/jburg-1.10.3.jar differ diff --git a/language-server/bundled-compiler/jflex-1.6.0.jar b/language-server/bundled-compiler/jflex-1.6.0.jar new file mode 100644 index 0000000..b22895c Binary files /dev/null and b/language-server/bundled-compiler/jflex-1.6.0.jar differ diff --git a/language-server/bundled-compiler/lzma-sdk-4j-9.22.0.jar b/language-server/bundled-compiler/lzma-sdk-4j-9.22.0.jar new file mode 100644 index 0000000..b1839df Binary files /dev/null and b/language-server/bundled-compiler/lzma-sdk-4j-9.22.0.jar differ diff --git a/language-server/frameworks/flex-config.xml b/language-server/frameworks/flex-config.xml new file mode 100644 index 0000000..9fdf129 --- /dev/null +++ b/language-server/frameworks/flex-config.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/language-server/playerglobal_docs/__Global__.xml b/language-server/playerglobal_docs/__Global__.xml new file mode 100644 index 0000000..dc9a13c --- /dev/null +++ b/language-server/playerglobal_docs/__Global__.xml @@ -0,0 +1,9376 @@ +__Global__VerifyError + + The VerifyError class represents an error that occurs when a malformed + or corrupted SWF file is encountered.An VerifyError is thrown when a malformed or corrupted SWF File is encountered. + + Error + The VerifyError class represents an error that occurs when a malformed + or corrupted SWF file is encountered. + + Loader classVerifyError + Creates a new VerifyError object.messageStringContains the message associated with the VerifyError object. + + + Creates a new VerifyError object. + ArgumentError + The ArgumentError class represents an error that occurs when the arguments + supplied in a function do not match the arguments defined for + that function.An ArgumentError is thrown when the parameter values supplied during a + function call do not match the parameters defined for that function. + + Error + The ArgumentError class represents an error that occurs when the arguments + supplied in a function do not match the arguments defined for + that function. This error occurs, for example, when a function is called with + the wrong number of arguments, an argument of the incorrect type, or an invalid argument. + + The following example shows how an ArgumentError error is + generated and handled within a try..catch statement. The + println() function takes one argument, a single string, but because two strings are supplied, + the error is thrown. + Typically, the compiler might catch such an error, but the this[] syntax in the try + statement bypasses the compiler's syntax checking for the function. + +package { + import flash.display.Sprite; + + public class ArgumentErrorExample extends Sprite { + public function ArgumentErrorExample() { + println("Hello World"); + + try { + this["println"]("Hello", "World"); + } + catch(e:ArgumentError) { + trace(e); + } + } + + public function println(str:String):void { + trace(str); + } + } +} +ArgumentError + Creates an ArgumentError object.messageStringA string associated with the error. + + + Creates an ArgumentError object. + QName + +QName objects represent qualified names of XML elements and attributes.Object + +QName objects represent qualified names of XML elements and attributes. Each +QName object has a local name and a namespace Uniform Resource Identifier (URI). +When the value of the namespace URI is null, the QName object matches any namespace. +Use the QName constructor to create a new QName object that is either a copy of another QName +object or a new QName object with a uri from a Namespace object and a +localName from a QName object. + + +

Methods specific to E4X can use QName objects interchangeably with strings. +E4X methods are in the QName, Namespace, XML, and XMLList classes. +These E4X methods, which take a string, can also take a QName object. +This interchangeability is how namespace support works with, for example, +the XML.child() method.

+ +

The QName class (along with the XML, XMLList, and Namespace classes) implements +powerful XML-handling standards defined in ECMAScript for XML +(E4X) specification (ECMA-357 edition 2).

+ +

A qualified identifier evaluates to a QName object. If the QName object of an XML element is +specified without identifying a namespace, the uri +property of the associated QName object is set to the global default namespace. If the QName object of an XML +attribute is specified without identifying a namespace, the uri property is set to +an empty string.

+ +
The following example shows how to create a QName instance and use it to select XML elements. + Two ways of creating a QName are shown: +
  1. Creating a Namespace instance and then using it as input to the QName constructor. + This approach is best if you want to use the Namespace.prefix property for other + purposes later.
  2. Creating a QName instance using a simple string value for the uri + parameter in the QName constructor.
+

+ This code does the following things: +

+
  1. Defines an XML variable named rssXML.
  2. Creates a new Namespace object with the prefix dc.
  3. Creates a new QName object using the Namespace object and the local name creator.
  4. Calls the showDescendants() method, which uses the XML.descendants() method to get an XMLList instance + containing all the descendant elements whose qualified name matches the given QName instance.
  5. Displays the qualified name and the text value of each element in the list using a for each loop.
  6. Creates another QName object using a string value for the uri parameter and the local name date.
  7. Calls the showDescendants() method again to display the name and text value of the descendant elements.
+ +package +{ + import flash.display.Sprite; + + public class QNameExample extends Sprite + { + public function QNameExample() + { + var rssXML:XML = <rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns="http://purl.org/rss/1.0/" + xmlns:dc="http://purl.org/dc/elements/1.1/"> + <channel rdf:about="http://www.xml.com/cs/xml/query/q/19"> + <title>Test RSS</title> + <link>http://www.adobe.com/</link> + <description>This is a test RSS document.</description> + <language>en-us</language> + <items> + <rdf:Seq> + <rdf:li rdf:resource="http://www.adobe.com/devnet/flash/"/> + <rdf:li rdf:resource="http://www.adobe.com/devnet/flex/"/> + </rdf:Seq> + </items> + </channel> + <item rdf:about="http://www.adobe.com/devnet/flash/"> + <title>Flash Developer Center</title> + <link>http://www.adobe.com/devnet/flash/</link> + <description>Welcome to the Flash Developer Center</description> + <dc:creator>Adobe</dc:creator> + <dc:date>2005-08-08</dc:date> + </item> + <item rdf:about="http://www.adobe.com/devnet/flex/"> + <title>Flex Developer Center</title> + <link>http://www.adobe.com/devnet/flex/</link> + <description>Welcome to the Flex Developer Center</description> + <dc:creator>Adobe</dc:creator> + <dc:date>2005-10-16</dc:date> + </item> + </rdf:RDF>; + + var dcNamespace:Namespace = new Namespace("dc", "http://purl.org/dc/elements/1.1/"); + var creatorQName:QName = new QName(dcNamespace, "creator"); + trace(creatorQName.uri); // http://purl.org/dc/elements/1.1/ + trace(creatorQName.localName); // creator + + showDescendants(rssXML, creatorQName); + + var dateQName:QName = new QName("http://purl.org/dc/elements/1.1/", "date"); + trace(dateQName.uri); // http://purl.org/dc/elements/1.1/ + trace(dateQName.localName); // date + + showDescendants(rssXML, dateQName); + } + + public function showDescendants(xmlData:XML, qualifiedName:QName):void + { + var decendantList:XMLList = xmlData.descendants(qualifiedName); + + for each (var element:XML in decendantList) + { + trace(element.name()); // the fully qualified name, + // like "http://purl.org/dc/elements/1.1/::creator" + trace(element); // the simple text value of each element, like "Adobe" + } + } + } +} +
XMLXMLListNamespaceECMAScript for XML (E4X) specification (ECMA-357 edition 2)QName + Creates a QName object that is a copy of another QName object.qnameQNameThe QName object to be copied. Objects of any other type are + converted to a string that is assigned to the localName property + of the new QName object. + + + Creates a QName object that is a copy of another QName object. If the parameter passed + to the constructor is a QName object, a copy of the QName object is created. If the parameter + is not a QName object, the parameter is converted to a string and assigned to the + localName property of the new QName instance. + If the parameter is undefined or unspecified, a new QName object + is created with the localName property set to the empty string. +

Note: This class shows two constructor entries because each form accepts + different parameters. The constructor behaves differently depending on the type and number of + parameters passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+ + +
QName + Creates a QName object with a URI object from a Namespace object and a localName from a QName object.uriNamespaceA Namespace object from which to copy the uri value. A parameter of any other type is converted to a string. + localNameQNameA QName object from which to copy the localName value. A parameter of any other type is converted to a string. + + + Creates a QName object with a URI object from a Namespace object and a localName from a QName object. + If either parameter is not the expected data type, the parameter is converted to a string and + assigned to the corresponding property of the new QName object. + For example, if both parameters are strings, a new QName object is returned with a uri property set + to the first parameter and a localName property set to the second parameter. + In other words, the following permutations, along with many others, are valid forms of the constructor: +
+QName (uri:Namespace, localName:String);
+QName (uri:String, localName: QName);
+QName (uri:String, localName: String);
+
+

If you pass null for the uri parameter, + the uri property of the new QName object is set to null. +

+

Note: This class shows two constructor entries because each form accepts + different parameters. The constructor behaves differently depending on the type and number of + parameters passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+ +
toString + Returns a string composed of the URI, and the local name for the + QName object, separated by "::".The qualified name, as a string. + + String + Returns a string composed of the URI, and the local name for the + QName object, separated by "::". + +

The format depends on the uri property of the QName object:

+
If uri == "" 
+		toString returns localName
+	else if uri == null
+		toString returns ~~::localName 
+	else
+		toString returns uri::localName
+ + +
valueOf + Returns the QName object.The primitive value of a QName instance. + + QName + Returns the QName object. + + localName + The local name of the QName object.String + The local name of the QName object. + + uri + The Uniform Resource Identifier (URI) of the QName object.String + The Uniform Resource Identifier (URI) of the QName object. + +
EvalError + The EvalError class represents an error that occurs when user code + calls the eval() function or attempts to use the new + operator with the Function object.An EvalError is thrown when code attempts to call eval() or use new with + the Function object. + + Error + The EvalError class represents an error that occurs when user code + calls the eval() function or attempts to use the new + operator with the Function object. Calling eval() and + calling new with the Function object are not supported. + + EvalError + Creates a new EvalError object.messageStringA string associated with the error. + + + Creates a new EvalError object. + Math + The Math class contains methods and constants that represent common mathematical + functions and values.The Math class is a top-level class consisting of static properties and + methods that define common mathematical constants and functions. + + Object + The Math class contains methods and constants that represent common mathematical + functions and values. +

Use the methods and properties of this class to access and manipulate mathematical constants and functions. + All the properties and methods of the Math class are static and must be called using the syntax + Math.method(parameter) or Math.constant. + In ActionScript, constants are defined with the maximum precision of double-precision IEEE-754 floating-point numbers.

+

Several Math class methods use the measure of an angle in radians as a parameter. You can use the following equation + to calculate radian values before calling the method and then provide the calculated value as the parameter, or you can + provide the entire right side of the equation (with the angle's measure in degrees in place of degrees) as + the radian parameter.

+

To calculate a radian value, use the following formula:

+
+ radians = degrees ~~ Math.PI/180
+ 
+

To calculate degrees from radians, use the following formula:

+
+ degrees = radians ~~ 180/Math.PI
+ 
+

The following is an example of passing the equation as a parameter to calculate the sine of a 45° angle:

+

Math.sin(45 ~~ Math.PI/180) is the same as Math.sin(.7854)

+

Note: The Math functions acos, asin, atan, atan2, cos, exp, log, pow, sin, and sqrt may + result in slightly different values depending on the algorithms + used by the CPU or operating system. Flash runtimes call on the CPU (or operating system if the CPU doesn't support + floating point calculations) when performing the calculations for the listed functions, and results have shown + slight variations depending upon the CPU or operating system in use. +

+ + +
abs + Computes and returns an absolute value for the number specified by the + parameter val.The absolute value of the specified paramater. + + NumbervalNumberThe number whose absolute value is returned. + Returns the absolute value of the specified Number. + + + Computes and returns an absolute value for the number specified by the + parameter val. + + acos + Computes and returns the arc cosine of the number specified in the + parameter val, in radians.The arc cosine of the parameter val. + + NumbervalNumberA number from -1.0 to 1.0. + + Returns the arc cosine, in radians, of the specified + Number. + + + Computes and returns the arc cosine of the number specified in the + parameter val, in radians. + + asin + Computes and returns the arc sine for the number specified in the + parameter val, in radians.A number between negative pi divided by 2 and positive pi + divided by 2. + + NumbervalNumberA number from -1.0 to 1.0. + + Returns the value, in radians, of the arc sine of the specified + Number parameter. + + + Computes and returns the arc sine for the number specified in the + parameter val, in radians. + + atan2 + Computes and returns the angle of the point y/x in + radians, when measured counterclockwise from a circle's x axis + (where 0,0 represents the center of the circle).A number. + + NumberyNumberThe y coordinate of the point. + xNumberThe x coordinate of the point. + + Returns the angle of the point y/x in radians, when measured + counterclockwise from a circle's x axis. + + + Computes and returns the angle of the point y/x in + radians, when measured counterclockwise from a circle's x axis + (where 0,0 represents the center of the circle). The return value is between + positive pi and negative pi. Note that the first parameter to atan2 is always the y coordinate. + + Math.acos()Math.asin()Math.atan()Math.cos()Math.sin()Math.tan()atan + Computes and returns the value, in radians, of the angle whose tangent is + specified in the parameter val.A number between negative pi divided by 2 and positive + pi divided by 2. + + NumbervalNumberA number that represents the tangent of an angle. + + Returns the angle, in radians, whose tangent is specified by + parameter val. + + + Computes and returns the value, in radians, of the angle whose tangent is + specified in the parameter val. The return value is between + negative pi divided by 2 and positive pi divided by 2. + + ceil + Returns the ceiling of the specified number or expression.An integer that is both closest to, and greater than or equal to, the parameter + val. + + NumbervalNumberA number or expression. + Returns the ceiling of the specified number or expression. + + + Returns the ceiling of the specified number or expression. The ceiling of a + number is the closest integer that is greater than or equal to the number. + + Math.floor()Math.round()cos + Computes and returns the cosine of the specified angle in radians.A number from -1.0 to 1.0. + + NumberangleRadiansNumberA number that represents an angle measured in radians. + Returns the cosine of the specified angle. + + + Computes and returns the cosine of the specified angle in radians. To + calculate a radian, see the overview of the Math class. + + + Math.acos()Math.asin()Math.atan()Math.atan2()Math.sin()Math.tan()exp + Returns the value of the base of the natural logarithm (e), to the + power of the exponent specified in the parameter x.e to the power of the parameter val. + + NumbervalNumberThe exponent; a number or expression. + Returns the value of the base of the natural logarithm + (e), to the power of the exponent specified in the parameter val. + + + Returns the value of the base of the natural logarithm (e), to the + power of the exponent specified in the parameter x. The + constant Math.E can provide the value of e. + + Math.Efloor + Returns the floor of the number or expression specified in the parameter + val.The integer that is both closest to, and less than or equal to, the parameter + val. + + NumbervalNumberA number or expression. + Returns the floor of the number or expression specified in the + parameter val. + + + Returns the floor of the number or expression specified in the parameter + val. The floor is the closest integer that is less than or equal + to the specified number or expression. + + log + Returns the natural logarithm of the parameter val.The natural logarithm of parameter val. + + NumbervalNumberA number or expression with a value greater than 0. + Returns the natural logarithm of parameter val. + + + Returns the natural logarithm of the parameter val. + + max + Evaluates val1 and val2 (or more values) and returns the largest value.The largest of the parameters val1 and val2 (or more values). + + Numberval1NumberA number or expression. + val2NumberA number or expression. + restA number or expression. Math.max() can accept multiple arguments. + Evaluates parameters val1 and val2 and + returns the larger value. + + + Evaluates val1 and val2 (or more values) and returns the largest value. + + Math.min()min + Evaluates val1 and val2 (or more values) and returns the smallest value.The smallest of the parameters val1 and val2 (or more values). + + Numberval1NumberA number or expression. + val2NumberA number or expression. + restA number or expression. Math.min() can accept multiple arguments. + Evaluates parameters val1 and val2 and returns the smaller value. + + + Evaluates val1 and val2 (or more values) and returns the smallest value. + + Math.max()pow + Computes and returns base to the power of pow.The value of base raised to the power of pow. + + NumberbaseNumberA number to be raised by the power of the parameter pow. + powNumberA number specifying the power that the parameter base is raised by. + Returns val1 to the power of val2. + + + Computes and returns base to the power of pow. + + random + Returns a pseudo-random number n, where 0 &lt;= n &lt; 1.A pseudo-random number. + + NumberReturns a pseudo-random number n, where 0 <= n < 1. + + + Returns a pseudo-random number n, where 0 <= n < 1. The number returned is calculated in an undisclosed manner, and is "pseudo-random" because the calculation inevitably contains some element of non-randomness. + + round + Rounds the value of the parameter val up or down to the nearest + integer and returns the value.The parameter val rounded to the nearest whole number. + + NumbervalNumberThe number to round. + Returns the value of parameter val rounded up or down to the + nearest integer. + + + Rounds the value of the parameter val up or down to the nearest + integer and returns the value. If val is equidistant + from its two nearest integers (that is, if the number ends in .5), the value + is rounded up to the next higher integer. + + Math.ceil()Math.floor()sin + Computes and returns the sine of the specified angle in radians.A number; the sine of the specified angle (between -1.0 and 1.0). + + NumberangleRadiansNumberA number that represents an angle measured in radians. + Returns the sine of the specified angle. + + + Computes and returns the sine of the specified angle in radians. To + calculate a radian, see the overview of the Math class. + + + Math.acos()Math.asin()Math.atan()Math.atan2()Math.cos()Math.tan()sqrt + Computes and returns the square root of the specified number.If the parameter val is greater than or equal to zero, a number; otherwise NaN (not a number). + + NumbervalNumberA number or expression greater than or equal to 0. + Returns the square root of the specified number. + + + Computes and returns the square root of the specified number. + + tan + Computes and returns the tangent of the specified angle.The tangent of the parameter angleRadians. + + NumberangleRadiansNumberA number that represents an angle measured in radians. + Returns the tangent of the specified angle. + + + Computes and returns the tangent of the specified angle. To calculate a + radian, see the overview of the Math class. + + + Math.acos()Math.asin()Math.atan()Math.atan2()Math.cos()Math.sin()E + A mathematical constant for the base of natural logarithms, expressed as e.2.71828182845905NumberA mathematical constant for the base of natural logarithms, expressed as e. + + + A mathematical constant for the base of natural logarithms, expressed as e. + The approximate value of e is 2.71828182845905. + + LN10 + A mathematical constant for the natural logarithm of 10, expressed as loge10, + with an approximate value of 2.302585092994046.2.302585092994046NumberA mathematical constant for the natural logarithm of 10, expressed + as loge10, with an approximate value of 2.302585092994046. + + + A mathematical constant for the natural logarithm of 10, expressed as loge10, + with an approximate value of 2.302585092994046. + + LN2 + A mathematical constant for the natural logarithm of 2, expressed as loge2, + with an approximate value of 0.6931471805599453.0.6931471805599453NumberA mathematical constant for the natural logarithm of 2, expressed + as loge2, with an approximate value of 0.6931471805599453. + + + A mathematical constant for the natural logarithm of 2, expressed as loge2, + with an approximate value of 0.6931471805599453. + + LOG10E + A mathematical constant for the base-10 logarithm of the constant e (Math.E), + expressed as log10e, with an approximate value of 0.4342944819032518.0.4342944819032518NumberA mathematical constant for the base-10 logarithm of the constant + e, expressed as log10e, with an approximate value of 0.4342944819032518. + + + A mathematical constant for the base-10 logarithm of the constant e (Math.E), + expressed as log10e, with an approximate value of 0.4342944819032518. +

The Math.log() method computes the natural logarithm of a number. Multiply the + result of Math.log() by Math.LOG10E to obtain the base-10 logarithm.

+ +
LOG2E + A mathematical constant for the base-2 logarithm of the constant e, expressed + as log2e, with an approximate value of 1.442695040888963387.1.442695040888963387NumberA mathematical constant for the base-2 logarithm of the constant + e, expressed as log2e, with an approximate value of 1.442695040888963387. + + + A mathematical constant for the base-2 logarithm of the constant e, expressed + as log2e, with an approximate value of 1.442695040888963387. + +

The Math.log method computes the natural logarithm of a number. Multiply the + result of Math.log() by Math.LOG2E to obtain the base-2 logarithm.

+ +
PI + A mathematical constant for the ratio of the circumference of a circle to its diameter, + expressed as pi, with a value of 3.141592653589793.3.141592653589793NumberA mathematical constant for the ratio of the circumference of a + circle to its diameter, expressed as pi, with a value of 3.141592653589793. + + + A mathematical constant for the ratio of the circumference of a circle to its diameter, + expressed as pi, with a value of 3.141592653589793. + + SQRT1_2 + A mathematical constant for the square root of one-half, with an approximate + value of 0.7071067811865476.0.7071067811865476NumberA mathematical constant for the square root of one-half, with an + approximate value of 0.7071067811865476. + + + A mathematical constant for the square root of one-half, with an approximate + value of 0.7071067811865476. + + SQRT2 + A mathematical constant for the square root of 2, with an approximate + value of 1.4142135623730951.1.4142135623730951NumberA mathematical constant for the square root of 2, with an + approximate value of 1.4142135623730951. + + + A mathematical constant for the square root of 2, with an approximate + value of 1.4142135623730951. + +
Array + The Array class lets you access and manipulate arrays.Lets you access and manipulate indexed arrays. + + Object + The Array class lets you access and manipulate arrays. Array indices are zero-based, which means that the first element in the array is [0], the second element is [1], and so on. To create an Array object, you use the new Array() constructor . Array() can also be + invoked as a function. In addition, you can use the array access ([]) operator to initialize an array or access the elements of an array. +

You can store a wide variety of data types in an array element, including numbers, strings, objects, and even other arrays. You can create a multidimensional array by creating an indexed array and assigning to each of its elements a different indexed array. Such an array is considered multidimensional because it can be used to represent data in a table.

+

Arrays are sparse arrays, meaning there might be an element at index 0 and another at index 5, but nothing in the index positions between those two elements. In such a case, the elements in positions 1 through 4 are undefined, which indicates the absence of an element, not necessarily the presence of an element with the value undefined.

+ +

Array assignment is by reference rather than by value. When you assign one array variable to another array variable, both refer to the same array:

+ + var oneArray:Array = new Array("a", "b", "c"); + var twoArray:Array = oneArray; // Both array variables refer to the same array. + twoArray[0] = "z"; + trace(oneArray); // Output: z,b,c. + +

Do not use the Array class to create associative arrays (also called hashes), which are data + structures that contain named elements instead of numbered elements. To create associative arrays, use the Object class. + Although ActionScript permits you to create associative arrays using the Array class, you cannot use any of the Array class methods or properties with associative arrays.

+

You can extend the Array class and override or add methods. However, you must specify the subclass as dynamic + or you will lose the ability to store data in an array.

+ +
The following example creates a new Array object myArr with no arguments + and an initial length of 0: + +package { + import flash.display.Sprite; + + public class ArrayExample extends Sprite { + public function ArrayExample() { + var myArr:Array = new Array(); + trace(myArr.length); // 0 + } + } +} +
[] (array access)Object classArray + Lets you create an array that contains the specified elements.The argument is a number that is not an integer greater than or equal to 0. + RangeErrorRangeErrorvaluesA comma-separated list of one or more arbitrary values. +

Note: If only a single numeric parameter is passed to the Array constructor, + it is assumed to specify the array's length property.

+
+ Lets you create an array that contains the specified elements. + You can specify values of any type. + The first element in an array always has an index (or position) of 0. +

Note: This class shows two constructor entries because the constructor accepts + variable types of arguments. The constructor behaves differently depending on the type and number of + arguments passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+
The following example creates a new Array object with an initial length of 3, + populates the array with the string elements one, two, and three, + and then converts the elements to a string. + +package { + import flash.display.Sprite; + + public class Array_Array_3 extends Sprite { + + public function Array_Array_3() { + var myArr:Array = new Array("one", "two", "three"); + trace(myArr.length); // 3 + trace(myArr); // one,two,three + } + } +} +
[] array accessArray.length
Array + Lets you create an array of the specified number of elements.The argument is a number that is not an integer greater than or equal to 0. + RangeErrorRangeErrornumElementsint0An integer that specifies the number of elements in the array. + + + Lets you create an array of the specified number of elements. + If you don't specify any parameters, an array containing 0 elements is created. + If you specify a number of elements, an array is created with numElements number of elements. +

Note: This class shows two constructor method entries because the constructor accepts + variable types of arguments. The constructor behaves differently depending on the type and number of + arguments passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+ + +
The following example creates the Array object myArr with no arguments + and an initial length of 0: + +package { + import flash.display.Sprite; + + public class Array_Array extends Sprite { + + public function Array_Array() { + var myArr:Array = new Array(); + trace(myArr.length); // 0 + } + } +} + The following example creates an Array object with 5 initial elements, with a length of 5, and populates + the first element with the string "one", and adds the string element "six" to the end + of the array by using the push() method: + +package { + import flash.display.Sprite; + + public class Array_Array_2 extends Sprite { + + public function Array_Array_2() { + var myArr:Array = new Array(5); + trace(myArr.length); // 5 + myArr[0] = "one"; + myArr.push("six"); + trace(myArr); // one,,,,,six + trace(myArr.length); // 6 + } + } +} +
[] array accessArray.length
concat + Concatenates the elements specified in the parameters with the elements in an array and creates a new array.An array that contains the elements from this array followed by elements from + the parameters. + + ArrayargsA value of any data type (such as numbers, elements, or strings) to be concatenated in a new array. + + Concatenates the elements specified in the parameters. + + + Concatenates the elements specified in the parameters with the elements in an array and creates a new array. + If the parameters specify an array, the elements of that array are concatenated. If you don't + pass any parameters, the new array is a duplicate (shallow clone) of the original array. + + The following code creates four Array objects: +
  • The numbers array, which contains the numbers 1, 2, and 3.
  • The letters array, which contains the letters a, b, and c.
  • The numbersAndLetters array, which calls the concat() method to produce the array [1,2,3,a,b,c].
  • The lettersAndNumbers array, which calls the concat() method to produce the array [a,b,c,1,2,3].
+ + +var numbers:Array = new Array(1, 2, 3); +var letters:Array = new Array("a", "b", "c"); +var numbersAndLetters:Array = numbers.concat(letters); +var lettersAndNumbers:Array = letters.concat(numbers); + +trace(numbers); // 1,2,3 +trace(letters); // a,b,c +trace(numbersAndLetters); // 1,2,3,a,b,c +trace(lettersAndNumbers); // a,b,c,1,2,3 +
every + Executes a test function on each item in the array until an item is reached that returns false for the + specified function.A Boolean value of true if all items in the array return true for the specified function; otherwise, false. + + BooleancallbackFunctionThe function to run on each item in the array. This function can contain a simple comparison (for example, item < 20) or a more complex operation, and is invoked with three arguments; the + value of an item, the index of an item, and the Array object: +
function callback(item:*, index:int, array:Array):Boolean;
+ +
thisObjectnullAn object to use as this for the function. +
+ Executes a test function on each item in the array until an item is reached that returns false for the + specified function. You use this method to determine whether all items in an array meet a criterion, such as having values + less than a particular number. + +

For this method, the second parameter, thisObject, must be null if the + first parameter, callback, is a method closure. Suppose you create a function in a movie clip + called me:

+
+     function myFunction(obj:Object):void {
+        //your code here
+     }
+     
+

Suppose you then use the every() method on an array called myArray:

+
+     myArray.every(myFunction, me);
+     
+

Because myFunction is a member of the Timeline class, which cannot be overridden + by me, the Flash runtime will throw an exception. + You can avoid this runtime error by assigning the function to a variable, as follows:

+
+     var myFunction:Function = function(obj:Object):void {
+         //your code here
+     };
+     myArray.every(myFunction, me);
+     
+ +
The following example tests two arrays to determine whether every item in each array is a number. It also outputs the results of the test, showing that isNumeric is true for the first array and false for the second: + +package { + import flash.display.Sprite; + public class Array_every extends Sprite { + public function Array_every() { + var arr1:Array = new Array(1, 2, 4); + var res1:Boolean = arr1.every(isNumeric); + trace("isNumeric:", res1); // true + + var arr2:Array = new Array(1, 2, "ham"); + var res2:Boolean = arr2.every(isNumeric); + trace("isNumeric:", res2); // false + } + private function isNumeric(element:*, index:int, arr:Array):Boolean { + return (element is Number); + } + } +} +
Array.some()
filter + Executes a test function on each item in the array and constructs a new array for all items that return true for the specified function.A new array that contains all items from the original array that returned true. + + ArraycallbackFunctionThe function to run on each item in the array. This function can contain a simple comparison (for example, item < 20) or a more complex operation, and is invoked with three arguments; the + value of an item, the index of an item, and the Array object: +
    function callback(item:*, index:int, array:Array):Boolean;
+ +
thisObjectnullAn object to use as this for the function. +
+ Executes a test function on each item in the array and constructs a new array for all items that return true for the specified function. If an item returns false, it is not included in the new array. + +

For this method, the second parameter, thisObject, must be null if the + first parameter, callback, is a method closure. Suppose you create a function in a movie clip + called me:

+
+     function myFunction(obj:Object):void {
+        //your code here
+     }
+     
+

Suppose you then use the filter() method on an array called myArray:

+
 
+     myArray.filter(myFunction, me);
+     
+

Because myFunction is a member of the Timeline class, which cannot be overridden + by me, the Flash runtime will throw an exception. + You can avoid this runtime error by assigning the function to a variable, as follows:

+
+     var myFunction:Function = function(obj:Object):void {
+         //your code here
+         };
+     myArray.filter(myFunction, me);
+     
+ +
The following example creates an array of all employees who are managers: + +package { + import flash.display.Sprite; + public class Array_filter extends Sprite { + public function Array_filter() { + var employees:Array = new Array(); + employees.push({name:"Employee 1", manager:false}); + employees.push({name:"Employee 2", manager:true}); + employees.push({name:"Employee 3", manager:false}); + trace("Employees:"); + employees.forEach(traceEmployee); + + var managers:Array = employees.filter(isManager); + trace("Managers:"); + managers.forEach(traceEmployee); + } + private function isManager(element:*, index:int, arr:Array):Boolean { + return (element.manager == true); + } + private function traceEmployee(element:*, index:int, arr:Array):void { + trace("\t" + element.name + ((element.manager) ? " (manager)" : "")); + } + } +} +
Array.map()
forEach + Executes a function on each item in the array.callbackFunctionThe function to run on each item in the array. This function can contain a simple command + (for example, a trace() statement) or a more complex operation, and is invoked with three arguments; the + value of an item, the index of an item, and the Array object: +
    function callback(item:*, index:int, array:Array):void;
+ +
thisObjectnullAn object to use as this for the function. + +
+ Executes a function on each item in the array. + +

For this method, the second parameter, thisObject, must be null if the + first parameter, callback, is a method closure. Suppose you create a function in a movie clip + called me:

+
+     function myFunction(obj:Object):void {
+        //your code here
+     }
+     
+

Suppose you then use the forEach() method on an array called myArray:

+
+     myArray.forEach(myFunction, me);
+     
+

Because myFunction is a member of the Timeline class, which cannot be overridden + by me, the Flash runtime will throw an exception. + You can avoid this runtime error by assigning the function to a variable, as follows:

+
+     var myFunction:Function = function(obj:Object):void {
+         //your code here
+         };
+     myArray.forEach(myFunction, me);
+     
+
The following example runs the trace() statement in the traceEmployee() function on each item in the array: + +package { + import flash.display.Sprite; + public class Array_forEach extends Sprite { + public function Array_forEach() { + var employees:Array = new Array(); + employees.push({name:"Employee 1", manager:false}); + employees.push({name:"Employee 2", manager:true}); + employees.push({name:"Employee 3", manager:false}); + trace(employees); + employees.forEach(traceEmployee); + } + private function traceEmployee(element:*, index:int, arr:Array):void { + trace(element.name + " (" + element.manager + ")"); + } + } +} + The following example also runs the trace() statement in a slightly altered traceEmployee() function on each item in the array: + +package { + import flash.display.Sprite; + public class Array_forEach_2 extends Sprite { + public function Array_forEach_2() { + var employeeXML:XML = <employees> + <employee name="Steven" manager="false" /> + <employee name="Bruce" manager="true" /> + <employee name="Rob" manager="false" /> + </employees>; + var employeesList:XMLList = employeeXML.employee; + var employeesArray:Array = new Array(); + for each (var tempXML:XML in employeesList) { + employeesArray.push(tempXML); + } + employeesArray.sortOn("@name"); + employeesArray.forEach(traceEmployee); + } + private function traceEmployee(element:*, index:Number, arr:Array):void { + trace(element.@name + ((element.@manager == "true") ? " (manager)" : "")); + } + } +} +
indexOf + Searches for an item in an array by using strict equality (===) and returns the index + position of the item.A zero-based index position of the item in the array. If the searchElement argument + is not found, the return value is -1. + + intsearchElementThe item to find in the array. + + fromIndexint0The location in the array from which to start searching for the item. + + Searches for an item in an array by using strict equality (===) and returns the index + position of the item. + The following example displays the position of the specified array: + +package { + import flash.display.Sprite; + public class Array_indexOf extends Sprite { + public function Array_indexOf() { + var arr:Array = new Array(123,45,6789); + arr.push("123-45-6789"); + arr.push("987-65-4321"); + + var index:int = arr.indexOf("123"); + trace(index); // -1 + + var index2:int = arr.indexOf(123); + trace(index2); // 0 + } + } +} +Array.lastIndexOf()=== (strict equality)join + Converts the elements in an array to strings, inserts the specified separator between the + elements, concatenates them, and returns the resulting string.A string consisting of the elements of an array + converted to strings and separated by the specified parameter. + + StringsepunknownA character or string that separates array elements in + the returned string. If you omit this parameter, a comma is used as the default + separator. + + Converts the elements in an array to strings. + + + Converts the elements in an array to strings, inserts the specified separator between the + elements, concatenates them, and returns the resulting string. A nested array is always + separated by a comma (,), not by the separator passed to the join() method. + + The following code creates an Array object myArr with elements one, + two, and three and then a string containing one and two and three + using the join() method. + + +var myArr:Array = new Array("one", "two", "three"); +var myStr:String = myArr.join(" and "); +trace(myArr); // one,two,three +trace(myStr); // one and two and three + The following code creates an Array object specialChars with elements (, + ), -, and a blank space and then creates a string containing (888) 867-5309. + Then, using a for loop, it removes each type of special character listed in specialChars to + produce a string (myStr) that contains only the digits of the phone number remaining: 888675309. + Note that other characters, such as +, could have been added to specialChars and then this + routine would work with international phone number formats. + + +var phoneString:String = "(888) 867-5309"; + +var specialChars:Array = new Array("(", ")", "-", " "); +var myStr:String = phoneString; + +var ln:uint = specialChars.length; +for(var i:uint; i < ln; i++) { + myStr = myStr.split(specialChars[i]).join(""); +} + +var phoneNumber:Number = new Number(myStr); + +trace(phoneString); // (888) 867-5309 +trace(phoneNumber); // 8888675309 +String.split()lastIndexOf + Searches for an item in an array, working backward from the last item, and returns the index position of the matching item using strict equality (===).A zero-based index position of the item in the array. If the searchElement argument is + not found, the return value is -1. + + intsearchElementThe item to find in the array. + + fromIndexint0x7fffffffThe location in the array from which to start searching for the item. The default is the maximum + value allowed for an index. If you do not specify fromIndex, the search starts at the last item + in the array. + + Searches for an item in an array, working backward from the last item, and returns the index position of the matching item using strict equality (===). + The following example displays the position of the specified array: + +package { + import flash.display.Sprite; + public class Array_lastIndexOf extends Sprite { + public function Array_lastIndexOf() { + var arr:Array = new Array(123,45,6789,123,984,323,123,32); + + var index:int = arr.indexOf(123); + trace(index); // 0 + + var index2:int = arr.lastIndexOf(123); + trace(index2); // 6 + } + } +} +Array.indexOf()=== (strict equality)map + Executes a function on each item in an array, and constructs a new array of items corresponding to the results of the function on + each item in the original array.A new array that contains the results of the function on each item in the original array. + + ArraycallbackFunctionThe function to run on each item in the array. This function can contain a simple command (such as changing the case of an array of strings) or a more complex operation, and is invoked with three arguments; the + value of an item, the index of an item, and the Array object: +
    function callback(item:*, index:int, array:Array):String;
+ +
thisObjectnullAn object to use as this for the function. +
+ Executes a function on each item in an array, and constructs a new array of items corresponding to the results of the function on + each item in the original array. + +

For this method, the second parameter, thisObject, must be null if the + first parameter, callback, is a method closure. Suppose you create a function in a movie clip + called me:

+
+     function myFunction(obj:Object):void {
+        //your code here
+     }
+     
+

Suppose you then use the map() method on an array called myArray:

+
+     myArray.map(myFunction, me);
+     
+

Because myFunction is a member of the Timeline class, which cannot be overridden + by me, the Flash runtime will throw an exception. + You can avoid this runtime error by assigning the function to a variable, as follows:

+
+     var myFunction:Function = function(obj:Object):void {
+         //your code here
+         };
+     myArray.map(myFunction, me);
+     
+
The following example changes all items in the array to use uppercase letters: + +package { + import flash.display.Sprite; + public class Array_map extends Sprite { + public function Array_map() { + var arr:Array = new Array("one", "two", "Three"); + trace(arr); // one,two,Three + + var upperArr:Array = arr.map(toUpper); + trace(upperArr); // ONE,TWO,THREE + } + private function toUpper(element:*, index:int, arr:Array):String { + return String(element).toUpperCase(); + } + } +} +
Array.filter()
pop + Removes the last element from an array and returns the value of that element.The value of the last element (of any data type) in the specified array. + + + Removes the last element from an array and returns the value of that element. + + The following code creates an Array object letters with elements a, + b, and c. The last element (c) is then removed from the array using the + pop() method and assigned to the String object letter. + + +var letters:Array = new Array("a", "b", "c"); +trace(letters); // a,b,c +var letter:String = letters.pop(); +trace(letters); // a,b +trace(letter); // c +Array.push()Array.shift()Array.unshift()push + Adds one or more elements to the end of an array and returns the new length of the array.An integer representing the length of the new array. + + uintargsOne or more values to append to the array. + + Adds one or more elements to the end of an array and returns the new length of the array. + + The following code creates an empty Array object letters and then populates the array + with the elements a, b, and c + using the push() method. + + +var letters:Array = new Array(); + +letters.push("a"); +letters.push("b"); +letters.push("c"); + +trace(letters.toString()); // a,b,c + The following code creates an Array object letters, which is initially + populated with the element a. The push() method + is then used once to add the elements b and c to the end of the array, + which is three elements after the push. + + +var letters:Array = new Array("a"); +var count:uint = letters.push("b", "c"); + +trace(letters); // a,b,c +trace(count); // 3 +Array.pop()Array.shift()Array.unshift()reverse + Reverses the array in place.The new array. + Array + Reverses the array in place. + + The following code creates an Array object letters with elements a, + b, and c. The order of the array elements is then reversed using the + reverse() method to produce the array [c,b,a]. + + +var letters:Array = new Array("a", "b", "c"); +trace(letters); // a,b,c +letters.reverse(); +trace(letters); // c,b,a +shift + Removes the first element from an array and returns that element.The first element (of any data type) in an array. + + + Removes the first element from an array and returns that element. The remaining array elements are moved + from their original position, i, to i-1. + + The following code creates the Array object letters with elements a, + b, and c. The shift() method is then used to remove the first + element (a) from letters and assign it to the string firstLetter. + + +var letters:Array = new Array("a", "b", "c"); +var firstLetter:String = letters.shift(); +trace(letters); // b,c +trace(firstLetter); // a +Array.pop()Array.push()Array.unshift()slice + Returns a new array that consists of a range of elements from the original array, without modifying the original array.An array that consists of a range of elements from the original array. + + ArraystartIndexint0A number specifying the index of the starting point + for the slice. If startIndex is a negative number, the starting + point begins at the end of the array, where -1 is the last element. + + endIndexint16777215A number specifying the index of the ending point for + the slice. If you omit this parameter, the slice includes all elements from the + starting point to the end of the array. If endIndex is a negative + number, the ending point is specified from the end of the array, where -1 is the + last element. + + Returns a new array that consists of a range of elements from the original array. + + + Returns a new array that consists of a range of elements from the original array, without modifying the original array. + The returned array includes the startIndex element and all elements up to, but not including, the endIndex element. + +

If you don't pass any parameters, the new array is a duplicate (shallow clone) of the original array.

+ +
The following code creates an Array object letters with elements + [a,b,c,d,e,f]. The array someLetters is then created by calling the + slice() method on elements one (b) through three (d), + resulting in an array with elements b and c. + + +var letters:Array = new Array("a", "b", "c", "d", "e", "f"); +var someLetters:Array = letters.slice(1,3); + +trace(letters); // a,b,c,d,e,f +trace(someLetters); // b,c + The following code creates an Array object letters with elements + [a,b,c,d,e,f].The array someLetters is then created by calling the + slice() method on element two (c), resulting in an array with elements + [c,d,e,f]. + + +var letters:Array = new Array("a", "b", "c", "d", "e", "f"); +var someLetters:Array = letters.slice(2); + +trace(letters); // a,b,c,d,e,f +trace(someLetters); // c,d,e,f + The following code creates an Array object letters with elements + [a,b,c,d,e,f]. The array someLetters is then created by calling the + slice() method on the second to last element from the end (e), resulting + in an array with elements e and f. + + +var letters:Array = new Array("a", "b", "c", "d", "e", "f"); +var someLetters:Array = letters.slice(-2); + +trace(letters); // a,b,c,d,e,f +trace(someLetters); // e,f +
some + Executes a test function on each item in the array until an item is reached that returns true.A Boolean value of true if any items in the array return true for the specified function; otherwise false. + + BooleancallbackFunctionThe function to run on each item in the array. This function can contain a simple comparison (for example + item < 20) or a more complex operation, and is invoked with three arguments; the + value of an item, the index of an item, and the Array object: +
    function callback(item:*, index:int, array:Array):Boolean;
+ +
thisObjectnullAn object to use as this for the function. +
+ Executes a test function on each item in the array until an item is reached that returns true. Use this method to determine whether any items in an array meet a criterion, such as having a value less than a particular number. + +

For this method, the second parameter, thisObject, must be null if the + first parameter, callback, is a method closure. Suppose you create a function in a movie clip + called me:

+
+     function myFunction(obj:Object):void {
+        //your code here
+     }
+     
+

Suppose you then use the some() method on an array called myArray:

+
+     myArray.some(myFunction, me);
+     
+

Because myFunction is a member of the Timeline class, which cannot be overridden + by me, the Flash runtime will throw an exception. + You can avoid this runtime error by assigning the function to a variable, as follows:

+
+     var myFunction:Function = function(obj:Object):void {
+         //your code here
+         };
+     myArray.some(myFunction, me);
+     
+
The following example displays which values are undefined: + +package { + import flash.display.Sprite; + public class Array_some extends Sprite { + public function Array_some() { + var arr:Array = new Array(); + arr[0] = "one"; + arr[1] = "two"; + arr[3] = "four"; + var isUndef:Boolean = arr.some(isUndefined); + if (isUndef) { + trace("array contains undefined values: " + arr); + } else { + trace("array contains no undefined values."); + } + } + private function isUndefined(element:*, index:int, arr:Array):Boolean { + return (element == undefined); + } + } +} +
every()
sortOn + Sorts the elements in an array according to one or more fields in the array.The return value depends on whether you pass any parameters: +
  • If you specify a value of 4 or Array.UNIQUESORT for the options parameter, and two or more elements being sorted have identical sort fields, a value of 0 is returned and the array is not modified.
  • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for the options parameter, an array is returned that reflects the results of the sort and the array is not modified.
  • Otherwise, nothing is returned and the array is modified to reflect the sort order.
+ +
Array
fieldNameObjectA string that identifies a field to be used as the sort value, or an + array in which the first element represents the primary sort field, the second represents + the secondary sort field, and so on. + + optionsObjectnullOne or more numbers or names of defined constants, separated by the bitwise OR (|) operator, that change the sorting behavior. The following values are acceptable for the options parameter: +
  • Array.CASEINSENSITIVE or 1
  • Array.DESCENDING or 2
  • Array.UNIQUESORT or 4
  • Array.RETURNINDEXEDARRAY or 8
  • Array.NUMERIC or 16
+

Code hinting is enabled if you use the string form of the flag (for example, DESCENDING) rather than the numeric form (2).

+ + +
+ Sorts the elements in an array according to one or more fields in the array. + The array should have the following characteristics: +
  • The array is an indexed array, not an associative array.
  • Each element of the array holds an object with one or more properties.
  • All of the objects have at least one property in common, the values of which can be used + to sort the array. Such a property is called a field.
+

If you pass multiple fieldName parameters, the first field represents the primary sort field, the second represents the next sort field, and so on. Flash sorts according to Unicode values. (ASCII is a subset of Unicode.) If either of the elements being compared does not contain the field that is specified in the fieldName parameter, the field is assumed to be set to undefined, and the elements are placed consecutively in the sorted array in no particular order.

+

By default, Array.sortOn() works in the following way:

+
  • Sorting is case-sensitive (Z precedes a).
  • Sorting is ascending (a precedes b).
  • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order.
  • Numeric fields are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".
+

Flash Player 7 added the options parameter, which you can use to override the default sort behavior. To sort a simple array (for example, an array with only one field), or to specify a sort order that the options parameter doesn't support, use Array.sort().

+

To pass multiple flags, separate them with the bitwise OR (|) operator:

+ + my_array.sortOn(someFieldName, Array.DESCENDING | Array.NUMERIC); + +

Flash Player 8 added the ability to specify a different sorting option for each field when you sort by more than one field. In Flash Player 8 and later, the options parameter accepts an array of sort options such that each sort option corresponds to a sort field in the fieldName parameter. The following example sorts the primary sort field, a, using a descending sort; the secondary sort field, b, using a numeric sort; and the tertiary sort field, c, using a case-insensitive sort:

+ + Array.sortOn (["a", "b", "c"], [Array.DESCENDING, Array.NUMERIC, Array.CASEINSENSITIVE]); + +

Note: The fieldName and options arrays must have the same number of elements; otherwise, the options array is ignored. Also, the Array.UNIQUESORT and Array.RETURNINDEXEDARRAY options can be used only as the first element in the array; otherwise, they are ignored.

+ +
The following code creates an empty Array object vegetables and the array + is then populated using five calls to push(). Each time push() is + called, a new Vegetable object is created by calling the Vegetable() + constructor, which accepts a String (name) and Number (price) object. + Calling push() five times with the values shown results in the following + array: [lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44]. The + sortOn() method is then used with the name parameter to produce the following array: + [asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44]. The + sortOn() method is then called again with the price parameter, and the + NUMERIC and DESCENDING constants to produce an array sorted by numbers in descending order: + [asparagus:3.99, spinach:1.89, lettuce:1.49, squash:1.44, celery:1.29]. + + +var vegetables:Array = new Array(); +vegetables.push(new Vegetable("lettuce", 1.49)); +vegetables.push(new Vegetable("spinach", 1.89)); +vegetables.push(new Vegetable("asparagus", 3.99)); +vegetables.push(new Vegetable("celery", 1.29)); +vegetables.push(new Vegetable("squash", 1.44)); + +trace(vegetables); +// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44 + +vegetables.sortOn("name"); +trace(vegetables); +// asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44 + +vegetables.sortOn("price", Array.NUMERIC | Array.DESCENDING); +trace(vegetables); +// asparagus:3.99, spinach:1.89, lettuce:1.49, squash:1.44, celery:1.29 + +class Vegetable { + public var name:String; + public var price:Number; + + public function Vegetable(name:String, price:Number) { + this.name = name; + this.price = price; + } + + public function toString():String { + return " " + name + ":" + price; + } +} + The following code creates an empty Array object records and the + array is then populated using three calls to push(). Each time push() is + called, the strings name and city and a zip number are + added to records. Three for loops are used to print the array elements. The + first for loop prints the elements in the order in which they were added. The second for + loop is run after records has been sorted by name and then city using the + sortOn() method. The third for loop produces different output because + records is re-sorted by city then by name. + + + +var records:Array = new Array(); +records.push({name:"john", city:"omaha", zip:68144}); +records.push({name:"john", city:"kansas city", zip:72345}); +records.push({name:"bob", city:"omaha", zip:94010}); + +for(var i:uint = 0; i < records.length; i++) { + trace(records[i].name + ", " + records[i].city); +} +// Results: +// john, omaha +// john, kansas city +// bob, omaha + +trace("records.sortOn('name', 'city');"); +records.sortOn(["name", "city"]); +for(var i:uint = 0; i < records.length; i++) { + trace(records[i].name + ", " + records[i].city); +} +// Results: +// bob, omaha +// john, kansas city +// john, omaha + +trace("records.sortOn('city', 'name');"); +records.sortOn(["city", "name"]); +for(var i:uint = 0; i < records.length; i++) { + trace(records[i].name + ", " + records[i].city); +} +// Results: +// john, kansas city +// bob, omaha +// john, omaha + The following code creates an empty Array object users and the + array is then populated using four calls to push(). Each time push() is + called, a User object is created with the User() constructor and a name + string and age uint are added to users. The resulting array set is + [Bob:3,barb:35,abcd:3,catchy:4]. +

The array is then sorted in the following ways: +

  1. By name only, producing the array [Bob:3,abcd:3,barb:35,catchy:4]
  2. By name and using the CASEINSENSITIVE constant, + producing the array [abcd:3,barb:35,Bob:3,catchy:4]
  3. By name and using the CASEINSENSITIVE and DESCENDING constants, + producing the array [catchy:4,Bob:3,barb:35,abcd:3]
  4. By age only, producing the array [abcd:3,Bob:3,barb:35,catchy:4]
  5. By age and using the NUMERIC constant, + producing the array [Bob:3,abcd:3,catchy:4,barb:35]
  6. By age and using the DESCENDING and NUMERIC constants, + producing the array [barb:35,catchy:4,Bob:3,abcd:3]
+

+

An array called indices is then created and assigned the results of a sort + by age and using the NUMERIC and RETURNINDEXEDARRAY constants, + resulting in the array [Bob:3,abcd:3,catchy:4,barb:35], which is then printed out + using a for loop.

+ + +class User { + public var name:String; + public var age:Number; + public function User(name:String, age:uint) { + this.name = name; + this.age = age; + } + + public function toString():String { + return this.name + ":" + this.age; + } +} + +var users:Array = new Array(); +users.push(new User("Bob", 3)); +users.push(new User("barb", 35)); +users.push(new User("abcd", 3)); +users.push(new User("catchy", 4)); + +trace(users); // Bob:3,barb:35,abcd:3,catchy:4 + +users.sortOn("name"); +trace(users); // Bob:3,abcd:3,barb:35,catchy:4 + +users.sortOn("name", Array.CASEINSENSITIVE); +trace(users); // abcd:3,barb:35,Bob:3,catchy:4 + +users.sortOn("name", Array.CASEINSENSITIVE | Array.DESCENDING); +trace(users); // catchy:4,Bob:3,barb:35,abcd:3 + +users.sortOn("age"); +trace(users); // abcd:3,Bob:3,barb:35,catchy:4 + +users.sortOn("age", Array.NUMERIC); +trace(users); // Bob:3,abcd:3,catchy:4,barb:35 + +users.sortOn("age", Array.DESCENDING | Array.NUMERIC); +trace(users); // barb:35,catchy:4,Bob:3,abcd:3 + +var indices:Array = users.sortOn("age", Array.NUMERIC | Array.RETURNINDEXEDARRAY); +var index:uint; +for(var i:uint = 0; i < indices.length; i++) { + index = indices[i]; + trace(users[index].name, ": " + users[index].age); +} + +// Results: +// Bob : 3 +// abcd : 3 +// catchy : 4 +// barb : 35 +
| (bitwise OR)Array.sort()
sort + Sorts the elements in an array.The return value depends on whether you pass any arguments, as described in + the following list: +
  • If you specify a value of 4 or Array.UNIQUESORT for the sortOptions argument + of the ...args parameter and two or more elements being sorted have identical sort fields, + Flash returns a value of 0 and does not modify the array.
  • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for + the sortOptions argument of the ...args parameter, Flash returns a sorted numeric + array of the indices that reflects the results of the sort and does not modify the array.
  • Otherwise, Flash returns nothing and modifies the array to reflect the sort order.
+ +
Array
argsThe arguments specifying a comparison function and one or more values that determine the behavior of the sort. +

This method uses the syntax and argument order Array.sort(compareFunction, sortOptions) with the arguments defined as follows:

+
  • compareFunction - A comparison function used to determine the sorting order of elements in an array. This argument is optional. A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value: +
    • A negative return value specifies that A appears before B in the sorted sequence.
    • A return value of 0 specifies that A and B have the same sort order.
    • A positive return value specifies that A appears after B in the sorted sequence.
    +
  • sortOptions - One or more numbers or defined constants, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. This argument is optional. The following values are acceptable for sortOptions: +
    • 1 or Array.CASEINSENSITIVE
    • 2 or Array.DESCENDING
    • 4 or Array.UNIQUESORT
    • 8 or Array.RETURNINDEXEDARRAY
    • 16 or Array.NUMERIC
    + For more information, see the Array.sortOn() method.
+ +
+ Sorts the elements in an array. This method sorts according to Unicode values. (ASCII is a subset of Unicode.) +

By default, Array.sort() works in the following way:

+
  • Sorting is case-sensitive (Z precedes a).
  • Sorting is ascending (a precedes b).
  • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order.
  • All elements, regardless of data type, are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".
+

+ To sort an array by using settings that deviate from the default settings, + you can either use one of the sorting options described in the sortOptions portion of the ...args parameter description, or you can create your own custom function to do the sorting. + If you create a custom function, you call the sort() method, and use the name + of your custom function as the first argument (compareFunction) +

+ +
The following code creates the Array object vegetables with elements + [spinach, green pepper, cilantro, onion, avocado]. The array is then sorted by + the sort() method, which is called with no parameters. The result is vegetables sorted in + alphabetical order ([avocado, cilantro, green pepper, onion, spinach]). + + +var vegetables:Array = new Array("spinach", + "green pepper", + "cilantro", + "onion", + "avocado"); + +trace(vegetables); // spinach,green pepper,cilantro,onion,avocado +vegetables.sort(); +trace(vegetables); // avocado,cilantro,green pepper,onion,spinach + The following code creates the Array object vegetables with elements + [spinach, green pepper, Cilantro, Onion, and Avocado]. The array is then sorted by + the sort() method, which is called with no parameters the first time; the result is + [Avocado,Cilantro,Onion,green pepper,spinach]. Then sort() is called on + vegetables again with the CASEINSENSITIVE constant as a parameter. + The result is vegetables sorted in alphabetical order + ([Avocado, Cilantro, green pepper, Onion, spinach]). + + +var vegetables:Array = new Array("spinach", + "green pepper", + "Cilantro", + "Onion", + "Avocado"); + +vegetables.sort(); +trace(vegetables); // Avocado,Cilantro,Onion,green pepper,spinach +vegetables.sort(Array.CASEINSENSITIVE); +trace(vegetables); // Avocado,Cilantro,green pepper,Onion,spinach + The following code creates the empty Array object vegetables, which is then + populated through five calls to push(). Each time push() is + called, a new Vegetable object is created by a call to the Vegetable() + constructor, which accepts a String (name) and Number (price) object. + Calling push() five times with the values shown results in the following + array: [lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44]. The + sort() method is then used to sort the array, resulting in the array + [asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44]. + +var vegetables:Array = new Array(); +vegetables.push(new Vegetable("lettuce", 1.49)); +vegetables.push(new Vegetable("spinach", 1.89)); +vegetables.push(new Vegetable("asparagus", 3.99)); +vegetables.push(new Vegetable("celery", 1.29)); +vegetables.push(new Vegetable("squash", 1.44)); + +trace(vegetables); +// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44 + +vegetables.sort(); + +trace(vegetables); +// asparagus:3.99, celery:1.29, lettuce:1.49, spinach:1.89, squash:1.44 + +//The following code defines the Vegetable class +class Vegetable { + private var name:String; + private var price:Number; + + public function Vegetable(name:String, price:Number) { + this.name = name; + this.price = price; + } + + public function toString():String { + return " " + name + ":" + price; + } +} + The following example is exactly the same as the previous one, except + that the sort() method is used with a custom sort function + (sortOnPrice), which sorts according to price instead of alphabetically. Note that the + new function getPrice() extracts the price. + + +var vegetables:Array = new Array(); +vegetables.push(new Vegetable("lettuce", 1.49)); +vegetables.push(new Vegetable("spinach", 1.89)); +vegetables.push(new Vegetable("asparagus", 3.99)); +vegetables.push(new Vegetable("celery", 1.29)); +vegetables.push(new Vegetable("squash", 1.44)); + +trace(vegetables); +// lettuce:1.49, spinach:1.89, asparagus:3.99, celery:1.29, squash:1.44 + +vegetables.sort(sortOnPrice); + +trace(vegetables); +// celery:1.29, squash:1.44, lettuce:1.49, spinach:1.89, asparagus:3.99 + +function sortOnPrice(a:Vegetable, b:Vegetable):Number { + var aPrice:Number = a.getPrice(); + var bPrice:Number = b.getPrice(); + + if(aPrice > bPrice) { + return 1; + } else if(aPrice < bPrice) { + return -1; + } else { + //aPrice == bPrice + return 0; + } +} + +// The following code defines the Vegetable class and should be in a separate package. +class Vegetable { + private var name:String; + private var price:Number; + + public function Vegetable(name:String, price:Number) { + this.name = name; + this.price = price; + } + + public function getPrice():Number { + return price; + } + + public function toString():String { + return " " + name + ":" + price; + } +} + The following code creates the Array object numbers with elements + [3,5,100,34,10]. A call to sort() without any parameters sorts + alphabetically, producing the undesired result [10,100,3,34,5]. To properly + sort numeric values, you must pass the constant NUMERIC to the sort() + method, which sorts numbers as follows: [3,5,10,34,100]. +

Note: The default behavior of the sort() function + is to handle each entity as a string. + If you use the Array.NUMERIC argument, the Flash runtime attempts to convert + any non-numeric values to integers for sorting purposes. If it fails, the runtime throws an error. + For example, the runtime can successfully convert a String value of "6" + to an integer, but will throw an error if it encounters a String value of "six".

+ + +var numbers:Array = new Array(3,5,100,34,10); + +trace(numbers); // 3,5,100,34,10 +numbers.sort(); +trace(numbers); // 10,100,3,34,5 +numbers.sort(Array.NUMERIC); +trace(numbers); // 3,5,10,34,100 +
| (bitwise OR)Array.sortOn()
splice + Adds elements to and removes elements from an array.An array containing the elements that were removed from the original array. + + ArraystartIndexintAn integer that specifies the index of the element in the array where the insertion or + deletion begins. You can use a negative integer to specify a position relative to the end of the array + (for example, -1 is the last element of the array). + deleteCountuintAn integer that specifies the number of elements to be deleted. This number includes the + element specified in the startIndex parameter. If you do not specify a value for the + deleteCount parameter, the method deletes all of the values from the startIndex + element to the last element in the array. If the value is 0, no elements are deleted. + valuesAn optional list of one or more comma-separated values + to insert into the array at the position specified in the startIndex parameter. + If an inserted value is of type Array, the array is kept intact and inserted as a single element. + For example, if you splice an existing array of length three with another array of length three, + the resulting array will have only four elements. One of the elements, however, will be an array of length three. + + + Adds elements to and removes elements from an array. This method modifies the array without + making a copy. +

Note: To override this method in a subclass of Array, use ...args for the parameters, + as this example shows:

+
+     public override function splice(...args) {
+       // your statements here
+     }
+     
+
The following code creates the Array object vegetables with the elements + [spinach, green pepper, cilantro, onion, avocado]. The splice() + method is then called with the parameters 2 and 2, which assigns + cilantro and onion to the spliced array. The + vegetables array then contains [spinach,green pepper,avocado]. The + splice() method is called a second time using the parameters 1, 0, + and the spliced array to assign + [cilantro,onion] as the second element in vegetables. + + +var vegetables:Array = new Array("spinach", + "green pepper", + "cilantro", + "onion", + "avocado"); + +var spliced:Array = vegetables.splice(2, 2); +trace(vegetables); // spinach,green pepper,avocado +trace(spliced); // cilantro,onion + +vegetables.splice(1, 0, spliced); +trace(vegetables); // spinach,cilantro,onion,green pepper,avocado + + Notice that cilantro and onion trace out as if vegetables + has 5 elements, even though it actually has four (and the second element is another array containing + two elements). To add cilantro and onion individually, you would use: + + +var vegetables:Array = new Array("spinach", + "green pepper", + "cilantro", + "onion", + "avocado"); + + var spliced:Array = vegetables.splice(2, 2); + trace(vegetables); // spinach,green pepper,avocado + trace(spliced); // cilantro,onion + + vegetables.splice(1, 0, "cilantro", "onion"); + trace(vegetables); // spinach,cilantro,onion,green pepper,avocado +
toLocaleString + Returns a string that represents the elements in the specified array.A string of array elements. + String + Returns a string that represents the elements in the specified array. Every element in the array, starting with index 0 and ending with the highest index, is converted to a concatenated string and separated by commas. In the ActionScript 3.0 implementation, this method returns the same value as the Array.toString() method. + + + Array.toString()toString + Returns a string that represents the elements in the specified array.A string of array elements. + + String + Returns a string that represents the elements in the specified array. Every element in the array, starting with index 0 and ending with the highest index, is converted to a concatenated string and separated by commas. To specify a custom separator, use the Array.join() method. + + + The following code creates an Array, converts the values to strings, and stores them in + the vegnums variable of the String data type. + + + +var vegetables:Array = new Array(); +vegetables.push(1); +vegetables.push(2); +vegetables.push(3); +vegetables.push(4); +vegetables.push(5); +var vegnums:String = vegetables.toString(); +trace(vegnums+",6"); +// 1,2,3,4,5,6 +String.split()Array.join()unshift + Adds one or more elements to the beginning of an array and returns the new length of the array.An integer representing the new length of the array. + + uintargsOne or more numbers, elements, or variables to be inserted at the beginning of the array. + + + Adds one or more elements to the beginning of an array and returns the new length of the array. The other + elements in the array are moved from their original position, i, to i+1. + + The following code creates the empty Array object names. + The strings Bill and Jeff are added by the push() method, + and then the strings Alfred and Kyle are added to the beginning of + names by two calls to the unshift() method. + + +var names:Array = new Array(); +names.push("Bill"); +names.push("Jeff"); + +trace(names); // Bill,Jeff + +names.unshift("Alfred"); +names.unshift("Kyle"); + +trace(names); // Kyle,Alfred,Bill,Jeff +Array.pop()Array.push()Array.shift()CASEINSENSITIVE + Specifies case-insensitive sorting for the Array class sorting methods.1uint + Specifies case-insensitive sorting for the Array class sorting methods. You can use this constant + for the options parameter in the sort() or sortOn() method. +

The value of this constant is 1.

+
Array.sort()Array.sortOn()
DESCENDING + Specifies descending sorting for the Array class sorting methods.2uint + Specifies descending sorting for the Array class sorting methods. + You can use this constant for the options parameter in the sort() + or sortOn() method. +

The value of this constant is 2.

+ +
Array.sort()Array.sortOn()
NUMERIC + Specifies numeric (instead of character-string) sorting for the Array class sorting methods.16uint + Specifies numeric (instead of character-string) sorting for the Array class sorting methods. + Including this constant in the options + parameter causes the sort() and sortOn() methods + to sort numbers as numeric values, not as strings of numeric characters. + Without the NUMERIC constant, sorting treats each array element as a + character string and produces the results in Unicode order. + +

For example, given the array of values [2005, 7, 35], if the NUMERIC + constant is not included in the options parameter, the + sorted array is [2005, 35, 7], but if the NUMERIC constant is included, + the sorted array is [7, 35, 2005].

+ +

This constant applies only to numbers in the array; it does + not apply to strings that contain numeric data such as ["23", "5"].

+ +

The value of this constant is 16.

+ +
Array.sort()Array.sortOn()
RETURNINDEXEDARRAY + Specifies that a sort returns an array that consists of array indices.8uint + Specifies that a sort returns an array that consists of array indices. You can use this constant + for the options parameter in the sort() or sortOn() + method, so you have access to multiple views of the array elements while the original array is unmodified. +

The value of this constant is 8.

+ +
Array.sort()Array.sortOn()
UNIQUESORT + Specifies the unique sorting requirement for the Array class sorting methods.4uint + Specifies the unique sorting requirement for the Array class sorting methods. + You can use this constant for the options parameter in the sort() or sortOn() + method. The unique sorting option terminates the sort if any two elements + or fields being sorted have identical values. +

The value of this constant is 4.

+ +
Array.sort()Array.sortOn()
length + A non-negative integer specifying the number of elements in the array.uint + A non-negative integer specifying the number of elements in the array. This property is automatically updated when new elements are added to the array. When you assign a value to an array element (for example, my_array[index] = value), if index is a number, and index+1 is greater than the length property, the length property is updated to index+1. +

Note: If you assign a value to the length property that is shorter than the existing length, the array will be truncated.

+ +
The following code creates an Array object names with the string element Bill. + It then uses the push() method to add another string element Kyle. The length of the array, as + determined by the length property, was one element before the use of push() and is two + elements after push() is called. Another string, Jeff, + is added to make the length of names three elements. The shift() method is then called twice + to remove Bill and Kyle, making the final array of length one. + + +var names:Array = new Array("Bill"); +names.push("Kyle"); +trace(names.length); // 2 + +names.push("Jeff"); +trace(names.length); // 3 + +names.shift(); +names.shift(); +trace(names.length); // 1 +
RegExp + + The RegExp class lets you work with regular expressions, which are patterns that you can use + to perform searches in strings and to replace text in strings.Object + + The RegExp class lets you work with regular expressions, which are patterns that you can use + to perform searches in strings and to replace text in strings. + +

You can create a new RegExp object by using the new RegExp() constructor or by + assigning a RegExp literal to a variable:

+ + var pattern1:RegExp = new RegExp("test-\\d", "i"); + var pattern2:RegExp = /test-\d/i; + + +

For more information, see "Using Regular Expressions" in the ActionScript 3.0 Developer's Guide.

+ +
The following example shows how you can use regular expressions to parse + strings and return a new string or a Boolean value, based on the string passed in. The + informalizeGreeting() method simply replaces the word Hello with Hi, + regardless of case. It also strips out the surname in the name in the string + (assuming that name matches the specified pattern). In the validateEmail() and + validatePhoneNumber() methods, the string passed is checked to see if its pattern matches a valid + email address or a specific phone number pattern, and the methods return Boolean values based on the results. + +package { + import flash.display.Sprite; + + public class RegExpExample extends Sprite { + public function RegExpExample() { + var formalGreeting:String = "Hello, John Smith."; + trace(informalizeGreeting(formalGreeting)); // Hi, John. + + var validEmail:String = "name@domain.com"; + trace(validateEmail(validEmail)); // true + + var invalidEmail:String = "foo"; + trace(validateEmail(invalidEmail)); // false + + var validPhoneNumber:String = "415-555-1212"; + trace(validatePhoneNumber(validPhoneNumber)); // true + + var invalidPhoneNumber:String = "312-867-530999"; + trace(validatePhoneNumber(invalidPhoneNumber)); // false + } + private function informalizeGreeting(str:String):String { + var pattern:RegExp = new RegExp("hello, (\\w+) \\w+", "i"); + return str.replace(pattern, "Hi, $1"); + } + private function validateEmail(str:String):Boolean { + var pattern:RegExp = /(\w|[_.\-])+@((\w|-)+\.)+\w{2,4}+/; + var result:Object = pattern.exec(str); + if(result == null) { + return false; + } + return true; + } + private function validatePhoneNumber(str:String):Boolean { + var pattern:RegExp = /^\d{3}-\d{3}-\d{4}$/; + var result:Object = pattern.exec(str); + if(result == null) { + return false; + } + return true; + } + } +} +
String.match()String.replace()String.search()RegExp + Lets you construct a regular expression from two strings.reStringThe pattern of the regular expression (also known as the constructor string). This is the + main part of the regular expression (the part that goes within the "/" characters). + +

Notes:

+ +
  • Do not include the starting and trailing "/" characters; use these only when defining a regular expression + literal without using the constructor. For example, the following two regular expressions are equivalent: + + var re1:RegExp = new RegExp("bob", "i"); + var re2:RegExp = /bob/i; + +
  • In a regular expression that is defined with the RegExp() constructor method, to use a + metasequence that begins with the backslash (\) character, such as \d (which matches any digit), + type the backslash character twice. For example, the following two regular expressions are equivalent: + + var re1:RegExp = new RegExp("\\d+", ""); + var re2:RegExp = /\d/; + +

    In the first expression, you must type the backlash character twice in this case, because the first parameter of the RegExp() + constructor method is a string, and in a string literal you must type a backslash character twice to have it + recognized as a single backslash character.

    + +
+ +
flagsStringThe modifiers of the regular expression. These can include the following: + +
  • g — When using the replace() method of the String class, + specify this modifier to replace all matches, rather than only the first one. + This modifier corresponds to the global property of the RegExp instance.
  • i — The regular expression is evaluated without case + sensitivity. This modifier corresponds to the ignoreCase property of the RegExp instance.
  • s — The dot (.) character matches new-line characters. Note + This modifier corresponds to the dotall property of the RegExp instance.
  • m — The caret (^) character and dollar sign ($) match + before and after new-line characters. This modifier corresponds to the + multiline property of the RegExp instance.
  • x — White space characters in the re string are ignored, + so that you can write more readable constructors. This modifier corresponds to the + extended property of the RegExp instance.
+ +

All other characters in the flags string are ignored.

+ +
+ Lets you construct a regular expression from two strings. One string defines the pattern of the + regular expression, and the other defines the flags used in the regular expression. + +
exec + Performs a search for the regular expression on the given string str.If there is no match, null; otherwise, an object with the following properties: + +
  • An array, in which element 0 contains the complete matching substring, and + other elements of the array (1 through n) contain substrings that match parenthetical groups + in the regular expression
  • index — The character position of the matched substring within + the string
  • input — The string (str)
+ + +
Object
strStringThe string to search. + +
+ Performs a search for the regular expression on the given string str. + +

If the g (global) flag is not set for the regular + expression, then the search starts + at the beginning of the string (at index position 0); the search ignores + the lastIndex property of the regular expression.

+ +

If the g (global) flag is set for the regular + expression, then the search starts + at the index position specified by the lastIndex property of the regular expression. + If the search matches a substring, the lastIndex property changes to match the position + of the end of the match.

+ +
When the g (global) flag is not set in the regular expression, then you can + use exec() to find the first match in the string: + + + var myPattern:RegExp = /(\w~~)sh(\w~~)/ig; + var str:String = "She sells seashells by the seashore"; + var result:Object = myPattern.exec(str); + trace(result); + + +

The result object is set to the following:

+ +
  • result[0] is set to "She" (the complete + match).
  • result[1] is set to an empty string (the first matching + parenthetical group).
  • result[2] is set to "e" (the second matching + parenthetical group).
  • result.index is set to 0.
  • result.input is set to the input string: "She sells seashells + by the seashore".
+ + + +

In the following example, the g (global) flag is set in the regular + expression, so you can use exec() repeatedly to find multiple matches:

+ + + var myPattern:RegExp = /(\w~~)sh(\w~~)/ig; + var str:String = "She sells seashells by the seashore"; + var result:Object = myPattern.exec(str); + + while (result != null) { + trace ( result.index, "\t", result); + result = myPattern.exec(str); + } + + +

This code results in the following output:

+ +

+            0      She,,e
+            10     seashells,sea,ells
+            27     seashore,sea,ore
+         
+ +
String.match()String.search()
test + Tests for the match of the regular expression in the given string str.If there is a match, true; otherwise, false. + + BooleanstrStringThe string to test. + + + Tests for the match of the regular expression in the given string str. + +

If the g (global) flag is not set for the regular expression, + then the search starts at the beginning of the string (at index position 0); the search ignores + the lastIndex property of the regular expression.

+ +

If the g (global) flag is set for the regular expression, then the search starts + at the index position specified by the lastIndex property of the regular expression. + If the search matches a substring, the lastIndex property changes to match the + position of the end of the match.

+ +
The following example shows the use of the test() method on a regular + expression in which the g (global) flag is set: + +var re1:RegExp = /\w/g; +var str:String = "a b c"; +trace (re1.lastIndex); // 0 +trace (re1.test(str)); // true +trace (re1.lastIndex); // 1 +trace (re1.test(str)); // true +trace (re1.lastIndex); // 3 +trace (re1.test(str)); // true +trace (re1.lastIndex); // 5 +trace (re1.test(str)); // false +
dotall + Specifies whether the dot character (.) in a regular expression pattern matches + new-line characters.Boolean + Specifies whether the dot character (.) in a regular expression pattern matches + new-line characters. Use the s flag when constructing + a regular expression to set dotall = true. + + The following example shows the effect of the s (dotall) + flag on a regular expression: + +var str:String = "<p>Hello\n" + + "again</p>" + + "<p>Hello</p>"; + +var pattern:RegExp = /<p>.*?<\/p>/; +trace(pattern.dotall) // false +trace(pattern.exec(str)); // <p>Hello</p> + +pattern = /<p>.*?<\/p>/s; +trace(pattern.dotall) // true +trace(pattern.exec(str)); + extended + Specifies whether to use extended mode for the regular expression.Boolean + Specifies whether to use extended mode for the regular expression. + When a RegExp object is in extended mode, white space characters in the constructor + string are ignored. This is done to allow more readable constructors. + +

Use the x flag when constructing a regular expression to set + extended = true.

+ +
The following example shows different ways to construct the same regular + expression. In each, the regular expression is to match a phone number pattern of + xxx-xxx-xxxx or (xxx) xxx-xxxx or (xxx)xxx-xxxx. + The second regular expression uses the x flag, causing the white spaces in + the string to be ignored. + +var rePhonePattern1:RegExp = /\d{3}-\d{3}-\d{4}|\(\d{3}\)\s?\d{3}-\d{4}/; +var str:String = "The phone number is (415)555-1212."; + +trace(rePhonePattern1.extended) // false +trace(rePhonePattern1.exec(str)); // (415)555-1212 + +var rePhonePattern2:RegExp = / \d{3}-\d{3}-\d{4} | \( \d{3} \) \ ? \d{3}-\d{4} /x; +trace(rePhonePattern2.extended) // true +trace(rePhonePattern2.exec(str)); // (415)555-1212 +
global + Specifies whether to use global matching for the regular expression.Boolean + Specifies whether to use global matching for the regular expression. When + global == true, the lastIndex property is set after a match is + found. The next time a match is requested, the regular expression engine starts from + the lastIndex position in the string. Use the g flag when + constructing a regular expression to set global to true. + + The following example shows the effect setting the g + (global) flag on the exec() method: + +var pattern:RegExp = /foo\d/; +var str:String = "foo1 foo2"; +trace(pattern.global); // false +trace(pattern.exec(str)); // foo1 +trace(pattern.lastIndex); // 0 +trace(pattern.exec(str)); // foo1 + +pattern = /foo\d/g; +trace(pattern.global); // true +trace(pattern.exec(str)); // foo1 +trace(pattern.lastIndex); // 4 +trace(pattern.exec(str)); // foo2 +ignoreCase + Specifies whether the regular expression ignores case sensitivity.Boolean + Specifies whether the regular expression ignores case sensitivity. Use the + i flag when constructing a regular expression to set + ignoreCase = true. + + The following example shows the effect of setting the i + (ignoreCase) flag: + +var pattern:RegExp = /bob/; +var str:String = "Bob bob"; +trace(pattern.ignoreCase); // false +trace(pattern.exec(str)); // bob + +pattern = /bob/i; +trace(pattern.ignoreCase); // true +trace(pattern.exec(str)); // Bob +lastIndex + Specifies the index position in the string at which to start the next search.Number + Specifies the index position in the string at which to start the next search. This property + affects the exec() and test() methods of the RegExp class. + However, the match(), replace(), and search() methods + of the String class ignore the lastIndex property and start all searches from + the beginning of the string. + +

When the exec() or test() method finds a match and the g + (global) flag is set to true for the regular expression, the method + automatically sets the lastIndex property to the index position of the character + after the last character in the matching substring of the last match. If the + g (global) flag is set to false, the method does not + set the lastIndexproperty.

+ +

You can set the lastIndex property to adjust the starting position + in the string for regular expression matching.

+ +
The following example shows the effect of setting the lastIndex + property, and it shows how it is updated after a call to the exec() method on a + regular expression in which the g (global) flag is set: + +var pattern:RegExp = /\w\d/g; +var str:String = "a1 b2 c3 d4"; +pattern.lastIndex = 2; +trace(pattern.exec(str)); // b2 +trace(pattern.lastIndex); // 5 +trace(pattern.exec(str)); // c3 +trace(pattern.lastIndex); // 8 +trace(pattern.exec(str)); // d4 +trace(pattern.lastIndex); // 11 +trace(pattern.exec(str)); // null +
multiline + Specifies whether the m (multiline) flag is set.Boolean + Specifies whether the m (multiline) flag is set. If it is set, + the caret (^) and dollar sign ($) in a regular expression + match before and after new lines. + Use the m flag when constructing a regular expression to set + multiline = true. + + The following example shows the effect setting the m (multiline) flag: + +var pattern:RegExp = /^bob/; +var str:String = "foo\n" + + "bob"; +trace(pattern.multiline); // false +trace(pattern.exec(str)); // null + +pattern = /^bob/m; +trace(pattern.multiline); // true +trace(pattern.exec(str)); // bob +source + Specifies the pattern portion of the regular expression.String + Specifies the pattern portion of the regular expression. + + The following code outputs the source parameter for two regular expressions: + +var re1:RegExp = /aabb/gi; +trace (re1.source); // aabb + +var re2:RegExp = new RegExp("x+y*", "i"); +trace(re2.source); // x+y* +
Date + The Date class represents date and time information.Object + The Date class represents date and time information. An instance of the Date class represents a particular point + in time for which the properties such as month, day, hours, and seconds can be queried or modified. The Date + class lets you retrieve date and time values relative to universal time (Greenwich mean time, now called universal + time or UTC) or relative to local time, which is determined by the local time zone setting on the operating system + that is running Flash Player. The methods of the Date class are not static but apply only to the individual Date + object specified when the method is called. The Date.UTC() and Date.parse() methods are + exceptions; they are static methods. +

The Date class handles daylight saving time differently, depending on the operating system and + runtime version. Flash Player 6 and later versions handle daylight saving time on the following operating + systems in these ways:

+
  • Windows - the Date object automatically adjusts its output for daylight saving time. The Date object detects + whether daylight saving time is employed in the current locale, and if so, it detects the standard-to-daylight + saving time transition date and times. However, the transition dates currently in effect are applied to dates in + the past and the future, so the daylight saving time bias might calculate incorrectly for dates in the past when + the locale had different transition dates.
  • Mac OS X - the Date object automatically adjusts its output for daylight saving time. The time zone information + database in Mac OS X is used to determine whether any date or time in the present or past should have a daylight + saving time bias applied.
  • Mac OS 9 - the operating system provides only enough information to determine whether the current date and + time should have a daylight saving time bias applied. Accordingly, the date object assumes that the current + daylight saving time bias applies to all dates and times in the past or future.
+

Flash Player 5 handles daylight saving time on the following operating systems as follows:

+
  • Windows - the U.S. rules for daylight saving time are always applied, which leads to incorrect transitions + in Europe and other areas that employ daylight saving time but have different transition times than the U.S. Flash + correctly detects whether daylight saving time is used in the current locale.
+

To use the Date class, construct a Date instance using the new operator.

+

ActionScript 3.0 adds several new accessor properties that can be used in place of many Date class methods + that access or modify Date instances. ActionScript 3.0 also includes several new variations of the + toString() method that are included for ECMA-262 3rd Edition compliance, including: + Date.toLocaleString(), Date.toTimeString(), Date.toLocaleTimeString(), + Date.toDateString(), and Date.toLocaleDateString().

+

To compute relative time or time elapsed, see the getTimer() method in the flash.utils package.

+ +
The following example shows various uses of the Date() constructor to assign the + following variables: +
  • myDate1 calls Date() with no parameters, which sets myDate1 to the + current date and time (according to your current system's date and time).
  • myDate2 calls Date() with the year (2000), month + (0 = January), and day (1) parameters passed to it.
  • myDate3 calls Date() with the year (65 = 1965), + month (2 = March), the day (6), the hour + (9), the minute (30), the second (15) + and the millisecond-+ (0) passed as parameters.
  • myDate4 calls Date() with the time value representing the number of milliseconds + before (since the value is negative) 0:00:00 GMT January 1, 1970.
+ + +package { + import flash.display.Sprite; + + public class DateExample extends Sprite{ + public function DateExample() { + var myDate1:Date = new Date(); + trace(myDate1); // [NOW] + + var myDate2:Date = new Date(2000, 0, 1); + trace(myDate2); // Sat Jan 1 00:00:00 GMT-0800 2000 + + var myDate3:Date = new Date(65, 2, 6, 9, 30, 15, 0); + trace(myDate3); // Sat Mar 6 09:30:15 GMT-0800 1965 + + var myDate4:Date = new Date(-14159025000); + trace(myDate4); // Sun Jul 20 19:56:15 GMT-0700 1969 + } + } +} +
flash.utils.getTimer()Date + Constructs a new Date object that holds the specified date and time.yearOrTimevalueObjectIf other parameters are specified, this number represents a + year (such as 1965); otherwise, it represents a time value. If the number represents a year, a + value of 0 to 99 indicates 1900 through 1999; otherwise all four digits of the year must be + specified. If the number represents a time value (no other parameters are specified), it is the + number of milliseconds before or after 0:00:00 GMT January 1, 1970; a negative values represents + a time before 0:00:00 GMT January 1, 1970, and a positive value represents a time after. + + monthNumberAn integer from 0 (January) to 11 (December). + + dateNumber1An integer from 1 to 31. + + hourNumber0An integer from 0 (midnight) to 23 (11 p.m.). + + minuteNumber0An integer from 0 to 59. + + secondNumber0An integer from 0 to 59. + + millisecondNumber0An integer from 0 to 999 of milliseconds. + + + Constructs a new Date object that holds the specified date and time. + +

The Date() constructor takes up to seven parameters (year, month, + ..., millisecond) to specify a date and time to the millisecond. The date that + the newly constructed Date object contains depends on the number, and data type, of arguments passed.

+
  • If you pass no arguments, the Date object is assigned the current date and time.
  • If you pass one argument of data type Number, the Date object is assigned a time value based on the number of milliseconds since January 1, 1970 0:00:000 GMT, as specified by the lone argument.
  • If you pass one argument of data type String, and the string contains a valid date, the Date object contains a time value based on that date.
  • If you pass two or more arguments, the Date object is assigned a time value based on the argument values passed, which represent the date's year, month, date, hour, minute, second, and milliseconds.
+

If you pass a string to the Date class constructor, the date can be in a variety of formats, but must at least include the month, date, and year. For example, Feb 1 2005 is valid, but Feb 2005 is not. The following list indicates some of the valid formats:

+
  • Day Month Date Hours:Minutes:Seconds GMT Year (for instance, "Tue Feb 1 00:00:00 GMT-0800 2005", which matches toString())
  • Day Month Date Year Hours:Minutes:Seconds AM/PM (for instance, "Tue Feb 1 2005 12:00:00 AM", which matches toLocaleString())
  • Day Month Date Year (for instance, "Tue Feb 1 2005", which matches toDateString())
  • Month/Day/Year (for instance, "02/01/2005")
  • Month/Year (for instance, "02/2005")
+
getMonth()getDate()getFullYear()
UTC + Returns the number of milliseconds between midnight on January 1, 1970, universal time, + and the time specified in the parameters.The number of milliseconds since January 1, 1970 and the specified date and time. + + NumberyearNumberA four-digit integer that represents the year (for example, 2000). + + monthNumberAn integer from 0 (January) to 11 (December). + + dateNumber1An integer from 1 to 31. + + hourNumber0An integer from 0 (midnight) to 23 (11 p.m.). + + minuteNumber0An integer from 0 to 59. + + secondNumber0An integer from 0 to 59. + + millisecondNumber0An integer from 0 to 999. + + + Returns the number of milliseconds between midnight on January 1, 1970, universal time, + and the time specified in the parameters. This method uses universal time, whereas the + Date constructor uses local time. +

This method is useful if you want to pass a UTC date to the Date class constructor. + Because the Date class constructor accepts the millisecond offset as an argument, you + can use the Date.UTC() method to convert your UTC date into the corresponding millisecond + offset, and send that offset as an argument to the Date class constructor:

+ +
The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20) using local + time. Then a call to UTC() within a setTime() method resets the same parameters + to universal time. + + +var someBirthday:Date = new Date(1974, 10, 30, 15, 20); +trace(someBirthday.toString()); + +someBirthday.setTime(Date.UTC(1974, 10, 30, 15, 20)); +trace(someBirthday.toString()); +
getDate + Returns the day of the month (an integer from 1 to 31) specified by a Date object + according to local time.The day of the month (1 - 31) a Date object represents. + + Number + Returns the day of the month (an integer from 1 to 31) specified by a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getDate() method is then called, which retrieves the day of the month. + +package { + import flash.display.Sprite; + + public class DateExample extends Sprite { + + public function DateExample() { + var someBirthday:Date = new Date(1974, 10, 30, 1, 20); + trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 + trace(someBirthday.getDate()); // 30 + } + } +} +getMonth()getFullYear()getDay + Returns the day of the week (0 for Sunday, 1 for Monday, and so on) specified by this + Date according to local time.A numeric version of the day of the week (0 - 6) a Date object + represents. + + Number + Returns the day of the week (0 for Sunday, 1 for Monday, and so on) specified by this + Date according to local time. Local time is determined by the operating + system on which the Flash runtimes are running. + + The following example creates a new Array object weekDayLabels, with elements + [Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday] and a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getDay() method is then called twice, which first shows the day of the month + as 6 and then shows the day of the week using weekDayLabels. + + +var weekDayLabels:Array = new Array("Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday"); + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getDay()); // 6 +trace(weekDayLabels[someBirthday.getDay()]); // Saturday +getFullYear + Returns the full year (a four-digit number, such as 2000) of a Date object + according to local time.The full year a Date object represents. + + Number + Returns the full year (a four-digit number, such as 2000) of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getFullYear() method is then called, which retrieves the four-digit year. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getFullYear()); // 1974 +getHours + Returns the hour (an integer from 0 to 23) of the day portion of a Date object + according to local time.The hour (0 - 23) of the day a Date object represents. + + Number + Returns the hour (an integer from 0 to 23) of the day portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getHours() and getMinutes() methods are then called, which + retrieves the hours and the minutes in 24-hour format. Finally, a string localTime + is created and assigned to the result of a call to the function getUSClockTime(), which, in turn calls + getHours() and getMinutes() again, resulting in the time 03:05 PM. + + +var someBirthday:Date = new Date(1974, 10, 30, 15, 5); + +trace(someBirthday); // Sat Nov 30 15:20:00 GMT-0800 1974 +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 15:5 + +var localTime:String = getUSClockTime(someBirthday.getHours(), someBirthday.getMinutes()); +trace(localTime); // 03:05 PM + +function getUSClockTime(hrs:uint, mins:uint):String { + var modifier:String = "PM"; + var minLabel:String = doubleDigitFormat(mins); + + if(hrs > 12) { + hrs = hrs-12; + } else if(hrs == 0) { + modifier = "AM"; + hrs = 12; + } else if(hrs < 12) { + modifier = "AM"; + } + + return (doubleDigitFormat(hrs) + ":" + minLabel + " " + modifier); +} + +function doubleDigitFormat(num:uint):String { + if(num < 10) { + return ("0" + num); + } + return num; +} +getMilliseconds + Returns the milliseconds (an integer from 0 to 999) portion of a Date object + according to local time.The milliseconds portion of a Date object. + + Number + Returns the milliseconds (an integer from 0 to 999) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object now with no parameters. + The getMilliseconds() method is then called, which retrieves the milliseconds of the + Date object now at the time it was created. + + +var now:Date = new Date(); +trace(now.getMilliseconds()); +getMinutes + Returns the minutes (an integer from 0 to 59) portion of a Date object + according to local time.The minutes portion of a Date object. + + Number + Returns the minutes (an integer from 0 to 59) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object now with no parameters. + The getMinutes() method is then called, which retrieves the minutes of the + Date object now at the time it was created. + + +var now:Date = new Date(); +trace(now); +trace(now.getMinutes()); +getMonth + Returns the month (0 for January, 1 for February, and so on) portion of this + Date according to local time.The month (0 - 11) portion of a Date object. + + Number + Returns the month (0 for January, 1 for February, and so on) portion of this + Date according to local time. Local time is determined by the operating system + on which the Flash runtimes are running. + + The following example creates a new Array object monthLabels, with elements + January through December and a new Date object now with no parameters. + The getMonth() method is then called twice, which first returns the month number and + then the month name of the month the Date object now was created. + + +var monthLabels:Array = new Array("January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"); + +var now:Date = new Date(); +trace(now.getMonth()); +trace(monthLabels[now.getMonth()]); +getSeconds + Returns the seconds (an integer from 0 to 59) portion of a Date object + according to local time.The seconds (0 to 59) portion of a Date object. + + Number + Returns the seconds (an integer from 0 to 59) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + The following example creates a new Date object now with no parameters. + The getSeconds() method is then called, which retrieves the seconds of the + Date object now at the time it was created. + + +var now:Date = new Date(); +trace(now.getSeconds()); +getTime + Returns the number of milliseconds since midnight January 1, 1970, universal time, + for a Date object.The number of milliseconds since Jan 1, 1970 that a Date object represents. + + Number + Returns the number of milliseconds since midnight January 1, 1970, universal time, + for a Date object. Use this method to represent a specific instant in time + when comparing two or more Date objects. + + The following example creates a new Date object mlk with parameters + year (1929), month (0 = January), and + day (15). The getTime() method is then called, which + retrieves the milliseconds since midnight January 1, 1970, which is negative since the year is + set to 1929. + + +var mlk:Date = new Date(1929, 0, 15); +trace(mlk); // Tue Jan 15 00:00:00 GMT-0800 1929 +trace(mlk.getTime()); // -1292601600000 + The following example creates a new Date object now with no parameters + and then uses the following DateMath (created below) class methods to add time to the original Date + object now from the time it was created: +
  • addSeconds(): adds 30 seconds to now.
  • addMinutes(): adds 30 minutes to now.
  • addHours(): adds 6 hours to the Date object now.
  • addDays(): adds 30 days to the Date object now.
  • addWeeks(): adds 4 weeks to now.
+ + + +var now:Date = new Date(); +trace(now); +trace(DateMath.addSeconds(now, 30)); +trace(DateMath.addMinutes(now, 30)); +trace(DateMath.addHours(now, 6)); +trace(DateMath.addDays(now, 30)); +trace(DateMath.addWeeks(now, 4)); + +class DateMath { + public static function addWeeks(date:Date, weeks:Number):Date { + return addDays(date, weeks*7); + } + + public static function addDays(date:Date, days:Number):Date { + return addHours(date, days*24); + } + + public static function addHours(date:Date, hrs:Number):Date { + return addMinutes(date, hrs*60); + } + + public static function addMinutes(date:Date, mins:Number):Date { + return addSeconds(date, mins*60); + } + + public static function addSeconds(date:Date, secs:Number):Date { + var mSecs:Number = secs * 1000; + var sum:Number = mSecs + date.getTime(); + return new Date(sum); + } +} + Note: it's important to use getTime when performing Date arithmetic because it will continue + to work during leap years and doesn't require a bunch of if logic like following pseudo-code: +
+ function addMonths(num:Number):void {
+     currentMonth = currentMonth + num;
+     if(currentMonth > 12) {
+         currentYear++;
+         currentMonth = currentMonth - 12;
+     }
+ }
+ 
+
getTimezoneOffset + Returns the difference, in minutes, between universal + time (UTC) and the computer's local time.The minutes you need to add to the computer's local time value to equal UTC. If + your computer's time is set later than UTC, the return value will be negative. + + Number + Returns the difference, in minutes, between universal + time (UTC) and the computer's local time. + + The following example creates a new Date object now with no parameters. + The getTimezoneOffset() method is then called, which retrieves the difference (in minutes) of the + time now was created and Universal Time. The time zone offset is then converted to hours by + dividing the result by 60. + + +var date:Date = new Date(); +trace(date.getTimezoneOffset() / 60); +getUTCDate + Returns the day of the month (an integer from 1 to 31) of a Date object, + according to universal time (UTC).The UTC day of the month (1 to 31) that a Date object represents. + + Number + Returns the day of the month (an integer from 1 to 31) of a Date object, + according to universal time (UTC). + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getUTCDate() method is then called, which retrieves the day of the month, according to the UTC. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getUTCDate()); // 30 +getDate()getUTCDay + Returns the day of the week (0 for Sunday, 1 for Monday, and so on) of this Date + according to universal time (UTC).The UTC day of the week (0 to 6) that a Date object represents. + + Number + Returns the day of the week (0 for Sunday, 1 for Monday, and so on) of this Date + according to universal time (UTC). + + The following example creates a new Array object weekDayLabels, with elements + [Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday] and a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getUTCDay() method is then called twice, which first shows the day of the month + as 6 and then shows the day of the week using weekDayLabels, according to the UTC. + + +var weekDayLabels:Array = new Array("Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday"); + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getUTCDay()); // 6 +trace(weekDayLabels[someBirthday.getUTCDay()]); // Saturday +getDay()getUTCFullYear + Returns the four-digit year of a Date object according to universal time (UTC).The UTC four-digit year a Date object represents. + + Number + Returns the four-digit year of a Date object according to universal time (UTC). + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getUTCFullYear() method is then called, which retrieves the four-digit year, according to the UTC. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getUTCFullYear()); // 1974 +getFullYear()getUTCHours + Returns the hour (an integer from 0 to 23) of the day of a Date object + according to universal time (UTC).The UTC hour of the day (0 to 23) a Date object represents. + + Number + Returns the hour (an integer from 0 to 23) of the day of a Date object + according to universal time (UTC). + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). + The getHours() and getMinutes() methods are then called, which retrieves + the hours and the minutes in 24-hour format. Finally, a string localTime is created and + assigned to the result of a call to the function getUSClockTime(), which, in turn calls + getHours() and getMinutes() again, resulting in the time 03:05 PM. + Lastly, a String variable utcTime is created in the same manner as localTime, + and in this case, the result is the same. + + +var someBirthday:Date = new Date(1974, 10, 30, 15, 5); + +trace(someBirthday); // Sat Nov 30 15:20:00 GMT-0800 1974 +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 15:5 + +var localTime:String = getUSClockTime(someBirthday.getHours(), someBirthday.getMinutes()); +trace(localTime); // 03:05 PM + +var utcTime:String = getUSClockTime(someBirthday.getUTCHours(), someBirthday.getUTCMinutes()); +trace(utcTime); // 11:05 PM + +function getUSClockTime(hrs:uint, mins:uint):String { + var modifier:String = "PM"; + var minLabel:String = doubleDigitFormat(mins); + + if(hrs > 12) { + hrs = hrs-12; + } else if(hrs == 0) { + modifier = "AM"; + hrs = 12; + } else if(hrs < 12) { + modifier = "AM"; + } + + return (doubleDigitFormat(hrs) + ":" + minLabel + " " + modifier); +} + +function doubleDigitFormat(num:uint):String { + if(num < 10) { + return ("0" + num); + } + return num; +} +getHours()getUTCMilliseconds + Returns the milliseconds (an integer from 0 to 999) portion of a Date object + according to universal time (UTC).The UTC milliseconds portion of a Date object. + + Number + Returns the milliseconds (an integer from 0 to 999) portion of a Date object + according to universal time (UTC). + + The following example creates a new Date object now with no parameters. + The getUTCMilliseconds() method is then called, which retrieves the milliseconds of the + Date object now at the time it was created, according to the UTC + + +var now:Date = new Date(); +trace(now.getUTCMilliseconds()); +getUTCMinutes + Returns the minutes (an integer from 0 to 59) portion of a Date object + according to universal time (UTC).The UTC minutes portion of a Date object. + + Number + Returns the minutes (an integer from 0 to 59) portion of a Date object + according to universal time (UTC). + + The following example creates a new Date object now with no parameters. + The getUTCMinutes() method is then called, which retrieves the minutes of the + Date object now at the time it was created, according to the UTC + + +var now:Date = new Date(); +trace(now.getUTCMinutes()); +getUTCMonth + Returns the month (0 [January] to 11 [December]) portion of a Date object + according to universal time (UTC).The UTC month portion of a Date object. + + Number + Returns the month (0 [January] to 11 [December]) portion of a Date object + according to universal time (UTC). + + The following example creates a new Array object monthLabels, with elements + January through December and a new Date object now with no parameters. + The getUTCMonth() method is then called twice, which first returns the month number and + then the month name of the month the Date object now was created, according to the UTC + + +var monthLabels:Array = new Array("January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"); + +var now:Date = new Date(); +trace(now.getMonth()); +trace(now.getUTCMonth()); +trace(monthLabels[now.getUTCMonth()]); +getMonth()getUTCSeconds + Returns the seconds (an integer from 0 to 59) portion of a Date object + according to universal time (UTC).The UTC seconds portion of a Date object. + + Number + Returns the seconds (an integer from 0 to 59) portion of a Date object + according to universal time (UTC). + + The following example creates a new Date object now with no parameters. + The getUTCSeconds() method is then called, which retrieves the seconds of the + Date object now at the time it was created, according to the UTC + + +var now:Date = new Date(); +trace(now.getUTCSeconds()); +parse + Converts a string representing a date into a number equaling the number of milliseconds + elapsed since January 1, 1970, UTC.A number representing the milliseconds elapsed since January 1, 1970, UTC. + + NumberdateStringA string representation of a date, which conforms to the format for the output of + Date.toString(). The date format for the output of Date.toString() is: +
+     Day Mon DD HH:MM:SS TZD YYYY
+     
+

For example:

+
+     Wed Apr 12 15:30:17 GMT-0700 2006
+     
+

The Time Zone Designation (TZD) is always in the form GMT-HHMM or UTC-HHMM indicating the + hour and minute offset relative to Greenwich Mean Time (GMT), which is now also called universal time (UTC). + The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a + dash (-). Other supported formats include the following (you can include partial representations of these + formats; that is, just the month, day, and year):

+
+     MM/DD/YYYY HH:MM:SS TZD
+     HH:MM:SS TZD Day Mon/DD/YYYY 
+     Mon DD YYYY HH:MM:SS TZD
+     Day Mon DD HH:MM:SS TZD YYYY
+     Day DD Mon HH:MM:SS TZD YYYY
+     Mon/DD/YYYY HH:MM:SS TZD
+     YYYY/MM/DD HH:MM:SS TZD
+     
+ +
+ Converts a string representing a date into a number equaling the number of milliseconds + elapsed since January 1, 1970, UTC. + + The following example assigns a date string to dateParsed for November 30, 1974. + The Date.parse() method is then called, which converts the date into milliseconds since January 1, 1970. + +var dateParsed:String = "Sat Nov 30 1974"; + +var milliseconds:Number = Date.parse(dateParsed); +trace(milliseconds); // 155030400000 +
Date.toString()
setDate + Sets the day of the month, according to local time, and returns the new time in + milliseconds.The new time, in milliseconds. + + NumberdayNumberAn integer from 1 to 31. + + + Sets the day of the month, according to local time, and returns the new time in + milliseconds. Local time is determined by the operating system on which the Flash runtimes are + running. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The + method getDate() is then called, which retrieves the day of the month. Next + setDate() is called with the day parameter set to 20 and + then getDate() is called again, which retrieves the newly set day of month. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getDate()); // 30 + +someBirthday.setDate(20); +trace(someBirthday.getDate()); // 20 +setFullYear + Sets the year, according to local time, and returns the new time in milliseconds.The new time, in milliseconds. + + NumberyearNumberA four-digit number specifying a year. Two-digit numbers do not represent + four-digit years; for example, 99 is not the year 1999, but the year 99. + + monthNumberAn integer from 0 (January) to 11 (December). + + dayNumberA number from 1 to 31. + + + Sets the year, according to local time, and returns the new time in milliseconds. If + the month and day parameters are specified, + they are set to local time. Local time is determined by the operating system on which + the Flash runtimes are running. +

+ Calling this method does not modify the other fields of the Date but + Date.getUTCDay() and Date.getDay() can report a new value + if the day of the week changes as a result of calling this method. +

+ +
The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The + method getFullYear() is then called, which retrieves the four-digit year. + Next setFullYear() is called with the year parameter set to + 2000 and then getFullYear() is called again, which retrieves the newly set year. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getFullYear()); // 1974 + +someBirthday.setFullYear(2000); +trace(someBirthday.getFullYear()); // 2000 +
getUTCDay()getDay()
setHours + Sets the hour, according to local time, and returns the new time in milliseconds.The new time, in milliseconds. + + NumberhourNumberAn integer from 0 (midnight) to 23 (11 p.m.). + minuteNumberAn integer from 0 to 59. + secondNumberAn integer from 0 to 59. + millisecondNumberAn integer from 0 to 999. + + + Sets the hour, according to local time, and returns the new time in milliseconds. + Local time is determined by the operating system on which the Flash runtimes are running. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The methods + getHours() and + getMinutes() are then called, which retrieves the hours and minutes. Next setHours() + is called with the hour parameter set to 12 and then getHours() and + getMinutes() are called again, which retrieves the newly set hours and minutes. + + +var someBirthday:Date = new Date(1974, 10, 30, 15, 20); + +trace(someBirthday); // Sat Nov 30 15:20:00 GMT-0800 1974 +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 15:20 + +someBirthday.setHours(12); +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 12:20 +setMilliseconds + Sets the milliseconds, according to local time, and returns the new time in + milliseconds.The new time, in milliseconds. + + NumbermillisecondNumberAn integer from 0 to 999. + + + Sets the milliseconds, according to local time, and returns the new time in + milliseconds. Local time is determined by the operating system on which the Flash runtimes are + running. + + The following example creates a new Date object now with no parameters. + The method getMilliseconds() is then called, which retrieves the milliseconds when + now was created. Then another new Date object before with an additional + call to setMilliseconds() with the millisecond parameter set to 4 and + getMilliseconds() is called again, which retrieves the newly set milliseconds. + + +var now:Date = new Date(); +trace(now); +trace(now.getMilliseconds()); + +var before:Date = new Date(now.setMilliseconds(4)); +trace(before); +trace(before.getMilliseconds()); +setMinutes + Sets the minutes, according to local time, and returns the new time in milliseconds.The new time, in milliseconds. + + NumberminuteNumberAn integer from 0 to 59. + secondNumberAn integer from 0 to 59. + millisecondNumberAn integer from 0 to 999. + + + Sets the minutes, according to local time, and returns the new time in milliseconds. + Local time is determined by the operating system on which the Flash runtimes are running. + + The following example creates a new Date object now with no parameters. + The method getMinutes() is then called, which retrieves the minutes when + now was created. Then another new Date object before with an additional + call to setMinutes() with the minute parameter set to 0 and + getMinutes() is called again, which retrieves the newly set minutes. + + +var now:Date = new Date(); +trace(now); +trace(now.getMinutes()); + +var before:Date = new Date(now.setMinutes(0)); +trace(before); +trace(before.getMinutes()); +setMonth + Sets the month and optionally the day of the month, according to local time, and + returns the new time in milliseconds.The new time, in milliseconds. + + NumbermonthNumberAn integer from 0 (January) to 11 (December). + + dayNumberAn integer from 1 to 31. + + + Sets the month and optionally the day of the month, according to local time, and + returns the new time in milliseconds. Local time is determined by the operating + system on which the Flash runtimes are running. + + The following example creates a new Array object monthLabels, with elements + January through December and a new month object now with no parameters. + The method getMonth() is then called, which retrieves the month in which + now was created. Next setMonth() is called with the month parameter set to + 0 and then getMonth() is called again, which retrieves the newly set month.. + + +var monthLabels:Array = new Array("January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"); + +var now:Date = new Date(); +trace(now.getMonth()); +trace(monthLabels[now.getMonth()]); + +now.setMonth(0); +trace(now.getMonth()); // 0 +trace(monthLabels[now.getMonth()]); // January +setSeconds + Sets the seconds, according to local time, and returns the new time in milliseconds.The new time, in milliseconds. + + NumbersecondNumberAn integer from 0 to 59. + millisecondNumberAn integer from 0 to 999. + + + Sets the seconds, according to local time, and returns the new time in milliseconds. + Local time is determined by the operating system on which the Flash runtimes are running. + + The following example creates a new Date object now with no parameters. + The method getseconds() is then called, which retrieves the seconds when + now was created. Then the setSeconds() is called with the second + parameter set to 0 and + getSeconds() is called again, which retrieves the newly set seconds. + + +var now:Date = new Date(); +trace(now.getSeconds()); + +now.setSeconds(0); +trace(now.getSeconds()); // 0 +setTime + Sets the date in milliseconds since midnight on January 1, 1970, and returns the new + time in milliseconds.The new time, in milliseconds. + + NumbermillisecondNumberAn integer value where 0 is midnight on January 1, universal time (UTC). + + + Sets the date in milliseconds since midnight on January 1, 1970, and returns the new + time in milliseconds. + + The following example creates a new Date object now with no parameters. + The setTime() method is then called, with the millisecond parameter set + to -1292601600000, which sets the time to Tue Jan 15 00:00:00 GMT-0800 1929. + + +var now:Date = new Date(); +trace(now); + +now.setTime(-1292601600000); +trace(now); // Tue Jan 15 00:00:00 GMT-0800 1929 +setUTCDate + Sets the day of the month, in universal time (UTC), and returns the new time in + milliseconds.The new time, in milliseconds. + + NumberdayNumberA number; an integer from 1 to 31. + + + Sets the day of the month, in universal time (UTC), and returns the new time in + milliseconds. Calling this method does not modify the other fields of a Date + object, but the Date.getUTCDay() and Date.getDay() methods can report + a new value if the day of the week changes as a result of calling this method. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The method + getUTCDate() is called and correctly returns the day of the month. Next setUTCDate() + is called with the day parameter set to 1 and a trace() statement + confirms the date was correctly set. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getUTCDate()); // 30 + +someBirthday.setUTCDate(1); +trace(someBirthday); // Fri Nov 1 01:20:00 GMT-0800 1974 +getUTCDay()getDay()setUTCFullYear + Sets the year, in universal time (UTC), and returns the new time in milliseconds.An integer. + + NumberyearNumberAn integer that represents the year specified as a full four-digit year, + such as 2000. + + monthNumberAn integer from 0 (January) to 11 (December). + + dayNumberAn integer from 1 to 31. + + + Sets the year, in universal time (UTC), and returns the new time in milliseconds. +

+ Optionally, this method can also set the month and day of the month. Calling + this method does not modify the other fields, but the Date.getUTCDay() and + Date.getDay() methods can report a new value if the day of the week changes as a + result of calling this method. +

+ +
The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The method + getUTCFullYear() is called and correctly returns the four-digit year. Next setUTCFullYear() + is called with the year parameter set to 1975 and a trace() statement + confirms the year was correctly set. + + +var someBirthday:Date = new Date(1974, 10, 30, 1, 20); +trace(someBirthday); // Sat Nov 30 01:20:00 GMT-0800 1974 +trace(someBirthday.getUTCFullYear()); // 1974 + +someBirthday.setUTCFullYear(1975); +trace(someBirthday); // Thu Nov 30 01:20:00 GMT-0800 1975 +
getUTCDay()getDay()
setUTCHours + Sets the hour, in universal time (UTC), and returns the new time in milliseconds.The new time, in milliseconds. + + NumberhourNumberAn integer from 0 (midnight) to 23 (11 p.m.). + + minuteNumberAn integer from 0 to 59. + + secondNumberAn integer from 0 to 59. + + millisecondNumberAn integer from 0 to 999. + + + Sets the hour, in universal time (UTC), and returns the new time in milliseconds. + Optionally, the minutes, seconds, and milliseconds can be specified. + + The following example creates a new Date object someBirthday with parameters + year (1974), month (10 = November), day + (30), hour (1) and minute (20). The methods + getHours(), getMinutes(), getUTCHours(), and getUTCMinutes() + are then called, which retrieves the hours and minutes. Next setUTCHours() is called with the + hour parameter set to 12 and then the methods getHours(), + getMinutes(), getUTCHours(), and getUTCMinutes() are re-called and + correctly display the updated hour. + + +var someBirthday:Date = new Date(1974, 10, 30, 15, 20); + +trace(someBirthday); // Sat Nov 30 15:20:00 GMT-0800 1974 +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 15:20 +trace(someBirthday.getUTCHours() + ":" + someBirthday.getUTCMinutes()); // 23:20 + +someBirthday.setUTCHours(12); +trace(someBirthday.getHours() + ":" + someBirthday.getMinutes()); // 4:20 +trace(someBirthday.getUTCHours() + ":" + someBirthday.getUTCMinutes()); // 12:20 +setUTCMilliseconds + Sets the milliseconds, in universal time (UTC), and returns the new time in milliseconds.The new time, in milliseconds. + + NumbermillisecondNumberAn integer from 0 to 999. + + + Sets the milliseconds, in universal time (UTC), and returns the new time in milliseconds. + + The following example creates a new Date object now with no parameters. + The method getUTCMilliseconds() is then called, which retrieves the UTCMilliseconds when + now was created. Then another new Date object before with an additional + call to setUTCMilliseconds() with the millisecond parameter set to 4 and + getUTCMilliseconds() is called again, which retrieves the newly set milliseconds. + + + +var now:Date = new Date(); +trace(now); +trace(now.getUTCMilliseconds()); + +var before:Date = new Date(now.setUTCMilliseconds(4)); +trace(before); +trace(before.getUTCMilliseconds()); +setUTCMinutes + Sets the minutes, in universal time (UTC), and returns the new time in milliseconds.The new time, in milliseconds. + + NumberminuteNumberAn integer from 0 to 59. + + secondNumberAn integer from 0 to 59. + + millisecondNumberAn integer from 0 to 999. + + + Sets the minutes, in universal time (UTC), and returns the new time in milliseconds. + Optionally, you can specify the seconds and milliseconds. + + The following example creates a new Date object now with no parameters. + The method getUTCMinutes() is then called, which retrieves the UTCMinutes when + now was created. Then another new Date object before with an additional + call to setUTCMinutes() with the minute parameter set to 0 and + getUTCMinutes() is called again, which retrieves the newly set minutes. + + +var now:Date = new Date(); +trace(now); +trace(now.getUTCMinutes()); + +var before:Date = new Date(now.setUTCMinutes(0)); +trace(before); +trace(before.getUTCMinutes()); +setUTCMonth + Sets the month, and optionally the day, in universal time(UTC) and returns the new + time in milliseconds.The new time, in milliseconds. + + NumbermonthNumberAn integer from 0 (January) to 11 (December). + + dayNumberAn integer from 1 to 31. + + + Sets the month, and optionally the day, in universal time(UTC) and returns the new + time in milliseconds. Calling this method does not modify the other fields, but the + Date.getUTCDay() and Date.getDay() methods might report a new + value if the day of the week changes as a result of calling this method. + + The following example creates a new Array object UTCMonthLabels, with elements + January through December and a new UTCMonth object now with no parameters. + The method getUTCMonth() is then called, which retrieves the UTCMonth in which + now was created. Next setUTCMonth() is called with the month parameter set to + 0 and then getUTCMonth() is called again, which retrieves the newly set month.. + + +var UTCMonthLabels:Array = new Array("January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December"); + +var now:Date = new Date(); +trace(now.getUTCMonth()); +trace(UTCMonthLabels[now.getUTCMonth()]); + +now.setUTCUTCMonth(0); +trace(now.getUTCMonth()); // 0 +trace(UTCMonthLabels[now.getUTCMonth()]); // January +getDay()setUTCSeconds + Sets the seconds, and optionally the milliseconds, in universal time (UTC) and + returns the new time in milliseconds.The new time, in milliseconds. + + NumbersecondNumberAn integer from 0 to 59. + + millisecondNumberAn integer from 0 to 999. + + + Sets the seconds, and optionally the milliseconds, in universal time (UTC) and + returns the new time in milliseconds. + + The following example creates a new Date object now with no parameters. + The method getUTCSeconds() is then called, which retrieves the seconds when + now was created. Then the setUTCSeconds() is called with the second + parameter set to 0 and getUTCSeconds() is called again, which retrieves the + newly set seconds. + + +var now:Date = new Date(); +trace(now.getUTCSeconds()); + +now.setUTCSeconds(0); +trace(now.getUTCSeconds()); // 0 +toDateString + Returns a string representation of the day and date only, and does not include the time or timezone.The string representation of day and date only. + + String + Returns a string representation of the day and date only, and does not include the time or timezone. + Contrast with the following methods: +
  • Date.toTimeString(), which returns only the time and timezone
  • Date.toString(), which returns not only the day and date, but also the time and timezone.
+ +
The following example creates a new Date object now with no parameters + and then the following methods are called within a trace() statement +
  • toString: displays all parameters for now at the time now was created.
  • toDateString(): displays the day, month, and year parameters + for the time now was created.
+ + +var now:Date = new Date(); +trace(now); +trace(now.toDateString()); +
toString()
toLocaleDateString + Returns a String representation of the day and date only, and does not include the time or timezone.The String representation of day and date only. + + String + Returns a String representation of the day and date only, and does not include the time or timezone. + This method returns the same value as Date.toDateString. + Contrast with the following methods: +
  • Date.toTimeString(), which returns only the time and timezone
  • Date.toString(), which returns not only the day and date, but also the + time and timezone.
+ +
toDateString()toTimeString()toString()
toLocaleString + Returns a String representation of the day, date, time, given in local time.A string representation of a Date object in the local timezone. + + + String + Returns a String representation of the day, date, time, given in local time. + Contrast with the Date.toString() method, which returns the same information (plus the timezone) + with the year listed at the end of the string. + + toLocaleTimeString + Returns a String representation of the time only, and does not include the day, date, year, or timezone.The string representation of time and timezone only. + + String + Returns a String representation of the time only, and does not include the day, date, year, or timezone. + Contrast with the Date.toTimeString() method, which returns the time and timezone. + + toTimeString()toString + Returns a String representation of the day, date, time, and timezone.The string representation of a Date object. + + String + Returns a String representation of the day, date, time, and timezone. + The date format for the output is: +
+     Day Mon Date HH:MM:SS TZD YYYY
+     
+

For example:

+
+     Wed Apr 12 15:30:17 GMT-0700 2006
+     
+ +
The following example creates a new Date object now with no parameters + and then toString is called within a trace() statement, which + displays all parameters for now at the time now was created. + + + +var now:Date = new Date(); +trace(now); +
toTimeString + Returns a String representation of the time and timezone only, and does not include the day and date.The string representation of time and timezone only. + + String + Returns a String representation of the time and timezone only, and does not include the day and date. + Contrast with the Date.toDateString() method, which returns only the day and date. + + toDateString()toUTCString + Returns a String representation of the day, date, and time in universal time (UTC).The string representation of a Date object in UTC time. + + String + Returns a String representation of the day, date, and time in universal time (UTC). + For example, the date February 1, 2005 is returned as Tue Feb 1 00:00:00 2005 UTC. + + toString()valueOf + Returns the number of milliseconds since midnight January 1, 1970, universal time, + for a Date object.The number of milliseconds since January 1, 1970 that a Date object represents. + + Number + Returns the number of milliseconds since midnight January 1, 1970, universal time, + for a Date object. + + The following example creates a new Date object now with no parameters + The getTime() method is then called, which retrieves the number of milliseconds between + the time now was created and midnight on + January 1, 1970, and then valueOf() is called, which retrieves the same thing. + + + +var now:Date = new Date(); +trace(now.getTime()); +trace(now.valueOf()); +dateUTC + The day of the month (an integer from 1 to 31) of a Date object + according to universal time (UTC).Number + The day of the month (an integer from 1 to 31) of a Date object + according to universal time (UTC). + + getUTCDate()setUTCDate()date + The day of the month (an integer from 1 to 31) specified by a Date object + according to local time.Number + The day of the month (an integer from 1 to 31) specified by a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getDate()setDate()dayUTC + The day of the week (0 for Sunday, 1 for Monday, and so on) of this Date + according to universal time (UTC).Number + The day of the week (0 for Sunday, 1 for Monday, and so on) of this Date + according to universal time (UTC). + + getUTCDay()day + The day of the week (0 for Sunday, 1 for Monday, and so on) specified by this + Date according to local time.Number + The day of the week (0 for Sunday, 1 for Monday, and so on) specified by this + Date according to local time. Local time is determined by the operating + system on which the Flash runtimes are running. + + getDay()fullYearUTC + The four-digit year of a Date object according to universal time (UTC).Number + The four-digit year of a Date object according to universal time (UTC). + + getUTCFullYear()setUTCFullYear()fullYear + The full year (a four-digit number, such as 2000) of a Date object + according to local time.Number + The full year (a four-digit number, such as 2000) of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getFullYear()setFullYear()hoursUTC + The hour (an integer from 0 to 23) of the day of a Date object + according to universal time (UTC).Number + The hour (an integer from 0 to 23) of the day of a Date object + according to universal time (UTC). + + getUTCHours()setUTCHours()hours + The hour (an integer from 0 to 23) of the day portion of a Date object + according to local time.Number + The hour (an integer from 0 to 23) of the day portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getHours()setHours()millisecondsUTC + The milliseconds (an integer from 0 to 999) portion of a Date object + according to universal time (UTC).Number + The milliseconds (an integer from 0 to 999) portion of a Date object + according to universal time (UTC). + + getUTCMilliseconds()setUTCMilliseconds()milliseconds + The milliseconds (an integer from 0 to 999) portion of a Date object + according to local time.Number + The milliseconds (an integer from 0 to 999) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getMilliseconds()setMilliseconds()minutesUTC + The minutes (an integer from 0 to 59) portion of a Date object + according to universal time (UTC).Number + The minutes (an integer from 0 to 59) portion of a Date object + according to universal time (UTC). + + getUTCMinutes()setUTCMinutes()minutes + The minutes (an integer from 0 to 59) portion of a Date object + according to local time.Number + The minutes (an integer from 0 to 59) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getMinutes()setMinutes()monthUTC + The month (0 [January] to 11 [December]) portion of a Date object + according to universal time (UTC).Number + The month (0 [January] to 11 [December]) portion of a Date object + according to universal time (UTC). + + getUTCMonth()setUTCMonth()month + The month (0 for January, 1 for February, and so on) portion of a + Date object according to local time.Number + The month (0 for January, 1 for February, and so on) portion of a + Date object according to local time. Local time is determined by the operating system + on which the Flash runtimes are running. + + getMonth()setMonth()secondsUTC + The seconds (an integer from 0 to 59) portion of a Date object + according to universal time (UTC).Number + The seconds (an integer from 0 to 59) portion of a Date object + according to universal time (UTC). + + getUTCSeconds()setUTCSeconds()seconds + The seconds (an integer from 0 to 59) portion of a Date object + according to local time.Number + The seconds (an integer from 0 to 59) portion of a Date object + according to local time. Local time is determined by the operating system on which + the Flash runtimes are running. + + getSeconds()setSeconds()time + The number of milliseconds since midnight January 1, 1970, universal time, + for a Date object.Number + The number of milliseconds since midnight January 1, 1970, universal time, + for a Date object. Use this method to represent a specific instant in time + when comparing two or more Date objects. + + getTime()setTime()timezoneOffset + The difference, in minutes, between universal time (UTC) and the computer's local time.Number + The difference, in minutes, between universal time (UTC) and the computer's local time. + Specifically, this value is the number of minutes you need to add to the computer's local + time to equal UTC. If your computer's time is set later than UTC, the value will be negative. + getTimezoneOffset()
Object + The Object class is at the root of the ActionScript + runtime class hierarchy. + The Object class is at the root of the ActionScript + class hierarchy. Objects are created by constructors using the + new operator syntax, and can have properties assigned to them dynamically. + Objects can also be created by + assigning an object literal, as in: + + var obj:Object = {a:"foo", b:"bar"} + +

All classes that don't declare an explicit base class extend the built-in Object class.

+ + + +

You can use the Object class to create associative arrays. At its core, an associative array is an instance of the Object class, and each key-value pair is represented by a property and its value. Another reason to declare an associative array using the Object data type is that you can then use an object literal to populate your associative array (but only at the time you declare it). The following example creates an associative array using an object literal, accesses items using both the dot operator and the array access operator, and then adds a new key-value pair by creating a new property:

+ + + var myAssocArray:Object = {fname:"John", lname:"Public"}; + trace(myAssocArray.fname); // John + trace(myAssocArray["lname"]); // Public + myAssocArray.initial = "Q"; + trace(myAssocArray.initial); // Q + +

ActionScript 3.0 has two types of inheritance: class inheritance and prototype inheritance:

+
  • Class inheritance - is the primary inheritance mechanism and supports inheritance of fixed properties. A fixed property is a variable, constant or method declared as part of a class definition. Every class definition is now represented by a special class object that stores information about the class.
  • Prototype inheritance - is the only inheritance mechanism in previous versions of ActionScript and serves as an alternate form of inheritance in ActionScript 3.0. Each class has an associated prototype object, and the properties of the prototype object are shared by all instances of the class. When a class instance is created, it has a reference to its class's prototype object, which serves as a link between the instance and its associated class prototype object. At run time, when a property is not found on a class instance, the delegate, which is the class prototype object, is checked for that property. If the prototype object does not contain the property, the process continues with the prototype object's delegate checking in consecutively higher levels in the hierarchy until the Flash runtime finds the property.
+ +

Both class inheritance and prototype inheritance can exist simultaneously, as shown in the following example:

+ + + class A { + var x = 1 + prototype.px = 2 + } + dynamic class B extends A { + var y = 3 + prototype.py = 4 + } + + var b = new B() + b.x // 1 via class inheritance + b.px // 2 via prototype inheritance from A.prototype + b.y // 3 + b.py // 4 via prototype inheritance from B.prototype + + B.prototype.px = 5 + b.px // now 5 because B.prototype hides A.prototype + + b.px = 6 + b.px // now 6 because b hides B.prototype + +

Using functions instead of classes, you can construct custom prototype inheritance trees. With classes, the prototype inheritance tree mirrors the class inheritance tree. However, since the prototype objects are dynamic, you can add and delete prototype-based properties at run time.

+ +
The following example uses the classes ObjectExample and Circle + to demonstrate the dynamic nature of the Object class, and how value objects can be transformed into + Shape objects and then added to the stage at the specified x/y coordinates. + +

The example creates the value objects firstInitObj and secondInitObj. The custom + class Circle accepts the value object and loops over it while setting its matching internal + properties to those defined in the value object.

+ +package { + import flash.display.Sprite; + + public class ObjectExample extends Sprite { + public function ObjectExample() { + var firstInitObj:Object = new Object(); + firstInitObj.bgColor = 0xFF0000; + firstInitObj.radius = 25; + firstInitObj.xCenter = 25; + firstInitObj.yCenter = 25; + + var firstCircle:Circle = new Circle(firstInitObj); + addChild(firstCircle); + firstCircle.x = 50; + firstCircle.y = 50; + + var secondInitObj:Object = {bgColor:0xCCCCCC, radius:50, xCenter:50, yCenter:50}; + + var secondCircle:Circle = new Circle(secondInitObj); + addChild(secondCircle); + secondCircle.x = 100; + secondCircle.y = 100; + } + + } +} + +import flash.display.Shape; + +class Circle extends Shape { + public var bgColor:Number = 0xFFFFFF; + public var radius:Number = 0; + public var xCenter:Number = 0; + public var yCenter:Number = 0; + + public function Circle(initObj:Object) { + for(var i:String in initObj) { + this[i] = initObj[i]; + } + draw(); + } + + public function draw():void { + graphics.beginFill(bgColor); + graphics.drawCircle(xCenter, yCenter, radius); + graphics.endFill(); + } +} +
prototypeObject + Creates an Object object and stores a reference to the object's constructor method in the object's constructor property. + Creates an Object object and stores a reference to the object's constructor method in the object's constructor property. + + hasOwnProperty + Indicates whether an object has a specified property defined.If the target object has the property specified by the name + parameter this value is true, otherwise false. + + BooleannameStringThe property of the object. + + Indicates whether an object has a specified property defined. This method returns true if the target object has + a property that matches the string specified by the name parameter, and false otherwise. + The following types of properties cause this method to return true for objects that are instances of a class (as opposed to class objects): +
  • Fixed instance properties—variables, constants, or methods defined by the object's class that are not static;
  • Inherited fixed instance properties—variables, constants, or methods inherited by the object's class;
  • Dynamic properties—properties added to an object after it is instantiated (outside of its class definition). To add dynamic properties, the object's defining class must be declared with the dynamic keyword.
+

The following types of properties cause this method to return false for objects that are instances of a class:

+
  • Static properties—variables, constants, or methods defined with the static keyword in an object's defining class or any of its superclasses;
  • Prototype properties—properties defined on a prototype object that is part of the object's prototype chain. In ActionScript 3.0, the prototype chain is not used for class inheritance, but still exists as an alternative form of inheritance. For example, an instance of the Array class can access the valueOf() method because it exists on Object.prototype, which is part of the prototype chain for the Array class. Although you can use valueOf() on an instance of Array, the return value of hasOwnProperty("valueOf") for that instance is false.
+ +

ActionScript 3.0 also has class objects, which are direct representations of class definitions. + When called on class objects, the hasOwnProperty() method returns true only if a property + is a static property defined on that class object. For example, if you create a subclass of Array named + CustomArray, and define a static property in CustomArray named foo, a call to + CustomArray.hasOwnProperty("foo") returns true. + For the static property DESCENDING defined in the Array class, however, a call to + CustomArray.hasOwnProperty("DESCENDING") returns false.

+ +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, A subclass of Object implements function hasOwnProperty():Boolean instead of using an override of the base class.

+ +
isPrototypeOf + Indicates whether an instance of the Object class is in the prototype chain of the object specified + as the parameter.If the object is in the prototype chain of the object + specified by the theClass parameter this value is true, otherwise false. + + BooleantheClassObjectThe class to which the specified object may refer. + + + Indicates whether an instance of the Object class is in the prototype chain of the object specified + as the parameter. This method returns true if the object is in the prototype chain of the + object specified by the theClass parameter. The method returns false + if the target object is absent from the prototype chain of the theClass object, + and also if the theClass parameter is not an object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, A subclass of Object implements function isPrototypeOf():Boolean instead of using an override of the base class.

+ +
propertyIsEnumerable + Indicates whether the specified property exists and is enumerable.If the property specified by the name parameter is enumerable this value is true, otherwise false. + + BooleannameStringThe property of the object. + + Indicates whether the specified property exists and is enumerable. If true, then the property exists and + can be enumerated in a for..in loop. The property must exist on the target object because this method does not + check the target object's prototype chain. + +

Properties that you create are enumerable, but built-in properties are generally not enumerable.

+ +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, A subclass of Object implements function propertyIsEnumerable():Boolean instead of using an override of the base class.

+ +
setPropertyIsEnumerable + Sets the availability of a dynamic property for loop operations.nameStringThe property of the object. + isEnumBooleantrue If set to false, the dynamic property does not show up in for..in loops, and the method propertyIsEnumerable() returns false. + + Sets the availability of a dynamic property for loop operations. The property must exist on the target object because this method does not check the target object's prototype chain. + propertyIsEnumerable()toLocaleString + Returns the string representation of this object, formatted according to locale-specific conventions.A string representation of this object formatted according to local conventions. + + String + Returns the string representation of this object, formatted according to locale-specific conventions. + +

The default implementation of this method does not perform locale-specific formatting and returns the + same string as toString(). Subclasses should provided their own locale-aware implementation when appropriate.

+ +

Note: Methods of the Object class are dynamically created on Object's prototype. + To redefine this method in a subclass of Object, do not use the override keyword. For example, + a subclass of Object implements function toLocaleString():String instead of using an override of the base class.

+ +
Object.toString()
toString + Returns the string representation of the specified object.A string representation of the object. + + String + Returns the string representation of the specified object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

+ +
valueOf + Returns the primitive value of the specified object.The primitive value of this object or the object itself. + + Object + Returns the primitive value of the specified object. If this object + does not have a primitive value, the object itself is returned. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, A subclass of Object implements function valueOf():Object instead of using an override of the base class.

+ +
Object.toString()
constructor + A reference to the class object or constructor function for a given object instance.Object + A reference to the class object or constructor function for a given object instance. + If an object is an instance of a class, the constructor + property holds a reference to the class object. + If an object is created with a constructor function, the constructor + property holds a reference to the constructor function. + Do not confuse a constructor function with a constructor method of a class. + A constructor function is a Function object used to create objects, and is an + alternative to using the class keyword for defining classes. + +

If you use the class keyword to define a class, the class's prototype object + is assigned a property named constructor that holds a reference to the class object. + An instance of the class inherits this property from the prototype object. For example, + the following code creates a new class, A, and a class instance named myA:

+ + dynamic class A {} + trace(A.prototype.constructor); // [class A] + trace(A.prototype.constructor == A); // true + var myA:A = new A(); + trace(myA.constructor == A); // true + +

Advanced users may choose to use the function keyword instead of the class + keyword to define a Function object that can be used as a template for creating objects. Such a + function is called a constructor function because you can use it in conjunction with the new + operator to create objects. + If you use the function keyword to create a constructor function, its prototype object is assigned + a property named constructor that holds a reference to the constructor function. + If you then use the constructor function to create an object, the object inherits the + constructor property from the constructor function's prototype object. For example, + the following code creates a new constructor function, f, and an object named myF:

+ + function f() {} + trace(f.prototype.constructor); // function Function() {} + trace(f.prototype.constructor == f); // true + var myF = new f(); + trace(myF.constructor == f); // true + +

Note: The constructor property is writable, which means that user code can change + its value with an assignment statement. Changing the value of the constructor property is not + recommended, but if you write code that depends on the value of the constructor property, you should + ensure that the value is not reset. The value can be changed only when the property is accessed through the prototype + object (for example, className.prototype.constructor).

+

If you access the constructor property and compile in strict mode, you will get an error at compile + time because the constructor property depends on the protoype object, which is a runtime entity. + If you use standard mode or if the class description specifies "dynamic", the code runs without generating + an error.

+
ClassFunctionprototype
prototype + A reference to the prototype object of a class or function object.Object + A reference to the prototype object of a class or function object. The prototype property + is automatically created and attached to any class or function object that you create. This property is + static in that it is specific to the class or function that you create. For example, if you create a + class, the value of the prototype property is shared by all instances of the class and is + accessible only as a class property. Instances of your class cannot directly access + the prototype property. + +

A class's prototype object is a special instance of that class that provides a mechanism for sharing state across all instances of a class. At run time, when a property is not found on a class instance, the delegate, which is the class prototype object, is checked for that property. If the prototype object does not contain the property, the process continues with the prototype object's delegate checking in consecutively higher levels in the hierarchy until + the Flash runtime finds the property.

+ +

Note: In ActionScript 3.0, prototype inheritance is not the primary mechanism for inheritance. Class inheritance, which drives the inheritance of fixed properties in class definitions, is the primary inheritance mechanism in ActionScript 3.0.

+ +
URIError + A URIError exception is thrown when one of the global URI handling functions is used + in a way that is incompatible with its definition.Error + A URIError exception is thrown when one of the global URI handling functions is used + in a way that is incompatible with its definition. This exception is thrown when an invalid + URI is specified to a function that expects a valid URI, such as the Socket.connect() + method. + + + flash.net.Socket.connect()URIError + Creates a new URIError object.messageStringContains the message associated with the URIError object. + + + Creates a new URIError object. + SecurityError + The SecurityError exception is thrown when some type of security violation + takes place.Error + The SecurityError exception is thrown when some type of security violation + takes place. +

+ Examples of security errors:

+
  • An unauthorized property access or method call is made across a security sandbox + boundary.
  • An attempt was made to access a URL not permitted by the security sandbox.
  • A socket connection was attempted to an unauthorized port number, e.g. a port above + 65535.
  • An attempt was made to access the user's camera or microphone, and the request to + access the device was denied by the user.
+ +
The following example shows how a SecurityError error can + be generated and handled within a try...catch statement by attempting + to connect to a port number that is one larger than the maximum allowed. + +package { + import flash.display.Sprite; + import flash.net.Socket; + + public class SecurityErrorExample extends Sprite { + + public function SecurityErrorExample() { + try { + var host:String = "www.[yourDomain].com"; + var socket:Socket = new Socket(); + socket.connect(host, 65536); + } + catch(e:SecurityError) { + trace(e); + } + } + } +} +
SecurityError + Creates a new SecurityError object.messageString + Creates a new SecurityError object. + +
ReferenceError + A ReferenceError exception is thrown when a reference to an undefined property is + attempted on a sealed (nondynamic) object.Error + A ReferenceError exception is thrown when a reference to an undefined property is + attempted on a sealed (nondynamic) object. References to undefined variables will + result in ReferenceError exceptions to inform you of potential bugs and help you troubleshoot + application code. +

However, you can refer to undefined properties of a dynamic class without causing a ReferenceError exception + to be thrown. For more information, see the dynamic keyword.

+ +
The following example shows how a ReferenceError exception can + be generated and handled within a try..catch statement. + +package { + import flash.display.Sprite; + + public class ReferenceErrorExample extends Sprite { + + public function ReferenceErrorExample() { + try { + this["someMember"] = true; + } + catch(e:ReferenceError) { + trace(e); + } + } + } +} +
dynamic keywordReferenceError + Creates a new ReferenceError object.messageStringContains the message associated with the ReferenceError object. + + + Creates a new ReferenceError object. +
RangeError + A RangeError exception is thrown when a numeric value is outside the acceptable range.Error + A RangeError exception is thrown when a numeric value is outside the acceptable range. When working with arrays, + referring to an index position of an array item that does not exist will throw a RangeError exception. + Using Number.toExponential(), Number.toPrecision(), and Number.toFixed() methods + will throw a RangeError exception in cases + where the arguments are outside the acceptable range of numbers. You can extend Number.toExponential(), + Number.toPrecision(), and Number.toFixed() to avoid throwing a RangeError. +

Other situations that cause this exception to be thrown include the following: +

  • Any Flash runtime API that expects a depth number is invoked with an invalid depth + number.
  • Any Flash runtime API that expects a frame number is invoked with an invalid frame + number.
  • Any Flash runtime API that expects a layer number is invoked with an invalid layer + number.
+

+
The following example shows how a RangeError exception can + be generated and handled within a try..catch statement. + +package { + import flash.display.Sprite; + + public class RangeErrorExample extends Sprite { + + public function RangeErrorExample() { + var child:Sprite = new Sprite(); + try { + addChildAt(child, 1); + } + catch(e:RangeError) { + trace(e); + } + } + } +} +
Number.toExponential()Number.toPrecision()Number.toFixed()RangeError + Creates a new RangeError object.messageStringContains the message associated with the RangeError object. + + + Creates a new RangeError object. +
int + The int class lets you work with the data type representing a 32-bit signed integer.Object + The int class lets you work with the data type representing a 32-bit signed integer. + The range of values represented by the int class is -2,147,483,648 (-2^31) to 2,147,483,647 (2^31-1). +

The constant properties of the int class, MAX_VALUE and MIN_VALUE, are static, which means that you don't need an object to use them, so you don't need to use the constructor. The methods, however, are not static, which means that you do need an object to use them. You can create an int object by using the int class constructor or by declaring a variable of type int and assigning the variable a literal value.

+

The int data type is useful for loop counters and other situations where a floating point number is not needed, and is similar to the int data type in Java and C++. The default value of a variable typed as int is 0

+

If you are working with numbers that exceed int.MAX_VALUE, consider using Number.

+

The following example calls the toString() method of the int class, which returns the string 1234:

+ + var myint:int = 1234; + myint.toString(); + +

The following example assigns the value of the MIN_VALUE property to a variable declared without the use of the constructor:

+
+ var smallest:int = int.MIN_VALUE;
+ 
+ +
The following example uses the IntExample class to show how + to work with and check the validity of int data types: +
  1. Two int variables a and b are declared in the constructor.
  2. The two ints are added using the method addIntegers().
  3. A third int variable c is assigned the outcome of parseInteger(), + which checks the validity of the string passed to it to ensure that it is an integer value + in the acceptable range for int data types and returns an int equal to the integer value + of the string if it is valid.
  4. The int variables a and c are added together using addIntegers().
+ +package { + import flash.display.Sprite; + + public class IntExample extends Sprite { + public function IntExample() { + var a:int = 512; + var b:int = -128; + + trace(addIntegers(a, b)); // 384 + + var c:int = parseInteger("32"); + + trace(addIntegers(a, c)); // 544 + } + + public function addIntegers(a:int, b:int):int { + return a + b; + } + + public function parseInteger(str:String):int { + var num:Number = parseInt(str); + if(!isNaN(num) && num <= int.MAX_VALUE && num >= int.MIN_VALUE) { + return int(num); + } + + return 0; + } + + } +} +
uintNumberint + Constructor; creates a new int object.numObjectThe numeric value of the int object being created or a value to be converted to a number. The default value is 0 if value is not provided. + + + Constructor; creates a new int object. You must use the int constructor when using int.toString() and int.valueOf(). You do not use a constructor when using the properties of an int object. The new int constructor is primarily used as a placeholder. An int object is not the same as the int() function that converts a parameter to a primitive value. + + The following code constructs new int objects: +
+	 var n1:int = new int(3.4);
+	 var n2:int = new int(-10);
+	 
+ + +
int.toString()int.valueOf()
toExponential + Returns a string representation of the number in exponential notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in exponential notation. The string contains + one digit before the decimal point and up to 20 digits after the decimal point, as + specified by the fractionDigits parameter. + The following example shows how toExponential(2) returns a string in + exponential notation. + + +var num:Number = 315003; +trace(num.toExponential(2)); // 3.15e+5 + +toFixed + Returns a string representation of the number in fixed-point notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in fixed-point notation. + Fixed-point notation means that the string will contain a specific number of digits + after the decimal point, as specified in the fractionDigits parameter. + The valid range for the fractionDigits parameter is from 0 to 20. + Specifying a value outside this range throws an exception. + + The following example shows how toFixed(3) returns a string that rounds + to three decimal places. + + +var num:Number = 7.31343; +trace(num.toFixed(3)); // 7.313 + The following example shows how toFixed(2) returns a string that adds + trailing zeroes. + + +var num:Number = 4; +trace(num.toFixed(2)); // 4.00 +toPrecision + Returns a string representation of the number either in exponential notation or in + fixed-point notation.Throws an exception if the precision argument is outside the range 1 to 21. + RangeErrorRangeErrorStringprecisionuintAn integer between 1 and 21, inclusive, that represents the desired number of digits to represent in the resulting string. + + Returns a string representation of the number either in exponential notation or in + fixed-point notation. The string will contain the number of digits specified in the + precision parameter. + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in fixed-point notation because exponential notation is not required. + + +var num:Number = 31.570; +trace(num.toPrecision(3)); // 31.6 + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in exponential notation because the resulting number does not + contain enough digits for fixed-point notation. + + +var num:Number = 4000; +trace(num.toPrecision(3)); // 4.00e+3 +toString + Returns the string representation of an int object.A string. + + StringradixuintSpecifies the numeric base (from 2 to 36) to use for the number-to-string conversion. If you do not specify the radix parameter, the default value is 10. + + + Returns the string representation of an int object. + + The following example uses 2 and 8 for the radix parameter and returns a string that contains the corresponding representation of the number 9: +
+	 var myint:int = new int(9);
+	 trace(myint.toString(2)); // 1001
+	 trace(myint.toString(8)); // 11
+	 
+

The following example results in a hexadecimal value.

+
+	 var r:int = new int(250);
+	 var g:int = new int(128);
+	 var b:int = new int(114);
+	 var rgb:String = "0x"+ r.toString(16)+g.toString(16)+b.toString(16);
+	 trace(rgb); // 0xfa8072
+	 
+ +
valueOf + Returns the primitive value of the specified int object.An int value. + + int + Returns the primitive value of the specified int object. + + The following example results in the primative value of the numSocks object. +
+	 var numSocks:int = new int(2);
+	 trace(numSocks.valueOf()); // 2
+	 
+ +
MAX_VALUE + The largest representable 32-bit signed integer, which is 2,147,483,647.2147483647int + The largest representable 32-bit signed integer, which is 2,147,483,647. + + The following ActionScript displayswrites the largest and smallest representable int objects to the Output panelto the log file: +
+	trace("int.MIN_VALUE = "+int.MIN_VALUE);
+	trace("int.MAX_VALUE = "+int.MAX_VALUE);
+	
+

This code logsdisplays the following values:

+
+	int.MIN_VALUE = -2147483648
+	int.MAX_VALUE = 2147483647
+	
+ + +
MIN_VALUE + The smallest representable 32-bit signed integer, which is -2,147,483,648.-2147483648int + The smallest representable 32-bit signed integer, which is -2,147,483,648. + + The following ActionScript displayswrites the largest and smallest representable int objects to the Output panel to the log file: +
+     trace("int.MIN_VALUE = "+int.MIN_VALUE);
+     trace("int.MAX_VALUE = "+int.MAX_VALUE);
+     
+

This code logsdisplays the following values:

+
+	int.MIN_VALUE = -2147483648
+	int.MAX_VALUE = 2147483647
+     
+ + +
Number + A data type representing an IEEE-754 double-precision floating-point number.The Number class is a simple wrapper object for the Number + data type. + + Object + A data type representing an IEEE-754 double-precision floating-point number. You can manipulate primitive numeric + values by using the methods and properties associated with the Number class. This class is identical to the + JavaScript Number class. +

The properties of the Number class are static, which means you do not need an object to use them, so you + do not need to use the constructor.

+

The Number data type adheres to the double-precision IEEE-754 standard.

+

The Number data type is useful when you need to use floating-point values. + Flash runtimes handle int and uint data types more efficiently than Number, but Number is + useful in situations where the range of values required exceeds the valid range + of the int and uint data types. The Number class can be used to + represent integer values well beyond the valid range of the int and uint data types. + The Number data type can use up to 53 bits to represent integer values, compared to + the 32 bits available to int and uint. The default value of a variable typed as Number is NaN (Not a Number).

+ +
The following example shows how a number with six digits after the decimal place + is truncated (with rounding) to a number with two digits after the decimal point. + + +package { + import flash.display.Sprite; + + public class NumberExample extends Sprite { + public function NumberExample() { + var num:Number = new Number(10.456345); + var str:String = num.toFixed(2); + trace(num); // 10.456345 + trace(str); // 10.46 + } + } +} +
intuintNumber + Creates a Number object with the specified value.numObjectThe numeric value of the Number instance being created or a value + to be converted to a Number. The default value is 0 if num is + not specified. Using the constructor without specifying a num parameter is not + the same as declaring a variable of type Number with no value assigned (such as var myNumber:Number), which + defaults to NaN. A number with no value assigned is undefined and the equivalent of + new Number(undefined). + + Creates a Number with the specified value. + + + Creates a Number object with the specified value. This constructor has the same effect + as the Number() public native function that converts an object of a different type + to a primitive numeric value. + + Number.toString()Number.valueOf()toExponential + Returns a string representation of the number in exponential notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in exponential notation. The string contains + one digit before the decimal point and up to 20 digits after the decimal point, as + specified by the fractionDigits parameter. + The following example shows how toExponential(2) returns a string in + exponential notation. + + +var num:Number = 315003; +trace(num.toExponential(2)); // 3.15e+5 + +toFixed + Returns a string representation of the number in fixed-point notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in fixed-point notation. + Fixed-point notation means that the string will contain a specific number of digits + after the decimal point, as specified in the fractionDigits parameter. + The valid range for the fractionDigits parameter is from 0 to 20. + Specifying a value outside this range throws an exception. + + The following example shows how toFixed(3) returns a string that rounds + to three decimal places. + + +var num:Number = 7.31343; +trace(num.toFixed(3)); // 7.313 + The following example shows how toFixed(2) returns a string that adds + trailing zeroes. + + +var num:Number = 4; +trace(num.toFixed(2)); // 4.00 +toPrecision + Returns a string representation of the number either in exponential notation or in + fixed-point notation.Throws an exception if the precision argument is outside the range 1 to 21. + RangeErrorRangeErrorStringprecisionuintAn integer between 1 and 21, inclusive, that represents the desired number of digits to represent in the resulting string. + + Returns a string representation of the number either in exponential notation or in + fixed-point notation. The string will contain the number of digits specified in the + precision parameter. + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in fixed-point notation because exponential notation is not required. + + +var num:Number = 31.570; +trace(num.toPrecision(3)); // 31.6 + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in exponential notation because the resulting number does not + contain enough digits for fixed-point notation. + + +var num:Number = 4000; +trace(num.toPrecision(3)); // 4.00e+3 +toString + Returns the string representation of the specified Number object (myNumber).The numeric representation of the Number object as a string. + + StringradixNumber10Specifies the numeric base (from 2 to 36) to use for the number-to-string + conversion. If you do not specify the radix parameter, the default value + is 10. + + Returns the string representation of this Number using the specified + radix parameter as the numeric base. + + + Returns the string representation of the specified Number object (myNumber). + If the value of the Number object is a decimal number without a leading zero (such as .4), + Number.toString() adds a leading zero (0.4). + + + valueOf + Returns the primitive value type of the specified Number object.The primitive type value of the Number object. + + NumberReturns the primitive value type of the specified Number object. + + + Returns the primitive value type of the specified Number object. + + MAX_VALUE + The largest representable number (double-precision IEEE-754).NumberThe largest representable number (double-precision IEEE-754). + + + The largest representable number (double-precision IEEE-754). This number is + approximately 1.79e+308. + + MIN_VALUE + The smallest representable non-negative, non-zero, number (double-precision IEEE-754).NumberThe smallest representable number (double-precision IEEE-754). + + + The smallest representable non-negative, non-zero, number (double-precision IEEE-754). This number is + approximately 5e-324. The smallest representable number overall is actually -Number.MAX_VALUE. + + NEGATIVE_INFINITY + Specifies the IEEE-754 value representing negative infinity.NumberSpecifies the IEEE-754 value representing negative infinity. + + + Specifies the IEEE-754 value representing negative infinity. The value of this property + is the same as that of the constant -Infinity. +

+ Negative infinity is a special numeric value that is returned when a mathematical + operation or function returns a negative value larger than can be + represented. +

+ +
NaN + The IEEE-754 value representing Not a Number (NaN).NumberThe IEEE-754 value representing Not a Number (NaN). + + + The IEEE-754 value representing Not a Number (NaN). + + isNaN() global functionPOSITIVE_INFINITY + Specifies the IEEE-754 value representing positive infinity.NumberSpecifies the IEEE-754 value representing positive infinity. + + + Specifies the IEEE-754 value representing positive infinity. The value of this property + is the same as that of the constant Infinity. +

+ Positive infinity is a special numeric value that is returned when a mathematical + operation or function returns a value larger than can be represented. +

+ +
DefinitionError + The DefinitionError class represents an error that occurs when user code + attempts to define an identifier that is already defined.An DefinitionError is thrown when code attempts to redefine a class, + interface, or function. + + Error + The DefinitionError class represents an error that occurs when user code + attempts to define an identifier that is already defined. This error commonly + occurs in redefining classes, interfaces, + and functions. + + DefinitionError + Creates a new DefinitionError object.messageString + Creates a new DefinitionError object. + + Function + A function is the basic unit of code that can be invoked in ActionScript.The Function class is used to represent a built-in or user-defined function. + + Object + A function is the basic unit of code that can be invoked in ActionScript. + Both user-defined and built-in functions in ActionScript are represented by Function objects, + which are instances of the Function class. +

Methods of a class are slightly different than Function objects. Unlike an ordinary function object, a method is tightly linked to its associated class object. Therefore, a method or property has a definition that is shared among all instances of the same class. Methods can be extracted from an instance and treated as "bound" methods (retaining the link to the original instance). For a bound method, the this keyword points to the original object that implemented the method. For a function, this points to the associated object at the time the function is invoked.

+ + +
The following example uses the FunctionExample, + SimpleCollection, EventBroadcaster, and EventListener classes + to show various uses of functions in ActionScript. This is accomplished with the following steps: +
  1. The constructor for FunctionExample creates a local variable named + simpleColl, which is populated with an array of integers ranging from 1 to + 8.
  2. The simpleColl object is printed using trace().
  3. An EventListener object, listener, is added to simpleColl.
  4. When the insert() and remove() functions are called, the listener responds + to their events.
  5. A second SimpleCollection object is created named greaterThanFourColl.
  6. The greaterThanFourColl object is assigned the result of simpleColl.select() + with the argument 4 and an anonymous function. The SimpleCollection object's select method is an + internal iterator that uses the anonymous function parameter as a block.
+ +package { + import flash.display.Sprite; + + public class FunctionExample extends Sprite { + public function FunctionExample() { + var simpleColl:SimpleCollection; + simpleColl = new SimpleCollection(0, 1, 2, 3, 4, 5, 6, 7, 8); + trace(simpleColl); // 0, 1, 2, 3, 4, 5, 6, 7, 8 + + var listener:EventListener = new EventListener(); + simpleColl.addListener(listener); + simpleColl.insert(9); // itemInsertedHandler: 9 + simpleColl.remove(8); // itemRemovedHandler: 8 + trace(simpleColl); // 0, 1, 2, 3, 4, 5, 6, 7, 9 + + var greaterThanFourColl:SimpleCollection; + greaterThanFourColl = simpleColl.select(4, function(item:int, value:int){ return item > value }); + trace(greaterThanFourColl); // 5, 6, 7, 9 + } + } +} + +import flash.display.Sprite; + +class EventBroadcaster { + private var listeners:Array; + + public function EventBroadcaster() { + listeners = new Array(); + } + + public function addListener(obj:Object):void { + removeListener(obj); + listeners.push(obj); + } + + public function removeListener(obj:Object):void { + for(var i:uint = 0; i < listeners.length; i++) { + if(listeners[i] == obj) { + listeners.splice(i, 1); + } + } + } + + public function broadcastEvent(evnt:String, ...args):void { + for(var i:uint = 0; i < listeners.length; i++) { + listeners[i][evnt].apply(listeners[i], args); + } + } +} + +class SimpleCollection extends EventBroadcaster { + private var arr:Array; + public function SimpleCollection(... args) { + arr = (args.length == 1 && !isNaN(args[0])) ? new Array(args[0]) : args; + } + + public function insert(obj:Object):void { + remove(obj); + arr.push(obj); + broadcastEvent("itemInsertedHandler", obj); + } + + public function remove(obj:Object):void { + for(var i:uint = 0; i < arr.length; i++) { + if(arr[i] == obj) { + var obj:Object = arr.splice(i, 1)[0]; + broadcastEvent("itemRemovedHandler", obj); + } + } + } + + public function select(val:int, fn:Function):SimpleCollection { + var col:SimpleCollection = new SimpleCollection(); + for(var i:uint = 0; i < arr.length; i++) { + if(fn.call(this, arr[i], val)) { + col.insert(arr[i]); + } + } + return col; + } + + public function toString():String { + var str:String = new String(); + for(var i:uint = 0; i < arr.length - 1; i++) { + str += arr[i] + ", "; + } + str += arr[arr.length - 1]; + return str; + } +} + +class EventListener { + public function EventListener() { + } + + public function itemInsertedHandler(obj:Object):void { + trace("itemInsertedHandler: " + obj); + } + + public function itemRemovedHandler(obj:Object):void { + trace("itemRemovedHandler: " + obj); + } +} +
apply + Specifies the value of thisObject to be used within any function that ActionScript calls.Any value that the called function specifies. + + + thisArgunknownThe object to which the function is applied. + + argArrayunknownAn array whose elements are passed to the function as parameters. + + Specifies the object instance on which the Function is called. + + + Specifies the value of thisObject to be used within any function that ActionScript calls. + This method also specifies the parameters to be passed to any called function. Because apply() + is a method of the Function class, it is also a method of every Function object in ActionScript. +

The parameters are specified as an Array object, unlike Function.call(), which specifies + parameters as a comma-delimited list. This is often useful when the number of parameters to be passed is not + known until the script actually executes.

+

Returns the value that the called function specifies as the return value.

+ + +
Function.call()
call + Invokes the function represented by a Function object.thisArgunknownAn object that specifies the value of thisObject within the function body. + + argsThe parameter or parameters to be passed to the function. You can specify zero or more parameters. + + Invokes this Function. + + + Invokes the function represented by a Function object. Every function in ActionScript + is represented by a Function object, so all functions support this method. +

In almost all cases, the function call (()) operator can be used instead of this method. + The function call operator produces code that is concise and readable. This method is primarily useful + when the thisObject parameter of the function invocation needs to be explicitly controlled. + Normally, if a function is invoked as a method of an object within the body of the function, thisObject + is set to myObject, as shown in the following example:

+ + myObject.myMethod(1, 2, 3); + +

In some situations, you might want thisObject to point somewhere else; + for example, if a function must be invoked as a method of an object, but is not actually stored as a method + of that object:

+ + myObject.myMethod.call(myOtherObject, 1, 2, 3); + +

You can pass the value null for the thisObject parameter to invoke a function as a + regular function and not as a method of an object. For example, the following function invocations are equivalent:

+ + Math.sin(Math.PI / 4) + Math.sin.call(null, Math.PI / 4) + + +

Returns the value that the called function specifies as the return value.

+ +
Function.apply()
SyntaxError + A SyntaxError exception is thrown when a parsing error occurs, for one of the following reasons:.Error + A SyntaxError exception is thrown when a parsing error occurs, for one of the following reasons:. +
  • An invalid regular expression is parsed by the RegExp class.
  • Invalid XML content is parsed by the XML class.
+ +
RegExp classXML classSyntaxError + Creates a new SyntaxError object.messageStringContains the message associated with the SyntaxError object. + + + Creates a new SyntaxError object. +
XMLList + The XMLList class contains methods for working with one or more XML elements.Object + The XMLList class contains methods for working with one or more XML elements. An XMLList object + can represent one or more XML objects or elements (including multiple nodes or attributes), so + you can call methods on the elements as a group or on the individual elements in the collection. +

If an XMLList object has only one XML element, you can use the XML class methods on the + XMLList object directly. In the following example, example.two is an XMLList + object of length 1, so you can call any XML method on it.

+ + var example2 = <example><two>2</two></example>; +

If you attempt to use XML class methods with an XMLList object containing more than one XML + object, an exception is thrown; instead, iterate over the XMLList collection (using a + for each..in statement, for example) and apply the methods to each XML object in + the collection.

+ +
The following example creates an XML property named books and adds several + items with book publisher and name tags to a node named books. + Then the showBooksByPublisher() method is called, + which takes the XMLList and returns each item matching the publisher, "Addison-Wesley." + +package { + import flash.display.Sprite; + + public class XMLListExample extends Sprite { + private var books:XML; + + public function XMLListExample() { + books = <books> + <book publisher="Addison-Wesley" name="Design Patterns" /> + <book publisher="Addison-Wesley" name="The Pragmatic Programmer" /> + <book publisher="Addison-Wesley" name="Test Driven Development" /> + <book publisher="Addison-Wesley" name="Refactoring to Patterns" /> + <book publisher="O'Reilly Media" name="The Cathedral & the Bazaar" /> + <book publisher="O'Reilly Media" name="Unit Test Frameworks" /> + </books>; + + showBooksByPublisher("Addison-Wesley"); + } + + private function showBooksByPublisher(name:String):void { + var results:XMLList = books.book.(@publisher == name); + showList(results); + } + + private function showList(list:XMLList):void { + var item:XML; + for each(item in list) { + trace("item: " + item.toXMLString()); + } + } + } +} +
XMLfor each..inNamespaceQNameXMLList + Creates a new XMLList object.valueObjectAny object that can be converted to an XMLList object by using the top-level XMLList() function. + + + Creates a new XMLList object. + + top-level XMLList() functionattribute + Calls the attribute() method of each XML object and returns an XMLList object + of the results.An XMLList object of matching XML objects or an empty XMLList object. + + XMLListattributeNameThe name of the attribute that you want to include in an XMLList object. + + + Calls the attribute() method of each XML object and returns an XMLList object + of the results. The results match the given attributeName parameter. If there is no + match, the attribute() method returns an empty XMLList object. + + XML.attribute()XML.attributes()attributes + Calls the attributes() method of each XML object and + returns an XMLList object of attributes for each XML object.An XMLList object of attributes for each XML object. + + XMLList + Calls the attributes() method of each XML object and + returns an XMLList object of attributes for each XML object. + + XML.attribute()XML.attributes()child + Calls the child() method of each XML object and returns an XMLList object that + contains the results in order.An XMLList object of child nodes that match the input parameter. + + XMLListpropertyNameObjectThe element name or integer of the XML child. + + + Calls the child() method of each XML object and returns an XMLList object that + contains the results in order. + + XML.child()children + Calls the children() method of each XML object and + returns an XMLList object that contains the results.An XMLList object of the children in the XML objects. + + XMLList + Calls the children() method of each XML object and + returns an XMLList object that contains the results. + + XML.children()comments + Calls the comments() method of each XML object and returns + an XMLList of comments.An XMLList of the comments in the XML objects. + + XMLList + Calls the comments() method of each XML object and returns + an XMLList of comments. + + XML.comments()contains + Checks whether the XMLList object contains an XML object that is equal to the given + value parameter.If the XMLList contains the XML object declared in the value parameter, + then true; otherwise false. + + BooleanvalueXMLAn XML object to compare against the current XMLList object. + + + Checks whether the XMLList object contains an XML object that is equal to the given + value parameter. + + copy + Returns a copy of the given XMLList object.The copy of the XMLList object. + + XMLList + Returns a copy of the given XMLList object. The copy is a duplicate of the entire tree of nodes. + The copied XML object has no parent and returns null if you attempt to call the parent() method. + + descendants + Returns all descendants (children, grandchildren, great-grandchildren, and so on) of the XML object + that have the given name parameter.An XMLList object of the matching descendants (children, grandchildren, and so on) of the XML objects + in the original list. If there are no descendants, returns an empty XMLList object. + + XMLListnameObject*The name of the element to match. + + + Returns all descendants (children, grandchildren, great-grandchildren, and so on) of the XML object + that have the given name parameter. The name parameter can be a + QName object, a String data type, or any other data type that is then converted to a String + data type. + +

To return all descendants, use + the asterisk (~~) parameter. If no parameter is passed, + the string "~~" is passed and returns all descendants of the XML object.

+ +
XML.descendants()
elements + Calls the elements() method of each XML object.An XMLList object of the matching child elements of the XML objects. + + XMLListnameObject*The name of the elements to match. + + + Calls the elements() method of each XML object. The name parameter is + passed to the descendants() method. If no parameter is passed, the string "~~" is passed to the + descendants() method. + + XML.elements()hasComplexContent + Checks whether the XMLList object contains complex content.If the XMLList object contains complex content, then true; otherwise false. + + Boolean + Checks whether the XMLList object contains complex content. An XMLList object is + considered to contain complex content if it is not empty and either of the following conditions is true: + +
  • The XMLList object contains a single XML item with complex content.
  • The XMLList object contains elements.
+ +
hasSimpleContent()XML.hasComplexContent()XML.hasSimpleContent()
hasOwnProperty + Checks for the property specified by p.If the parameter exists, then true; otherwise false. + + BooleanpStringThe property to match. + + + Checks for the property specified by p. + + hasSimpleContent + Checks whether the XMLList object contains simple content.If the XMLList contains simple content, then true; otherwise false. + + Boolean + Checks whether the XMLList object contains simple content. An XMLList object is + considered to contain simple content if one or more of the following + conditions is true: +
  • The XMLList object is empty
  • The XMLList object contains a single XML item with simple content
  • The XMLList object contains no elements
+ +
hasComplexContent()XML.hasComplexContent()XML.hasSimpleContent()
length + Returns the number of properties in the XMLList object.The number of properties in the XMLList object. + + int + Returns the number of properties in the XMLList object. + + normalize + Merges adjacent text nodes and eliminates empty text nodes for each + of the following: all text nodes in the XMLList, all the XML objects + contained in the XMLList, and the descendants of all the XML objects in + the XMLList.The normalized XMLList object. + + XMLList + Merges adjacent text nodes and eliminates empty text nodes for each + of the following: all text nodes in the XMLList, all the XML objects + contained in the XMLList, and the descendants of all the XML objects in + the XMLList. + + parent + Returns the parent of the XMLList object if all items in the XMLList object have the same parent.Returns the parent XML object. + + Object + Returns the parent of the XMLList object if all items in the XMLList object have the same parent. + If the XMLList object has no parent or different parents, the method returns undefined. + + processingInstructions + If a name parameter is provided, lists all the children of the XMLList object that + contain processing instructions with that name.An XMLList object that contains the processing instructions for each XML object. + + XMLListnameString*The name of the processing instructions to match. + + + If a name parameter is provided, lists all the children of the XMLList object that + contain processing instructions with that name. With no parameters, the method lists all the + children of the XMLList object that contain any processing instructions. + + XML.processingInstructions()propertyIsEnumerable + Checks whether the property p is in the set of properties that can be iterated in a for..in statement + applied to the XMLList object.If the property can be iterated in a for..in statement, then true; otherwise false. + + BooleanpStringThe index of a property to check. + + + Checks whether the property p is in the set of properties that can be iterated in a for..in statement + applied to the XMLList object. This is true only if toNumber(p) is greater than or equal to 0 + and less than the length of the XMLList object. + + text + Calls the text() method of each XML + object and returns an XMLList object that contains the results.An XMLList object of all XML properties of the XMLList object that represent XML text nodes. + + XMLList + Calls the text() method of each XML + object and returns an XMLList object that contains the results. + + XML.text()toString + Returns a string representation of all the XML objects in an XMLList object.The string representation of the XML object. + + String + Returns a string representation of all the XML objects in an XMLList object. The rules for + this conversion depend on whether the XML object has simple content or complex content: + +
  • If the XML object has simple content, toString() returns the string contents of the + XML object with the following stripped out: the start tag, attributes, namespace declarations, and + end tag.
+ +
  • If the XML object has complex content, toString() returns an XML encoded string + representing the entire XML object, including the start tag, attributes, namespace declarations, + and end tag.
+ +

To return the entire XML object every time, use the toXMLString() method.

+ + +
The following example shows what the toString() method returns when the + XML object has simple content: + +var test:XML = <type name="Joe">example</type>; +trace(test.toString()); //example + The following example shows what the toString() method returns when the + XML object has complex content: + +var test:XML = +<type name="Joe"> + <base name="Bob"></base> + example +</type>; +trace(test.toString()); + // <type name="Joe"> + // <base name="Bob"/> + // example + // </type> +
hasComplexContent()hasSimpleContent()toXMLString()
toXMLString + Returns a string representation of all the XML objects in an XMLList object.The string representation of the XML object. + + String + Returns a string representation of all the XML objects in an XMLList object. + Unlike the toString() method, the toXMLString() + method always returns the start tag, attributes, + and end tag of the XML object, regardless of whether the XML object has simple content + or complex content. (The toString() method strips out these items for XML + objects that contain simple content.) + + + toString()valueOf + Returns the XMLList object.Returns the current XMLList object. + + XMLList + Returns the XMLList object. + +
Boolean +A Boolean object is a data type that can have one of two values, either true or false, +used for logical operations.Object +A Boolean object is a data type that can have one of two values, either true or false, +used for logical operations. Use the Boolean +class to retrieve the primitive data type or string representation of a Boolean object. + +

To create a Boolean object, you can use the constructor or the global function, or assign a literal value. +It doesn't matter which technique you use; in ActionScript 3.0, all three techniques are equivalent. (This is +different from JavaScript, where a Boolean object is distinct from the Boolean primitive type.)

+ +

The following lines of code are equivalent:

+ +var flag:Boolean = true; +var flag:Boolean = new Boolean(true); +var flag:Boolean = Boolean(true); + + +
The following example toggles and displays each corresponding value for the Boolean object: + + package { + import flash.display.Sprite; + + public class BooleanExample extends Sprite { + private var flag:Boolean; + + public function BooleanExample() { + trace(flag); // false + toggle(); + trace(flag); // true + toggle(); + trace(flag); // false + } + + private function toggle():void{ + flag = !flag; + } + } +} +
Boolean + Creates a Boolean object with the specified value.expressionObjectfalseAny expression. + + + Creates a Boolean object with the specified value. If you omit the expression + parameter, the Boolean object is initialized with a value of false. If you + specify a value for the expression parameter, the method evaluates it and returns the result + as a Boolean value according to the rules in the global Boolean() function. + + The following code creates a new Boolean object, initialized to a value of false called myBoolean: + + var myBoolean:Boolean = new Boolean(); + + + Boolean() global functiontoString + Returns the string representation ("true" or + "false") of the Boolean object.The string "true" or "false". + + String + Returns the string representation ("true" or + "false") of the Boolean object. The output is not localized, and is "true" or + "false" regardless of the system language. + + This example creates a variable of type Boolean and then uses the toString() method + to convert the value to a string for use in an array of strings: + + var myStringArray:Array = new Array("yes", "could be"); + var myBool:Boolean = 0; + myBool.toString(); + myStringArray.push(myBool); + trace(myStringArray); // yes,could be,false + + + + valueOf + Returns true if the value of the specified Boolean + object is true; false otherwise.A Boolean value. + + Boolean + Returns true if the value of the specified Boolean + object is true; false otherwise. + + The following example shows how this method works, and also shows that the + value of a new Boolean object is false: + + var myBool:Boolean = new Boolean(); + trace(myBool.valueOf());   // false + myBool = (6==3+3); + trace(myBool.valueOf());   // true + + + +
Error + The Error class contains information about an error that occurred in a script.An Error is thrown when an error occurs in a script. + + Object + The Error class contains information about an error that occurred in a script. In developing ActionScript 3.0 applications, + when you run your compiled code in the debugger version of a Flash runtime, a dialog box displays exceptions of type Error, + or of a subclass, to help you troubleshoot the code. + You create an Error object by using the Error constructor function. + Typically, you throw a new Error object from within a try + code block that is caught by a catch or finally code block. +

You can also create a subclass of the Error class and throw instances of that subclass.

+ +
The following example uses the ErrorExample class to show + how a custom error can be generated. This is accomplished with the following + steps: +
  1. A local variable nullArray of Array type is declared, but notice + that a new Array object is never created.
  2. The constructor attempts to load a value into the uninitialized array by using + the push() method within an error handling code segment that catches a + custom error by using the CustomError class, which extends Error.
  3. When the CustomError is thrown, the constructor catches it and then outputs an + error message by using the trace() statement.
+ +package +{ + import flash.display.Sprite; + public class ErrorExample extends Sprite + { + private var nullArray:Array; + public function ErrorExample() + { + try + { + nullArray.push("item"); + } + catch(e:Error) + { + throw new CustomError("nullArray is null"); + } + } + } +} + +class CustomError extends Error +{ + public function CustomError(message:String) + { + super(message); + } +} +
Error + Creates a new Error object.messageStringA string associated with the Error object; this parameter + is optional. + idint0A reference number to associate with the specific error message. + + Creates a new Error instance with the specified error message. + + + Creates a new Error object. If message is specified, its value is assigned + to the object's Error.message property. + + + The following example creates a new Error object err and then, using the + Error() constructor, assigns the string "New Error Message" to + err. + + +var err:Error = new Error(); +trace(err.toString()); // Error + +err = new Error("New Error Message"); +trace(err.toString()); // Error: New Error Message +statements.html#throwstatements.html#try..catch..finallygetStackTrace + Returns the call stack for an error as a string at the time of the error's construction (for the debugger version + of Flash Player and the AIR Debug Launcher (ADL) only; returns null if not using the debugger version + of Flash Player or the ADL.A string representation of the call stack. + + + + StringReturns the call stack for an error in a readable form. + + + + Returns the call stack for an error as a string at the time of the error's construction (for the debugger version + of Flash Player and the AIR Debug Launcher (ADL) only; returns null if not using the debugger version + of Flash Player or the ADL. As shown in the following example, the first line of the return value is the + string representation of the exception object, followed by the stack trace elements: + + + TypeError: null cannot be converted to an object + at com.xyz.OrderEntry.retrieveData(OrderEntry.as:995) + at com.xyz.OrderEntry.init(OrderEntry.as:200) + at com.xyz.OrderEntry.$construct(OrderEntry.as:148) + + + + toString + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined.The error message. + + StringReturns the error message, or the word "Error" if the message is + undefined. + + + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined. + + The following example creates a new Error object err and then, using the + Error() constructor, assigns the string "New Error Message" to + err. Finally, the message property is set to "Another New Error Message", + which overwrites "New Error Message". + + + +var err:Error = new Error(); +trace(err.toString()); // Error + +err = new Error("New Error Message"); +trace(err.toString()); // Error: New Error Message + +err.message = "Another New Error Message"; +trace(err.toString()); // Error: Another New Error Message +Error.messagestatements.html#throwstatements.html#try..catch..finallymessage + Contains the message associated with the Error object.StringContains the error message associated with the Error instance. + + + Contains the message associated with the Error object. By default, the value of this property + is "Error". You can specify a message property when you create an + Error object by passing the error string to the Error constructor function. + + + statements.html#throwstatements.html#try..catch..finallyname + Contains the name of the Error object.StringThe name of the Error instance. + + + Contains the name of the Error object. By default, the value of this property is "Error". + + statements.html#throwstatements.html#try..catch..finallyerrorID + Contains the reference number associated with the specific error message.intContains the error number. + + + + Contains the reference number associated with the specific error message. For a custom Error object, + this number is the value from the id parameter supplied in the constructor. +
TypeError + A TypeError exception is thrown when the actual type of an operand is different + from the expected type.Error + A TypeError exception is thrown when the actual type of an operand is different + from the expected type. +

+ In addition, this exception is thrown when: +

  • An actual parameter to a function or method could not be coerced to the formal + parameter type.
  • A value is assigned to a variable and cannot be coerced to the variable's type.
  • The right side of the is or instanceof operator is not a valid type.
  • The super keyword is used illegally.
  • A property lookup results in more than one binding, and is therefore ambiguous.
  • A method is invoked on an incompatible object. For example, a TypeError + exception is thrown if a RegExp class method is "grafted" onto a generic object + and then invoked.
+

+ +
The following example shows how a TypeError exception can + be generated and handled within a try..catch statement. + +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + + public class TypeErrorExample extends Sprite { + public function TypeErrorExample() { + try { + var child:Object = new Object(); + addChild(DisplayObject(child)); + } + catch(e:TypeError) { + trace(e); + } + } + } +} +
is operatorinstanceof operatorsuper statementRegExp classTypeError + Creates a new TypeError object.messageStringContains the message associated with the TypeError object. + + + Creates a new TypeError object. +
arguments + An arguments object is used to store and access a function's arguments.An arguments object is used to store and access a function's arguments. + Object + An arguments object is used to store and access a function's arguments. + Within a function's body, you can access its arguments object by using the local arguments + variable. +

+ The arguments are stored as array elements: the first is accessed as + arguments[0], the second as arguments[1], and so on. The + arguments.length property indicates the number of arguments passed to + the function. There may be a different number of arguments passed than + the function declares. +

+

+ Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. + To get a reference to the function + that called the current function, you must pass a reference to that function as an + argument. An example of this technique can be found in the example for arguments.callee. +

+

ActionScript 3.0 includes a new ...(rest) keyword that is recommended instead of the + arguments class.

+ +
The following example shows uses for various arguments properties, + such as callee and length. + +package { + import flash.display.Sprite; + + public class ArgumentsExample extends Sprite { + public function ArgumentsExample() { + println("Hello World"); + } + + public function println(str:String):void { + trace(arguments.callee == this.println); // true + trace(arguments.length); // 1 + trace(arguments[0]); // Hello World + trace(str); // Hello World + } + } +} +
...(rest)Functioncallee + A reference to the currently executing function.FunctionA reference to the currently executing function. + + A reference to the currently executing function. + + The following code shows how to get a reference to the function + that calls the function named secondFunction(). The firstFunction() function has + the Boolean argument of true + to demonstrate that secondFunction() successfully calls firstFunction() and + to prevent an infinite loop of each function calling the other. + +

Because the callSecond parameter is true, firstFunction() + calls secondFunction() and passes a reference to itself as the only + argument. The function secondFunction() receives this argument and stores it + using a parameter named caller, which is of data type Function. From within secondFunction(), the + caller parameter is then used to call the firstFunction function, + but this time with the callSecond argument set to false.

+

When execution returns to firstFunction(), the trace() + statement is executed because callSecond is false.

+ + package { + import flash.display.Sprite; + + public class ArgumentsExample extends Sprite { + private var count:int = 1; + + public function ArgumentsExample() { + firstFunction(true); + } + + public function firstFunction(callSecond:Boolean) { + trace(count + ": firstFunction"); + if(callSecond) { + secondFunction(arguments.callee); + } + else { + trace("CALLS STOPPED"); + } + } + + public function secondFunction(caller:Function) { + trace(count + ": secondFunction\n"); + count++; + caller(false); + } + } +} +
length + The number of arguments passed to the function.NumberThe number of parameters passed to the function. + + The number of arguments passed to the function. This may be more or less + than the function declares. + +
String + The String class is a data type that represents a string of characters.Object + The String class is a data type that represents a string of characters. The String class + provides methods and properties that let you manipulate primitive string value types. + You can convert the value of any object into a String data type object using the String() + function. +

+ Because all string indexes are zero-based, the index of the last character + for any string x is x.length - 1. +

+ You can call any of the methods of the String class whether you use the constructor method + new String() to create a new string variable or simply assign a string literal value. + Unlike previous versions of ActionScript, it makes no difference whether you use the constructor, + the global function, or simply assign a string literal value. The following lines of code are equivalent: +

+ + var str:String = new String("foo"); + var str:String = "foo"; + var str:String = String("foo"); +

When setting a string variable to undefined, the Flash runtimes coerce undefined + to null. So, the statement:

+
+ var s:String = undefined;
+ sets the value to null instead of undefined. Use the String() + function if you need to use undefined. +
The following example uses the StringExample and + StringHelper classes to show how various methods of the String class are used. + This is accomplished using the following steps: +
  1. The constructor for StringExample declares several local String instances, + which are initialized with various strings and a new StringHelper object.
  2. The StringHelper class has the following methods: +
    • replace(): calls the split() and join() methods of + String to remove a substring of the string passed in with a new one.
    • trim(): calls both trimBack() and trimFront() using the + strings passed in and returns the updated string.
    • trimFront():recursively removes all characters that match the char + parameter, starting from the front of the string and working toward the end, until the first character in + the string does not match char and returns the updated string.
    • trimBack(): recursively removes all characters that match the char + parameter, starting from the end of the string and working backward, until the last character in + the string does not match char and returns the updated string.
    • stringToCharacter(): returns the first character of the string passed to it.
    +
  3. Three strings are then produced using the declared string variables with a call to the + replace() method used to produce the second string and trim() to produce the + third string.
+ +package { + import flash.display.Sprite; + + public class StringExample extends Sprite { + public function StringExample() { + var companyStr:String = new String(" Company X"); + var productStr:String = "Product Z Basic "; + var emptyStr:String = " "; + var strHelper:StringHelper = new StringHelper(); + + var companyProductStr:String = companyStr + emptyStr + productStr; + trace("'" + companyProductStr + "'"); // ' Company X Product Z Basic ' + + companyProductStr = strHelper.replace(companyProductStr, "Basic", "Professional"); + trace("'" + companyProductStr + "'"); // ' Company X Product Z Professional ' + + companyProductStr = strHelper.trim(companyProductStr, emptyStr); + trace("'" + companyProductStr + "'"); // 'Company X Product Z Professional' + } + } +} + +class StringHelper { + public function StringHelper() { + } + + public function replace(str:String, oldSubStr:String, newSubStr:String):String { + return str.split(oldSubStr).join(newSubStr); + } + + public function trim(str:String, char:String):String { + return trimBack(trimFront(str, char), char); + } + + public function trimFront(str:String, char:String):String { + char = stringToCharacter(char); + if (str.charAt(0) == char) { + str = trimFront(str.substring(1), char); + } + return str; + } + + public function trimBack(str:String, char:String):String { + char = stringToCharacter(char); + if (str.charAt(str.length - 1) == char) { + str = trimBack(str.substring(0, str.length - 1), char); + } + return str; + } + + public function stringToCharacter(str:String):String { + if (str.length == 1) { + return str; + } + return str.slice(0, 1); + } +} +
String() global functionString + Creates a new String object initialized to the specified string.valStringThe initial value of the new String object. + + + Creates a new String object initialized to the specified string. + +

+ Note: Because string literals use less overhead than String + objects and are generally easier to use, you should use string literals instead of the + String class unless you have a good reason to use a String object rather than a string literal. +

+ +
charAt + Returns the character in the position specified by the index parameter.The character at the specified index. Or an empty string if the + specified index is outside the range of this string's indices. + + StringindexNumber0An integer specifying the position of a character in the string. The first + character is indicated by 0, and the last character is indicated by + my_str.length - 1. + + + Returns the character in the position specified by the index parameter. + If index is not a number from 0 to string.length - 1, an + empty string is returned. +

+ This method is similar to String.charCodeAt() except that the returned + value is a character, not a 16-bit integer character code. +

+ +
charCodeAt()
charCodeAt + Returns the numeric Unicode character code of the character at the specified + index.The Unicode character code of the character at the specified index. Or + NaN if the index is outside the range of this string's indices. +

Unicode values are defined in the Unicode Character Database + specification.

+ +
Number
indexNumber0An integer that specifies the position of a character in the string. The + first character is indicated by 0, and the last character is indicated by + my_str.length - 1. + +
+ Returns the numeric Unicode character code of the character at the specified + index. If index is not a number from 0 to + string.length - 1, NaN is returned. +

+ This method is similar to String.charAt() except that the returned + value is a 16-bit integer character code, not the actual character. +

+ +
charAt()
concat + Appends the supplied arguments to the end of the String object, converting them to strings if + necessary, and returns the resulting string.A new string consisting of this string concatenated + with the specified parameters. + + StringargsZero or more values to be concatenated. + + + Appends the supplied arguments to the end of the String object, converting them to strings if + necessary, and returns the resulting string. The original value of the source String object + remains unchanged. + + fromCharCode + Returns a string comprising the characters represented by the Unicode character codes + in the parameters.The string value of the specified Unicode character codes. + + StringcharCodesA series of decimal integers that represent Unicode values. +

Unicode values are defined in the Unicode Character Database + specification.

+ +
+ Returns a string comprising the characters represented by the Unicode character codes + in the parameters. + +
indexOf + Searches the string and returns the position of the first occurrence of val + found at or after startIndex within the calling string.The index of the first occurrence of the specified substring or -1. + + intvalStringThe substring for which to search. + + startIndexNumber0An optional integer specifying the starting index of the search. + + + Searches the string and returns the position of the first occurrence of val + found at or after startIndex within the calling string. This index is zero-based, + meaning that the first character in a string is considered to be at index 0--not index 1. If + val is not found, the method returns -1. + + lastIndexOf()lastIndexOf + Searches the string from right to left and returns the index of the last occurrence + of val found before startIndex.The position of the last occurrence of the specified substring or -1 if not found. + + intvalStringThe string for which to search. + + startIndexNumber0x7FFFFFFFAn optional integer specifying the starting index from which to + search for val. The default is the maximum value allowed for an index. + If startIndex is not specified, the search starts at the last item in the string. + + + Searches the string from right to left and returns the index of the last occurrence + of val found before startIndex. The index is zero-based, + meaning that the first character is at index 0, and the last is at string.length + - 1. If val is not found, the method returns -1. + + indexOf()localeCompare + Compares the sort order of two or more strings and returns the result of the comparison as an integer.The value 0 if the strings are equal. Otherwise, a negative integer if the original + string precedes the string argument and a positive integer if the string argument precedes + the original string. In both cases the absolute value of the number represents the difference + between the two strings. + + intotherStringA string value to compare. + valuesOptional set of more strings to compare. + + Compares the sort order of two or more strings and returns the result of the comparison as an integer. While this + method is intended to handle the comparison in a locale-specific way, the ActionScript 3.0 implementation + does not produce a different result from other string comparisons such as the equality (==) or + inequality (!=) operators. + If the strings are equivalent, the return value is 0. + If the original string value precedes the string value specified by other, + the return value is a negative integer, the absolute value of which represents + the number of characters that separates the two string values. + If the original string value comes after other, + the return value is a positive integer, the absolute value of which represents + the number of characters that separates the two string values. + + match + Matches the specifed pattern against the + string.An array of strings consisting of all substrings in + the string that match the specified pattern. + +

If pattern is a regular expression, in order to return an array with + more than one matching substring, the g (global) flag must be set + in the regular expression:

+ +
  • If the g (global) flag is not set, + the return array will contain no more than one match, and the lastIndex + property of the regular expression remains unchanged.
  • If the g (global) flag is set, the method starts the search at + the beginning of the string (index position 0). If a matching substring is an empty string (which + can occur with a regular expression such as /x~~/), the method adds that + empty string to the array of matches, and then continues searching at the next index position. + The lastIndex property of the regular expression is set to 0 after the + method completes.
+ +

If no match is found, the method returns an empty array. If you pass + no value (or an undefined value) as the pattern parameter, + the method returns null.

+ + +
Array
patternThe pattern to match, which can be any type of object, but it is typically + either a string or a regular expression. If the pattern is not a regular expression + or a string, then the method converts it to a string before executing. + +
+ Matches the specifed pattern against the + string. + +
RegExp
replace + Matches the specifed pattern against the string and returns a new string + in which the first match of pattern is replaced with the content specified by repl.The resulting string. Note that the source string remains unchanged. + + StringpatternThe pattern to match, which can be any type of object, but it is typically + either a string or a regular expression. If you specify a pattern parameter + that is any object other than a string or a regular expression, the toString() method is + applied to the parameter and the replace() method executes using the resulting string + as the pattern. + + replObjectTypically, the string that is inserted in place of the matching content. However, you can + also specify a function as this parameter. If you specify a function, the string returned + by the function is inserted in place of the matching content. + +

When you specify a string as the repl parameter and specify a regular expression + as the pattern parameter, you can use the following special $ replacement codes + in the repl string:

+ + $ Code + Replacement Text + $$ + $ + $& + The matched substring. + $` + The portion of the string that precedes the matched substring. + Note that this code uses the straight left single quote character (`), + not the straight single quote character (') or the left curly single quote + character (‘). + $' + The portion of string that follows the matched substring. + Note that this code uses the straight single quote character ('). + $n + The nth captured parenthetical group match, where n is a single + digit 1-9 and $n is not followed by a decimal digit. + $nn + The nnth captured parenthetical group match, where nn is a two-digit + decimal number (01-99). If the nnth capture is undefined, the replacement text + is an empty string. + + +

For example, the following shows the use of the $2 and $1 + replacement codes, which represent the first and second capturing group matched:

+ + var str:String = "flip-flop"; + var pattern:RegExp = /(\w+)-(\w+)/g; + trace(str.replace(pattern, "$2-$1")); // flop-flip + +

When you specify a function as the repl, the replace() method + passes the following parameters to the function: +

+ +
  • + The matching portion of the string. +
  • + Any captured parenthetical group matches are provided as the next arguments. The number of arguments passed + this way will vary depending on the number of parenthetical matches. You can determine the + number of parenthetical matches by checking arguments.length - 3 within the function + code. +
  • + The index position in the string where the match begins. +
  • + The complete string. +
+ +

For example, consider the following:

+ + + var str1:String = "abc12 def34"; + var pattern:RegExp = /([a-z]+)([0-9]+)/; + var str2:String = str1.replace(pattern, replFN); + trace (str2); // 12abc 34def + + function replFN():String { + return arguments[2] + arguments[1]; + } + + +

The call to the replace() method uses a function as the repl + parameter. The regular expression (/([a-z]([0-9]/g) is matched twice. The + first time, the pattern matches the substring "abc12", and the following list + of arguments is passed to the function: +

+ + + {"abc12", "abc", "12", 0, "abc12 def34"} + + +

The second time, the pattern matches the substring "def23", and the + following list of arguments is passed to the function: +

+ + + {"def34", "def", "34", 6, "abc123 def34"} + + +
+ Matches the specifed pattern against the string and returns a new string + in which the first match of pattern is replaced with the content specified by repl. + The pattern parameter can be a string or a regular expression. The repl parameter + can be a string or a function; if it is a function, the string returned + by the function is inserted in place of the match. The original string is not modified. + +

In the following example, only the first instance of "sh" (case-sensitive) + is replaced:

+ + + var myPattern:RegExp = /sh/; + var str:String = "She sells seashells by the seashore."; + trace(str.replace(myPattern, "sch")); + // She sells seaschells by the seashore. + +

In the following example, all instances of "sh" (case-sensitive) + are replaced because the g (global) flag is set in the regular expression:

+ + + var myPattern:RegExp = /sh/g; + var str:String = "She sells seashells by the seashore."; + trace(str.replace(myPattern, "sch")); + // She sells seaschells by the seaschore. + +

In the following example, all instance of "sh" + are replaced because the g (global) flag is set in the regular expression + and the matches are not case-sensitive because the i (ignoreCase) flag is set:

+ + + var myPattern:RegExp = /sh/gi; + var str:String = "She sells seashells by the seashore."; + trace(str.replace(myPattern, "sch")); + // sche sells seaschells by the seaschore. + +
RegExp
search + Searches for the specifed pattern and returns the index of + the first matching substring.The index of the first matching substring, or -1 if + there is no match. Note that the string is zero-indexed; the first character of + the string is at index 0, the last is at string.length - 1. + + intpatternThe pattern to match, which can be any type of object but is typically + either a string or a regular expression.. If the pattern is not a regular expression + or a string, then the method converts it to a string before executing. + Note that if you specify a regular expression, the method ignores the global flag ("g") of the + regular expression, and it ignores the lastIndex property of the regular + expression (and leaves it unmodified). If you pass an undefined value (or no value), + the method returns -1. + + + Searches for the specifed pattern and returns the index of + the first matching substring. If there is no matching substring, the method returns + -1. + + RegExpslice + Returns a string that includes the startIndex character + and all characters up to, but not including, the endIndex character.A substring based on the specified indices. + + StringstartIndexNumber0The zero-based index of the starting point for the slice. If + startIndex is a negative number, the slice is created from right-to-left, where + -1 is the last character. + + endIndexNumber0x7fffffffAn integer that is one greater than the index of the ending point for + the slice. The character indexed by the endIndex parameter is not included in the extracted + string. + If endIndex is a negative number, the ending point is determined by + counting back from the end of the string, where -1 is the last character. + The default is the maximum value allowed for an index. If this parameter is omitted, String.length is used. + + + Returns a string that includes the startIndex character + and all characters up to, but not including, the endIndex character. The original String object is not modified. + If the endIndex parameter is not specified, then the end of the + substring is the end of the string. If the character indexed by startIndex is the same as or to the right of the + character indexed by endIndex, the method returns an empty string. + + + + substr()substring()split + Splits a String object into an array of substrings + by dividing it wherever the specified delimiter parameter + occurs.An array of substrings. + + + + ArraydelimiterThe pattern that specifies where to split this string. This can be any type of + object but is typically either a string or a regular expression. If the delimiter + is not a regular expression or string, then the method converts it to a string before executing. + + limitNumber0x7fffffffThe maximum number of items to place into the array. + The default is the maximum value allowed. + + + + Splits a String object into an array of substrings + by dividing it wherever the specified delimiter parameter + occurs. + +

If the delimiter parameter is a regular expression, only + the first match at a given position of the string is considered, + even if backtracking could find a nonempty substring match at that + position. For example:

+ + + var str:String = "ab"; + var results:Array = str.split(/a~~?/); // results == ["","b"] + + results = str.split(/a~~/); // results == ["","b"].) + + +

If the delimiter parameter is a regular expression + containing grouping parentheses, then each time the + delimiter is matched, the results (including any + undefined results) of the grouping parentheses are spliced into the + output array. For example

+ + + var str:String = "Thi5 is a tricky-66 example."; + var re:RegExp = /(\d+)/; + var results:Array = str.split(re); + // results == ["Thi","5"," is a tricky-","66"," example."] + + +

If the limit parameter is specified, then + the returned array will have no more than the specified + number of elements.

+

If the delimiter is an empty string, an empty + regular expression, or a regular expression that can match an empty + string, each single character in the string + is output as an element in the array.

+ +

If the delimiter parameter is undefined, the entire + string is placed into the first element of the returned + array.

+ +
Array.join()RegExp
substr + Returns a substring consisting of the characters that start at the specified + startIndex and with a length specified by len.A substring based on the specified parameters. + + StringstartIndexNumber0An integer that specified the index of the first character to be + used to create the substring. If startIndex is a negative number, the + starting index is determined from the end of the string, where -1 is the + last character. + + lenNumber0x7fffffffThe number of characters in the substring being created. + The default value is the maximum value allowed. If len + is not specified, the substring includes all the characters from startIndex + to the end of the string. + + + Returns a substring consisting of the characters that start at the specified + startIndex and with a length specified by len. The original + string is unmodified. + + + substring + Returns a string consisting of the character specified by startIndex + and all characters up to endIndex - 1.A substring based on the specified parameters. + + StringstartIndexNumber0An integer specifying the index of the first character used to create + the substring. Valid values for startIndex are 0 through + String.length. If startIndex is a negative value, 0 + is used. + + endIndexNumber0x7fffffffAn integer that is one greater than the index of the last character in the + extracted substring. Valid values for endIndex are 0 through + String.length. The character at endIndex is not included in + the substring. The default is the maximum value allowed for an index. + If this parameter is omitted, String.length is used. If + this parameter is a negative value, 0 is used. + + + Returns a string consisting of the character specified by startIndex + and all characters up to endIndex - 1. If endIndex is not + specified, String.length is used. If the value of startIndex + equals the value of endIndex, the method returns an empty string. + If the value of startIndex is greater than the value of + endIndex, the parameters are automatically swapped before the function + executes. The original string is unmodified. + + + toLocaleLowerCase + Returns a copy of this string, with all uppercase characters converted + to lowercase.A copy of this string with all uppercase characters converted + to lowercase. + + String + Returns a copy of this string, with all uppercase characters converted + to lowercase. The original string is unmodified. While this + method is intended to handle the conversion in a locale-specific way, the ActionScript 3.0 implementation + does not produce a different result from the toLowerCase() method. + + toLowerCase()toLocaleUpperCase + Returns a copy of this string, with all lowercase characters converted + to uppercase.A copy of this string with all lowercase characters converted + to uppercase. + + String + Returns a copy of this string, with all lowercase characters converted + to uppercase. The original string is unmodified. While this + method is intended to handle the conversion in a locale-specific way, the ActionScript 3.0 implementation + does not produce a different result from the toUpperCase() method. + + + toUpperCase()toLowerCase + Returns a copy of this string, with all uppercase characters converted + to lowercase.A copy of this string with all uppercase characters converted + to lowercase. + + String + Returns a copy of this string, with all uppercase characters converted + to lowercase. The original string is unmodified. + +

This method converts all characters (not simply A-Z) for which Unicode lowercase + equivalents exist:

+ + + var str:String = " JOSÉ BARÇA"; + trace(str.toLowerCase()); // josé barça + +

These case mappings are defined in the Unicode Character Database + specification.

+ + +
toUpperCase()
toUpperCase + Returns a copy of this string, with all lowercase characters converted + to uppercase.A copy of this string with all lowercase characters converted + to uppercase. + + + String + Returns a copy of this string, with all lowercase characters converted + to uppercase. The original string is unmodified. + +

This method converts all characters (not simply a-z) for which Unicode uppercase + equivalents exist:

+ + + var str:String = "José Barça"; + trace(str.toUpperCase()); // JOSÉ BARÇA + +

These case mappings are defined in the Unicode Character Database + specification.

+ + +
toLowerCase()
valueOf + Returns the primitive value of a String instance.The value of the string. + + String + Returns the primitive value of a String instance. This method is designed to + convert a String object into a primitive string value. Because Flash runtimes + automatically call valueOf() when necessary, + you rarely need to call this method explicitly. + + + length + An integer specifying the number of characters in the specified String object.int + An integer specifying the number of characters in the specified String object. +

+ Because all string indexes are zero-based, the index of the last character for any + string x is x.length - 1. +

+ +
Class + A Class object is created for each class definition in a program.Object + A Class object is created for each class definition in a program. Every Class object is an instance + of the Class class. The Class object contains the static properties and methods of the class. The + class object creates instances of the class when invoked using the new operator. + +

Some methods, such as flash.net.getClassByAlias(), return an object of type Class. + Other methods may have a parameter of type Class, such as flash.net.registerClassAlias().

+

The class name is the reference to the Class object, as this example shows:

+
 
+ class Foo {
+ }
+ 
+

The class Foo{} statement is the class definition that creates the Class object Foo. Additionally, + the statement new Foo() will create a new instance of class Foo, and the result will be of type Foo.

+

Use the class statement to declare your classes. Class objects are useful for advanced + techniques, such as assigning classes to an existing instance object at runtime, as shown in the "Examples" + section below.

+

Any static properties and methods of a class live on the class's Class object. Class, itself, declares + prototype.

+ +

Generally, you do not need to declare or create variables of type Class manually. However, in the following + code, a class is assigned as a public Class property circleClass, and you can refer to this Class property + as a property of the main Library class:

+ + package { + import flash.display.Sprite; + public class Library extends Sprite { + + public var circleClass:Class = Circle; + public function Library() { + } + } + } + + import flash.display.Shape; + class Circle extends Shape { + public function Circle(color:uint = 0xFFCC00, radius:Number = 10) { + graphics.beginFill(color); + graphics.drawCircle(radius, radius, radius); + } + } + + +

Another SWF file can load the resulting Library.swf file and then instantiate objects of type Circle. The + following example shows one way to get access to a child SWF file's assets. (Other techniques include using + flash.utils.getDefnitionByName() or importing stub definitions of the child SWF file.)

+ + + package { + import flash.display.Sprite; + import flash.display.Shape; + import flash.display.Loader; + import flash.net.URLRequest; + import flash.events.Event; + public class LibaryLoader extends Sprite { + public function LibaryLoader() { + var ldr:Loader = new Loader(); + var urlReq:URLRequest = new URLRequest("Library.swf"); + ldr.load(urlReq); + ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); + } + private function loaded(event:Event):void { + var library:Object = event.target.content; + var circle:Shape = new library.circleClass(); + addChild(circle); + } + } + } + +

In ActionScript 3.0, you can create embedded classes for external assets (such as images, sounds, or fonts) that are + compiled into SWF files. In earlier versions of ActionScript, you associated those assets using a linkage ID with the + MovieClip.attachMovie() method. In ActionScript 3.0, each embedded asset is represented by a unique embedded + asset class. Therefore, you can use the new operator to instantiate the asset's associated class and call + methods and properties on that asset.

+

For example, if you are using an MXML compiler to generate SWF files, you would create an embedded + class as follows:

+ + [Embed(source="bratwurst.jpg")] + public var imgClass:Class; + +

And, to instantiate it, you write the following:

+ + var myImg:Bitmap = new imgClass(); + + +
The following example shows how to use Class objects to defer until runtime + the decision about which class to instantiate using the following steps: +
  1. Declare two classes as ClassA and ClassB.
  2. Declare a variable of type Class named classToConstruct and one of type + Boolean chooseClassA, which is set to true in this case, + but your code could use a custom test expression to set the value of that variable.
+ +package { + import flash.display.Sprite; + + public class ClassExample extends Sprite { + public function ClassExample() { + var classToConstruct:Class; + var classInstance:Object; + + classToConstruct = ClassA; + classInstance = new classToConstruct(); + trace(classInstance); // [object ClassA] + + classToConstruct = ClassB; + classInstance = new classToConstruct(); + trace(classInstance); // [object ClassB] + } + } +} + +class ClassA { +} + +class ClassB { +} +
Object.prototypenew operator
Namespace + +The Namespace class contains methods and properties for defining and working with namespaces.The Namespace class contains methods and properties for defining and +working with namespaces of XML objects. + +Object + +The Namespace class contains methods and properties for defining and working with namespaces. +There are three scenarios for using namespaces: + +
  • Namespaces of XML objects Namespaces associate a namespace prefix with a Uniform Resource Identifier (URI) +that identifies the namespace. The prefix is a string used to reference the namespace within an +XML object. If the prefix is undefined, when the XML is converted to a string, a prefix is +automatically generated. +
  • Namespace to differentiate methods Namespaces can differentiate methods with the same name to perform different tasks. +If two methods have the same name but separate namespaces, they can perform different tasks. +
  • Namespaces for access control +Namespaces can be used to control access to a group of +properties and methods in a class. If you place the +properties and methods into a private +namespace, they are +inaccessible to any code that does not have access to +that namespace. You can grant access to the group of +properties and methods by passing the namespace to +other classes, methods or functions. +
+ +

This class shows two forms of the constructor method because each form accepts +different parameters.

+ +

This class (along with the XML, XMLList, and QName classes) implements +powerful XML-handling standards defined in ECMAScript for XML +(E4X) specification (ECMA-357 edition 2).

+ +
The following example shows how to work with namespaces defined in XML objects. + This is accomplished with the following steps: +
  1. The example defines three Namespace objects, each with a unique URI that defines a namespace.
  2. The example defines an XML variable named myXML and assigns it to the return value of + getRSS(). The getRSS() method defines an XML object that contains several namespaces + and returns that XML object.
  3. The example declares and evaluates an Array variable by calling the parseRSS() method with + myXML passed to it. In parseRSS(), the default XML namespace is defined as + rss and the example defines an XMLList variable by assigning the list of item + objects in myXML. An array is created and populated with various nodes within + myXML.item. The array is then returned.
  4. The elements in the array are printed using a for loop and three calls to + trace().
+ +package { + import flash.display.Sprite; + + public class NamespaceExample extends Sprite { + private var rss:Namespace = new Namespace("http://purl.org/rss/1.0/"); + private var rdf:Namespace = new Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); + private var dc:Namespace = new Namespace("http://purl.org/dc/elements/1.1/"); + + public function NamespaceExample() { + var myXML:XML = getRSS(); + var rssItems:Array = parseRSS(myXML); + + var len:uint = rssItems.length; + for (var i:uint; i < len; i++) { + trace(rssItems[i].title); + trace(rssItems[i].creator); + trace(rssItems[i].date); + // Adobe Flash Developer Center + // Adobe + // 2005-08-08 + // Flex Developer Center + // Adobe + // 2005-10-16 + } + } + + private function parseRSS(rssXML:XML):Array { + default xml namespace = rss; + + var items:XMLList = rssXML.item; + + var arr:Array = new Array(); + var len:uint = items.length(); + for (var i:uint; i < len; i++) { + arr.push({title:items[i].title, creator:items[i].dc::creator, date:items[i].dc::date}); + } + + return arr; + } + + private function getRSS():XML { + var myXML:XML = <rdf:RDF + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns="http://purl.org/rss/1.0/" + xmlns:dc="http://purl.org/dc/elements/1.1/" + > + <channel rdf:about="http://www.xml.com/cs/xml/query/q/19"> + <title>Test RSS</title> + <link>http://www.adobe.com/</link> + <description>This is a test RSS document.</description> + <language>en-us</language> + <items> + <rdf:Seq> + <rdf:li rdf:resource="http://www.adobe.com/devnet/flash/"/> + <rdf:li rdf:resource="http://www.adobe.com/devnet/flex/"/> + </rdf:Seq> + </items> + </channel> + <item rdf:about="http://www.adobe.com/devnet/flash/"> + <title>Adobe Flash Developer Center</title> + <link>http://www.adobe.com/devnet/flash/</link> + <description>Welcome to the Flash Developer Center</description> + <dc:creator>Adobe</dc:creator> + <dc:date>2005-08-08</dc:date> + </item> + <item rdf:about="http://www.adobe.com/devnet/flex/"> + <title>Flex Developer Center</title> + <link>http://www.adobe.com/devnet/flex/</link> + <description>Welcome to the Flex Developer Center</description> + <dc:creator>Adobe</dc:creator> + <dc:date>2005-10-16</dc:date> + </item> + </rdf:RDF>; + + return myXML; + } + } +} +
The following example shows how namespaces can be used to differentiate methods that have + the same name but perform different tasks. In this example, three methods named hello() + reside in separate namespaces; each returns a different string when called. + +package { + + import flash.display.Sprite; + + public class Namespace_2_Example extends Sprite { + public function Namespace_2_Example() { + var vocab:MultilingualVocabulary = new MultilingualVocabulary(); + + trace(vocab.hello()); // hello + + var languages:Array = vocab.getLanguages(); + + for (var i:uint; i < languages.length; i++) { + var ns:Namespace = languages[i]; + if (ns != null) { + trace(ns.toString() + ": " + vocab.ns::hello()); + // hello + // MultilingualVocabulary:Hawaiian: aloha + // MultilingualVocabulary:French: bon jour + } + } + } + } +} + +class MultilingualVocabulary { + public namespace French; + public namespace Hawaiian; + private var languages:Array; + + public function MultilingualVocabulary() { + languages = new Array(Hawaiian, French); + } + + public function hello():String { + return "hello"; + } + + Hawaiian function hello():String { + return "aloha"; + } + + French function hello():String { + return "bon jour"; + } + + public function getLanguages():Array { + return languages; + } +} + The following example uses namespace names to select an appropriate + variable value. It shows how you can store a namespace value in a variable and use + that variable to refer to objects within that namespace. +

The example defines namespaces and colors that correspond to mouse + states for a rectangular button. Each time the button is drawn, the example applies + the appropriate color (out is red; over is yellow; down is white) by referencing the bgcolor + variable for the corresponding namespace (out, over, down).

+ +package { + import flash.display.Sprite; + + public class Namespace_3_Example extends Sprite { + public function Namespace_3_Example() { + addChild(new StateButton("Press Me.")); + } + } +} + +import flash.display.Sprite; +import flash.text.TextField; +import flash.events.Event; +import flash.events.MouseEvent; + +class StateButton extends Sprite{ + private namespace out; + private namespace over; + private namespace down; + private var label:TextField; + private var labelTxt:String; + private var ns:Namespace; + out var bgColor:Number = 0xFF0000; + over var bgColor:Number = 0xFFFF00; + down var bgColor:Number = 0xFFFFFF; + + public function StateButton(str:String) { + buttonMode = true; + labelTxt = str; + ns = out; + draw(); + addLabel(); + addListeners(); + } + + private function addLabel():void { + label = new TextField(); + label.text = labelTxt; + label.width = 50; + label.height = 20; + label.mouseEnabled = false; + addChild(label); + } + + private function addListeners():void { + addEventListener(MouseEvent.MOUSE_UP, mouseOverHandler); + addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); + addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); + addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + } + + private function mouseOutHandler(e:Event):void { + ns = out; + draw(); + } + + private function mouseOverHandler(e:Event):void { + ns = over; + draw(); + } + + private function mouseDownHandler(e:Event):void { + ns = down; + draw(); + } + + private function draw():void { + this.graphics.clear(); + this.graphics.beginFill(ns::bgColor); + this.graphics.drawRect(0, 0, 60, 20); + } +} +
XMLXMLListQNameECMAScript for XML (E4X) specification (ECMA-357 edition 2)Namespace + Creates a Namespace object according to the values of the prefixValue and uriValue parameters.prefixValueThe prefix to use for the namespace. + + uriValueThe Uniform Resource Identifier (URI) of the namespace. + + + Creates a Namespace object, given the prefixValue and uriValue. + + + Creates a Namespace object according to the values of the prefixValue and uriValue parameters. + This constructor requires both parameters. +

The value of the prefixValue parameter is assigned to the prefix + property as follows:

+
  • If undefined is passed, prefix is set to undefined.
  • If the value is a valid XML name, as determined by the isXMLName() function, it is converted to a string and assigned to the prefix property.
  • If the value is not a valid XML name, the prefix property is set to undefined.
+ +

The value of the uriValue parameter is assigned to the uri + property as follows:

+
  • If a QName object is passed, the uri property is set to the value of the QName object's uri property.
  • Otherwise, the uriValue parameter is converted to a string and assigned to the uri property.
+

Note: This class shows two constructor method entries because each form accepts + different parameters. The constructor behaves differently depending on the type and number of + arguments passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+ +
Namespace + Creates a Namespace object.uriValueThe Uniform Resource Identifier (URI) of the namespace. + + + Creates a Namespace object, given the uriValue. + + + Creates a Namespace object. + The values assigned to the uri and prefix properties + of the new Namespace object depend on the type of value passed for the uriValue parameter: +
  • If no value is passed, the prefix and uri properties are set to an empty string.
  • If the value is a Namespace object, a copy of the object is created.
  • If the value is a QName object, the uri property is set to the uri property of the QName object.
+

Note: This class shows two constructor entries because each form accepts + different parameters. The constructor behaves differently depending on the type and number of + parameters passed, as detailed in each entry. ActionScript 3.0 does not support method or constructor overloading.

+ +
toString + Equivalent to the Namespace.uri property.The Uniform Resource Identifier (URI) of the namespace, as a string. + + + StringEquivalent to the Namespace.uri property. + + + Equivalent to the Namespace.uri property. + + valueOf + Returns the URI value of the specified object.The Uniform Resource Identifier (URI) of the namespace, as a string. + + + StringEquivalent to the Namespace.uri property. + + + Returns the URI value of the specified object. + + prefix + The prefix of the namespace.StringThe prefix of the namespace. + + + The prefix of the namespace. + + uri + The Uniform Resource Identifier (URI) of the namespace.StringThe Uniform Resource Identifier (URI) of the namespace. + + + The Uniform Resource Identifier (URI) of the namespace. + +
XML + The XML class contains methods and properties for working with XML objects.Object + The XML class contains methods and properties for working with XML objects. The XML class + (along with the XMLList, Namespace, and QName classes) implements the + powerful XML-handling standards defined in ECMAScript for XML + (E4X) specification (ECMA-357 edition 2). + +

Use the toXMLString() method to return a string representation of the XML object + regardless of whether the XML object has simple content or complex content.

+ +

Note: The XML class (along with related classes) from ActionScript 2.0 has been + renamed XMLDocument and moved into the flash.xml package. + It is included in ActionScript 3.0 for backward compatibility.

+ + +
The following example first creates an XML variable and adds nodes to it. + Then XML properties are used to find and print XML nodes. Notice that the "at" + (@) symbol is used in several of the trace() calls to locate information + by attribute name. + +package { + import flash.display.Sprite; + + public class XmlExample extends Sprite { + public function XmlExample() { + var employees:XML = + <employees> + <employee ssn="123-123-1234"> + <name first="John" last="Doe"/> + <address> + <street>11 Main St.</street> + <city>San Francisco</city> + <state>CA</state> + <zip>98765</zip> + </address> + </employee> + <employee ssn="789-789-7890"> + <name first="Mary" last="Roe"/> + <address> + <street>99 Broad St.</street> + <city>Newton</city> + <state>MA</state> + <zip>01234</zip> + </address> + </employee> + </employees>; + + trace(employees.employee[0].address.zip); // 98765 + + trace(employees.employee[1].@ssn); // 789-789-7890 + + trace(employees.employee.name); // <name first="John" last="Doe"/> + // <name first="Mary" last="Roe"/> + + trace(employees..zip[0]); // 98765 + + trace(employees..@ssn[1]); // 789-789-7890 + + trace(employees..name); // <name first="John" last="Doe"/> + // <name first="Mary" last="Roe"/> + + trace(employees.employee[0].address.*); // <street>11 Main St.</street> + // <city>San Francisco</city> + // <state>CA</state> + // <zip>98765</zip> + var node:String = "zip"; + trace(employees.employee[0].address[node]); // 98765 + + var attribute:String = "ssn"; + trace(employees.employee[1].@[attribute]); // 789-789-7890 + + for each (var num:XML in employees..@ssn) { + trace(num); // 123-123-1234 + } // 789-789-7890 + + var ssnToFind:String = "789-789-7890"; + trace(employees.employee.(@ssn == ssnToFind).toXMLString()); + // <employee ssn="789-789-7890"> + // <name first="Mary" last="Roe"/> + // <address> + // <street>99 Broad St.</street> + // <city>Newton</city> + // <state>MA</state> + // <zip>01234</zip> + // </address> + // </employee> + } + } +} +
NamespaceQNameXMLListXML.toXMLString()ECMAScript for XML (E4X) specification (ECMA-357 edition 2)XML + Creates a new XML object.valueObjectAny object that can be converted to XML with the top-level + XML() function. + + + Creates a new XML object. You must use the constructor to create an + XML object before you call any of the methods of the XML class. + +

Use the toXMLString() method to return a string representation of the XML object + regardless of whether the XML object has simple content or complex content.

+ +
The following example shows how you can load a remote XML document in ActionScript 3.0 using the URLLoader class in Flash Professional. + Example provided by + ActionScriptExamples.com. + +// +// Requires: +// - TextArea control UI component in the Flash Professional Library. +// +import fl.controls.TextArea; + +var xml:XML; + +var urlRequest:URLRequest = new URLRequest("http://www.helpexamples.com/flash/xml/menu.xml"); + +var urlLoader:URLLoader = new URLLoader(); +urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); +urlLoader.load(urlRequest); + +var textArea:TextArea = new TextArea(); +textArea.move(5, 5); +textArea.setSize(stage.stageWidth - 10, stage.stageHeight - 10); +addChild(textArea); + +function urlLoader_complete(evt:Event):void { + xml = new XML(evt.currentTarget.data); + textArea.text = xml.toXMLString(); +} + Here's another variation using all ActionScript. + Example provided by + ActionScriptExamples.com. + +var xml:XML; +var textArea:TextField = new TextField(); +textArea.width = 300; + +var urlRequest:URLRequest = new URLRequest("http://www.helpexamples.com/flash/xml/menu.xml"); +var urlLoader:URLLoader = new URLLoader(); +urlLoader.dataFormat = URLLoaderDataFormat.TEXT; +urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); +urlLoader.load(urlRequest); + +function urlLoader_complete(evt:Event):void { + xml = new XML(evt.target.data); + textArea.text = xml.toXMLString(); + addChild(textArea); +} +
XML() global functionXML.toXMLString()
addNamespace + Adds a namespace to the set of in-scope namespaces for the XML object.The new XML object, with the namespace added. + + XMLnsObjectThe namespace to add to the XML object. + + + Adds a namespace to the set of in-scope namespaces for the XML object. If the namespace already + exists in the in-scope namespaces for the XML object (with a prefix matching that of the given + parameter), then the prefix of the existing namespace is set to undefined. If the input parameter + is a Namespace object, it's used directly. If it's a QName object, the input parameter's + URI is used to create a new namespace; otherwise, it's converted to a String and a namespace is created from + the String. + + This example uses a namespace defined in one XML object and applies it + to another XML object: + +var xml1:XML = <ns:foo xmlns:ns="www.example.com/ns" />; +var nsNamespace:Namespace = xml1.namespace(); + +var xml2:XML = <bar />; +xml2.addNamespace(nsNamespace); +trace(xml2.toXMLString()); // <bar xmlns:ns="www.example.com/ns"/> +appendChild + Appends the given child to the end of the XML object's properties.The resulting XML object. + + XMLchildObjectThe XML object to append. + + + Appends the given child to the end of the XML object's properties. + The appendChild() method takes an XML object, an XMLList object, or + any other data type that is then converted to a String. + +

Use the delete (XML) operator to remove XML nodes.

+ +
This example appends a new element to the end of the child list of an XML object: + +var xml:XML = + <body> + <p>hello</p> + </body>; + +xml.appendChild(<p>world</p>); +trace(xml.p[0].toXMLString()); // <p>hello</p> +trace(xml.p[1].toXMLString()); // <p>world</p> +
delete (XML) operator
attribute + Returns the XML value of the attribute that has the name matching the attributeName + parameter.An XMLList object or an empty XMLList object. Returns an empty XMLList object + when an attribute value has not been defined. + + XMLListattributeNameThe name of the attribute. + + + Returns the XML value of the attribute that has the name matching the attributeName + parameter. Attributes are found within XML elements. + In the following example, the element has an attribute named "gender" + with the value "boy": <first gender="boy">John</first>. + +

The attributeName parameter can be any data type; however, + String is the most common data type to use. When passing any object other than a QName object, + the attributeName parameter uses the toString() method + to convert the parameter to a string.

+ +

If you need a qualified name reference, you can pass in a QName object. A QName object + defines a namespace and the local name, which you can use to define the qualified name of an + attribute. Therefore calling attribute(qname) is not the same as calling + attribute(qname.toString()).

+ +
This example shows a QName object passed into the attribute() method. The + localName property is attr and the namespace property + is ns. + + var xml:XML = <ns:node xmlns:ns = "http://uri" ns:attr = '7' /> + var qn:QName = new QName("http://uri", "attr"); + trace (xml.attribute(qn)); // 7 + To return an attribute with a name that matches an ActionScript reserved word, + use the attribute() method instead of the attribute identifier (@) + operator, as in the following example: + + var xml:XML = <example class="first" /> + trace(xml.attribute("class")); + +
XML.attributes()QNameNamespaceXML.elements()attribute identifier (&#064;) operator
attributes + Returns a list of attribute values for the given XML object.The list of attribute values. + + XMLList + Returns a list of attribute values for the given XML object. Use the name() + method with the attributes() method to return the name of an attribute. + Use of xml.attributes() is equivalent to xml.@*. + + The following example returns the name of the attribute: + + +var xml:XML=<example id='123' color='blue'/> +trace(xml.attributes()[1].name()); //color + This example returns the names of all the attributes: + + +var xml:XML = <example id='123' color='blue'/> +var attNamesList:XMLList = xml.@*; + +trace (attNamesList is XMLList); // true +trace (attNamesList.length()); // 2 + +for (var i:int = 0; i < attNamesList.length(); i++) +{ + trace (typeof (attNamesList[i])); // xml + trace (attNamesList[i].nodeKind()); // attribute + trace (attNamesList[i].name()); // id and color +} +XML.attribute()XML.name()&#064; operatorchildIndex + Identifies the zero-indexed position of this XML object within the context of its parent.The position of the object. Returns -1 as well as positive integers. + + int + Identifies the zero-indexed position of this XML object within the context of its parent. + + This example shows the use of the childIndex() method: + +var xml:XML = + <foo> + <bar /> + text + <bob /> + </foo>; +trace(xml.bar.childIndex()); // 0 +trace(xml.bob.childIndex()); // 2 +child + Lists the children of an XML object.An XMLList object of child nodes that match the input parameter. + + XMLListpropertyNameObjectThe element name or integer of the XML child. + + + Lists the children of an XML object. An XML child is an XML element, text node, comment, + or processing instruction. + +

Use the propertyName parameter to list the + contents of a specific XML child. For example, to return the contents of a child named + <first>, use child.name("first"). You can generate the same result + by using the child's index number. The index number identifies the child's position in the + list of other XML children. For example, name.child(0) returns the first child + in a list.

+ +

Use an asterisk (~~) to output all the children in an XML document. + For example, doc.child("~~").

+ +

Use the length() method with the asterisk (~~) parameter of the + child() method to output the total number of children. For example, + numChildren = doc.child("~~").length().

+ +
This example shows the use of the child() method to identify child + elements with a specified name: + +var xml:XML = + <foo> + <bar>text1</bar> + <bar>text2</bar> + </foo>; +trace(xml.child("bar").length()); // 2 +trace(xml.child("bar")[0].toXMLString()); // <bar>text1</bar> +trace(xml.child("bar")[1].toXMLString()); // <bar>text2</bar> +
XML.elements()XMLList classXML.length()
children + Lists the children of the XML object in the sequence in which they appear.An XMLList object of the XML object's children. + + XMLList + Lists the children of the XML object in the sequence in which they appear. An XML child + is an XML element, text node, comment, or processing instruction. + + This example shows the use of the children() method: + +XML.ignoreComments = false; +XML.ignoreProcessingInstructions = false; +var xml:XML = + <foo id="22"> + <bar>44</bar> + text + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml.children().length()); // 4 +trace(xml.children()[0].toXMLString()); // <bar>44</bar> +trace(xml.children()[1].toXMLString()); // text +trace(xml.children()[2].toXMLString()); // <!-- comment --> +trace(xml.children()[3].toXMLString()); // <?instruction ?> +comments + Lists the properties of the XML object that contain XML comments.An XMLList object of the properties that contain comments. + + XMLList + Lists the properties of the XML object that contain XML comments. + + This example shows the use of the comments() method: + +XML.ignoreComments = false; +var xml:XML = + <foo> + <!-- example --> + <!-- example2 --> + </foo>; +trace(xml.comments().length()); // 2 +trace(xml.comments()[1].toXMLString()); // <!-- example2 --> +contains + Compares the XML object against the given value parameter.If the XML object matches the value parameter, then true; otherwise false. + + BooleanvalueXMLA value to compare against the current XML object. + + + Compares the XML object against the given value parameter. + + This example shows the use of the contains() method: + +var xml:XML = + <order> + <item>Rice</item> + <item>Kung Pao Shrimp</item> + </order>; +trace(xml.item[0].contains(<item>Rice</item>)); // true +trace(xml.item[1].contains(<item>Kung Pao Shrimp</item>)); // true +trace(xml.item[1].contains(<item>MSG</item>)); // false +copy + Returns a copy of the given XML object.The copy of the object. + + XML + Returns a copy of the given XML object. The copy is a duplicate of the entire tree of nodes. + The copied XML object has no parent and returns null if you attempt to call the + parent() method. + + This example shows that the copy() method creates a new instance of an XML object. + When you modify the copy, the original remains unchanged: + +var xml1:XML = <foo />; +var xml2:XML = xml1.copy(); +xml2.appendChild(<bar />); +trace(xml1.bar.length()); // 0 +trace(xml2.bar.length()); // 1 +defaultSettings + Returns an object with the following properties set to the default values: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and + prettyPrinting.An object with properties set to the default settings. + + Object + Returns an object with the following properties set to the default values: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, prettyIndent, and + prettyPrinting. The default values are as follows: + +
  • ignoreComments = true
  • ignoreProcessingInstructions = true
  • ignoreWhitespace = true
  • prettyIndent = 2
  • prettyPrinting = true
+ +

Note: You do not apply this method to an instance of the XML class; you apply it to + XML, as in the following code: var df:Object = XML.defaultSettings().

+ +
The following example shows: how to apply some custom settings (for including comments and processing + instructions) prior to setting an XML object; how to then revert back to the default settings before setting another XML + object; and then how to set the custom settings again (for setting any more XML objects): + +XML.ignoreComments = false; +XML.ignoreProcessingInstructions = false; +var customSettings:Object = XML.settings(); + +var xml1:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml1.toXMLString()); +// <foo> +// <!-- comment --> +// <?instruction ?> +// </foo> + +XML.setSettings(XML.defaultSettings()); +var xml2:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml2.toXMLString()); +
XML.ignoreCommentsXML.ignoreProcessingInstructionsXML.ignoreWhitespaceXML.prettyIndentXML.prettyPrintingXML.setSettings()XML.settings()
descendants + Returns all descendants (children, grandchildren, great-grandchildren, and so on) of the + XML object that have the given name parameter.An XMLList object of matching descendants. If there are no descendants, returns an + empty XMLList object. + + XMLListnameObject*The name of the element to match. + + + Returns all descendants (children, grandchildren, great-grandchildren, and so on) of the + XML object that have the given name parameter. The name parameter + is optional. The name parameter can be a QName object, a String data type + or any other data type that is then converted to a String data type. + +

To return all descendants, use the "~~" parameter. If no parameter is passed, + the string "~~" is passed and returns all descendants of the XML object.

+ +
To return descendants with names that match ActionScript reserved words, use the + descendants() method instead of the descendant (..) operator, as in the + following example: + +var xml:XML = + <enrollees> + <student id="239"> + <class name="Algebra" /> + <class name="Spanish 2"/> + </student> + <student id="206"> + <class name="Trigonometry" /> + <class name="Spanish 2" /> + </student> + </enrollees> +trace(xml.descendants("class")); + The following example shows that the descendants() method returns an XMLList object + that contains all descendant objects, including children, grandchildren, and so on: + +XML.ignoreComments = false; +var xml:XML = + <body> + <!-- comment --> + text1 + <a> + <b>text2</b> + </a> + </body>; +trace(xml.descendants("*").length()); // 5 +trace(xml.descendants("*")[0]); // // <!-- comment --> +trace(xml.descendants("*")[1].toXMLString()); // text1 +trace(xml.descendants("a").toXMLString()); // <a><b>text2</b></a> +trace(xml.descendants("b").toXMLString()); // <b>text2</b> +
descendant accessor (..) operator
elements + Lists the elements of an XML object.An XMLList object of the element's content. The element's content falls between the start and + end tags. If you use the asterisk (~~) to call all elements, both the + element's tags and content are returned. + + XMLListnameObject*The name of the element. An element's name is surrounded by angle brackets. + For example, "first" is the name in this example: + <first></first>. + + + Lists the elements of an XML object. An element consists of a start and an end tag; + for example <first></first>. The name parameter + is optional. The name parameter can be a QName object, a String data type, + or any other data type that is then converted to a String data type. Use the name parameter to list a specific element. For example, + the element "first" returns "John" in this example: + <first>John</first>. + +

To list all elements, use the asterisk (~~) as the + parameter. The asterisk is also the default parameter.

+ +

Use the length() method with the asterisk parameter to output the total + number of elements. For example, numElement = addressbook.elements("~~").length().

+ +
The following example shows that the elements() method returns a + list of elements only + — not comments, text properties, or processing instructions: + +var xml:XML = + <foo> + <!-- comment --> + <?instruction ?> + text + <a>1</a> + <b>2</b> + </foo>; +trace(xml.elements("*").length()); // 2 +trace(xml.elements("*")[0].toXMLString()); // <a>1</a> +trace(xml.elements("b").length()); // 1 +trace(xml.elements("b")[0].toXMLString()); // <b>2</b> + To return elements with names that match ActionScript reserved words, + use the elements() method instead of the XML dot (.) operator, + as in the following example: + +var xml:XML = + <student id="206"> + <class name="Trigonometry" /> + <class name="Spanish 2" /> + </student> +trace(xml.elements("class")); +
XML.child()XMLList classXML.length()XML.attribute()XML dot (.) operator
hasComplexContent + Checks to see whether the XML object contains complex content.If the XML object contains complex content, true; otherwise false. + + Boolean + Checks to see whether the XML object contains complex content. An XML object contains complex content if + it has child elements. XML objects that representing attributes, comments, processing instructions, + and text nodes do not have complex content. However, an object that contains these can + still be considered to contain complex content (if the object has child elements). + + The following example shows an XML object with one property named a that has + simple content and one property named a that has complex content: + +var xml:XML = + <foo> + <a> + text + </a> + <a> + <b/> + </a> + </foo>; +trace(xml.a[0].hasComplexContent()); // false +trace(xml.a[1].hasComplexContent()); // true + +trace(xml.a[0].hasSimpleContent()); // true +trace(xml.a[1].hasSimpleContent()); // false +XML.hasSimpleContent()hasOwnProperty + Checks to see whether the object has the property specified by the p parameter.If the property exists, true; otherwise false. + + BooleanpStringThe property to match. + + + Checks to see whether the object has the property specified by the p parameter. + + The following example uses the hasOwnProperty() method to ensure + that a property (b) exists prior to evaluating an expression (b == "11") that uses the + property: + +var xml:XML = + <foo> + <a /> + <a> + <b>10</b> + </a> + <a> + <b>11</b> + </a> + </foo>; +trace(xml.a.(hasOwnProperty("b") && b == "11")); + If the last line in this example were the following, Flash Player would throw an exception since + the first element named a does not have a property named b: +

+

trace(xml.a.(b == "11"));
+

+
The following example uses the hasOwnProperty() method to ensure + that a property (item) exists prior to evaluating an expression + (item.contains("toothbrush")) that uses the + property: + +var xml:XML = + <orders> + <order id='1'> + <item>toothbrush</item> + <item>toothpaste</item> + </order> + <order> + <returnItem>shoe polish</returnItem> + </order> + </orders>; +trace(xml.order.(hasOwnProperty("item") && item.contains("toothbrush"))); +
hasSimpleContent + Checks to see whether the XML object contains simple content.If the XML object contains simple content, true; otherwise false. + + Boolean + Checks to see whether the XML object contains simple content. An XML object contains simple content + if it represents a text node, an attribute node, or an XML element that has no child elements. + XML objects that represent comments and processing instructions do not contain simple + content. + + The following example shows an XML object with one property named a that has + simple content and one property named a that has complex content: + +var xml:XML = + <foo> + <a> + text + </a> + <a> + <b/> + </a> + </foo>; +trace(xml.a[0].hasComplexContent()); // false +trace(xml.a[1].hasComplexContent()); // true + +trace(xml.a[0].hasSimpleContent()); // true +trace(xml.a[1].hasSimpleContent()); // false +XML.hasComplexContent()inScopeNamespaces + Lists the namespaces for the XML object, based on the object's parent.An array of Namespace objects. + + Array + Lists the namespaces for the XML object, based on the object's parent. + + insertChildAfter + Inserts the given child2 parameter after the child1 parameter in this XML object and returns the + resulting object.The resulting XML object or undefined. + + child1ObjectThe object in the source object that you insert before child2. + child2ObjectThe object to insert. + + + Inserts the given child2 parameter after the child1 parameter in this XML object and returns the + resulting object. If the child1 parameter is null, the method + inserts the contents of child2 before all children of the XML object + (in other words, after none). If child1 is provided, but it does not + exist in the XML object, the XML object is not modified and undefined is + returned. + +

If you call this method on an XML child that is not an element (text, attributes, comments, pi, and so on) + undefined is returned.

+ +

Use the delete (XML) operator to remove XML nodes.

+ +
The following example appends an element to the end of the child elements of an XML object: + +var xml:XML = + <menu> + <item>burger</item> + <item>soda</item> + </menu>; +xml.insertChildAfter(xml.item[0], <saleItem>fries</saleItem>); +trace(xml); + The trace() output is the following: +
 <menu>
+     <item>burger</item>
+     <saleItem>fries</saleItem>
+     <item>soda</item>
+ </menu>
+
XML.insertChildBefore()delete (XML) operator
insertChildBefore + Inserts the given child2 parameter before the child1 parameter + in this XML object and returns the resulting object.The resulting XML object or undefined. + + child1ObjectThe object in the source object that you insert after child2. + child2ObjectThe object to insert. + + + Inserts the given child2 parameter before the child1 parameter + in this XML object and returns the resulting object. If the child1 parameter + is null, the method inserts the contents of + child2 after all children of the XML object (in other words, before + none). If child1 is provided, but it does not exist in the XML object, + the XML object is not modified and undefined is returned. + +

If you call this method on an XML child that is not an element (text, attributes, + comments, pi, and so on) undefined is returned.

+ +

Use the delete (XML) operator to remove XML nodes.

+ +
The following example appends an element to the end of the child elements of an XML object: + +var xml:XML = + <menu> + <item>burger</item> + <item>soda</item> + </menu>; +xml.insertChildBefore(xml.item[0], <saleItem>fries</saleItem>); +trace(xml); + The trace() output is the following: +
+ <menu>
+     <saleItem>fries</saleItem>
+     <item>burger</item>
+     <item>soda</item>
+ </menu>
+
XML.insertChildAfter()delete (XML) operator
length + For XML objects, this method always returns the integer 1.Always returns 1 for any XML object. + + int + For XML objects, this method always returns the integer 1. + The length() method of the XMLList class returns a value of 1 for + an XMLList object that contains only one value. + + localName + Gives the local name portion of the qualified name of the XML object.The local name as either a String or null. + + Object + Gives the local name portion of the qualified name of the XML object. + + The following example illustrates the use of the localName() method: + +var xml:XML = + <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" + soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> + + <soap:Body xmlns:wx = "http://example.com/weather"> + <wx:forecast> + <wx:city>Quito</wx:city> + </wx:forecast> + </soap:Body> + </soap:Envelope>; + +trace(xml.localName()); // Envelope +name + Gives the qualified name for the XML object.The qualified name is either a QName or null. + + Object + Gives the qualified name for the XML object. + + The following example illustrates the use of the name() method to get the qualified + name of an XML object: + +var xml:XML = + <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" + soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> + + <soap:Body xmlns:wx = "http://example.com/weather"> + <wx:forecast> + <wx:city>Quito</wx:city> + </wx:forecast> + </soap:Body> + </soap:Envelope>; + +trace(xml.name().localName); // Envelope +trace(xml.name().uri); // "http://www.w3.org/2001/12/soap-envelope" + The following example illustrates the use of the name() method called on an XML property, + on a text element, and on an attribute: + +var xml:XML = + <foo x="15" y="22"> + text + </foo>; + +trace(xml.name().localName); // foo +trace(xml.name().uri == ""); // true +trace(xml.children()[0]); // text +trace(xml.children()[0].name()); // null +trace(xml.attributes()[0]); // 15 +trace(xml.attributes()[0].name()); // x +XML.attributes()attribute identifiernamespaceDeclarations + Lists namespace declarations associated with the XML object in the context of its parent.An array of Namespace objects. + + Array + Lists namespace declarations associated with the XML object in the context of its parent. + + The following example outputs the namespace declarations of an + XML object: + +var xml:XML = + <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns="http://purl.org/rss/1.0/"> + + <!-- ... --> + + </rdf:RDF>; + +for (var i:uint = 0; i < xml.namespaceDeclarations().length; i++) { + var ns:Namespace = xml.namespaceDeclarations()[i]; + var prefix:String = ns.prefix; + if (prefix == "") { + prefix = "(default)"; + } + trace(prefix + ":" , ns.uri); +} + The trace() output is the following: +
rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns#
+ dc: http://purl.org/dc/elements/1.1/
+ (default): http://purl.org/rss/1.0/
+
XML.namespace()
namespace + If no parameter is provided, gives the namespace associated with the qualified name of + this XML object.Returns null, undefined, or a namespace. + + prefixStringnullThe prefix you want to match. + + + If no parameter is provided, gives the namespace associated with the qualified name of + this XML object. If a prefix parameter is specified, the method returns the namespace + that matches the prefix parameter and that is in scope for the XML object. If there is no + such namespace, the method returns undefined. + + The following example uses the namespace() method + to get the namespace of an XML object and assign it to a Namespace object named soap + which is then used in identifying a property of the xml object + (xml.soap::Body[0]): + +var xml:XML = + <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" + soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> + + <soap:Body xmlns:wx = "http://example.com/weather"> + <wx:forecast> + <wx:city>Quito</wx:city> + </wx:forecast> + </soap:Body> + </soap:Envelope>; + +var soap:Namespace = xml.namespace(); +trace(soap.prefix); // soap +trace(soap.uri); // http://www.w3.org/2001/12/soap-envelope + +var body:XML = xml.soap::Body[0]; +trace(body.namespace().prefix); // soap +trace(xml.namespace().uri); // http://www.w3.org/2001/12/soap-envelope +trace(body.namespace("wx").uri); // "http://example.com/weather" + The following example uses the namespace() method to get the + default namespace for a node, as well as the namespace for a specific prefix ("dc"): + +var xml:XML = + <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns="http://purl.org/rss/1.0/"> + <!-- ... --> + </rdf:RDF>; + +trace(xml.namespace()); // http://www.w3.org/1999/02/22-rdf-syntax-ns# +trace(xml.namespace("dc")); // http://purl.org/dc/elements/1.1/ +trace(xml.namespace("foo")); // undefined +nodeKind + Specifies the type of node: text, comment, processing-instruction, + attribute, or element.The node type used. + + String + Specifies the type of node: text, comment, processing-instruction, + attribute, or element. + + This example traces all five node types: + +XML.ignoreComments = false; +XML.ignoreProcessingInstructions = false; + +var xml:XML = + <example id="10"> + <!-- this is a comment --> + <?test this is a pi ?> + and some text + </example>; + +trace(xml.nodeKind()); // element +trace(xml.children()[0].nodeKind()); // comment +trace(xml.children()[1].nodeKind()); // processing-instruction +trace(xml.children()[2].nodeKind()); // text +trace(xml.@id[0].nodeKind()); // attribute +attribute identifiernormalize + For the XML object and all descendant XML objects, merges adjacent text nodes and + eliminates empty text nodes.The resulting normalized XML object. + + XML + For the XML object and all descendant XML objects, merges adjacent text nodes and + eliminates empty text nodes. + + The following example shows the effect of calling the normalize() method: + +var xml:XML = <body></body>; +xml.appendChild("hello"); +xml.appendChild(" world"); +trace(xml.children().length()); // 2 +xml.normalize(); +trace(xml.children().length()); // 1 +parent + Returns the parent of the XML object.Either an XML reference of the parent node, or undefined + if the XML object has no parent. + + + Returns the parent of the XML object. If the XML object has no parent, the method returns + undefined. + + The following example uses the parent() method to identify the parent element + of a specific element in an XML structure: + +var xml:XML = + <body> + <p id="p1">Hello</p> + <p id="p2">Test: + <ul> + <li>1</li> + <li>2</li> + </ul> + </p> + </body>; +var node:XML = xml.p.ul.(li.contains("1"))[0]; // == <ul> ... </ul> +trace(node.parent().@id); // p2 +prependChild + Inserts a copy of the provided child object into the XML element before any existing XML + properties for that element.The resulting XML object. + + XMLvalueObjectThe object to insert. + + + Inserts a copy of the provided child object into the XML element before any existing XML + properties for that element. + +

Use the delete (XML) operator to remove XML nodes.

+ +
The following example uses the prependChild() method to add an element to the + begining of a child list of an XML object: + +var xml:XML = + <body> + <p>hello</p> + </body>; + +xml.prependChild(<p>world</p>); +trace(xml.p[0].toXMLString()); // <p>world</p> +trace(xml.p[1].toXMLString()); // <p>hello</p> +
delete (XML) operator
processingInstructions + If a name parameter is provided, lists all the children of the XML object + that contain processing instructions with that name.A list of matching child objects. + + XMLListnameString*The name of the processing instructions to match. + + + If a name parameter is provided, lists all the children of the XML object + that contain processing instructions with that name. With no parameters, the method + lists all the children of the XML object that contain any processing instructions. + + The following example uses the processingInstructions() method to get an + array of processing instructions for an XML object: + +XML.ignoreProcessingInstructions = false; +var xml:XML = + <body> + foo + <?xml-stylesheet href="headlines.css" type="text/css" ?> + <?instructionX ?> + + </body>; + +trace(xml.processingInstructions().length()); // 2 +trace(xml.processingInstructions()[0].name()); // xml-stylesheet +propertyIsEnumerable + Checks whether the property p is in the set of properties that can be iterated in a + for..in statement applied to the XML object.If the property can be iterated in a for..in statement, true; + otherwise, false. + + BooleanpStringThe property that you want to check. + + + Checks whether the property p is in the set of properties that can be iterated in a + for..in statement applied to the XML object. Returns true only + if toString(p) == "0". + + The following example shows that, for an XML object, the + propertyNameIsEnumerable() method returns a value of + true only for the value 0; whereas for an + XMLList object, the return value is true for each valid index + value for the XMLList object: + +var xml:XML = + <body> + <p>Hello</p> + <p>World</p> + </body>; + +trace(xml.propertyIsEnumerable(0)); // true +trace(xml.propertyIsEnumerable(1)); // false + +for (var propertyName:String in xml) { + trace(xml[propertyName]); +} + +var list:XMLList = xml.p; +trace(list.propertyIsEnumerable(0)); // true +trace(list.propertyIsEnumerable(1)); // true +trace(list.propertyIsEnumerable(2)); // false + +for (var propertyName:String in list) { + trace(list[propertyName]); +} +removeNamespace + Removes the given namespace for this object and all descendants.A copy of the resulting XML object. + + XMLnsNamespaceThe namespace to remove. + + + Removes the given namespace for this object and all descendants. The removeNamespaces() + method does not remove a namespace if it is referenced by the object's qualified name or the + qualified name of the object's attributes. + + The following example shows how to remove a namespace declaration + from an XML object: + +var xml:XML = + <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns="http://purl.org/rss/1.0/"> + + <!-- ... --> + + </rdf:RDF>; + +trace(xml.namespaceDeclarations().length); // 3 +trace(xml.namespaceDeclarations()[0] is String); // +var dc:Namespace = xml.namespace("dc"); +xml.removeNamespace(dc); +trace(xml.namespaceDeclarations().length); // 2 +replace + Replaces the properties specified by the propertyName parameter + with the given value parameter.The resulting XML object, with the matching properties replaced. + + XMLpropertyNameObjectCan be a + numeric value, an unqualified name for a set of XML elements, a qualified name for a set of + XML elements, or the asterisk wildcard ("*"). + Use an unqualified name to identify XML elements in the default namespace. + + valueXMLThe replacement value. This can be an XML object, an XMLList object, or any value + that can be converted with toString(). + + + Replaces the properties specified by the propertyName parameter + with the given value parameter. + If no properties match propertyName, the XML object is left unmodified. + + The following example illustrates calling the replace() method + with an integer as the first parameter: + +var xml:XML = + <body> + <p>Hello</p> + <p>World</p> + <hr/> + </body>; + +xml.replace(1, <p>Bob</p>); +trace(xml); + This results in the following trace() output: +

+ <body>
+     <p>Hello</p>
+     <p>Bob</p>
+     <hr/>
+ </body>
+ 
+
The following example calls replace() method + with a string as the first parameter: + +var xml:XML = + <body> + <p>Hello</p> + <p>World</p> + <hr/> + </body>; + +xml.replace("p", <p>Hi</p>); +trace(xml); + This results in the following trace() output: + +

+ <body>
+     <p>Hi</p>
+     <hr/>
+ </body>;
+ 
+
The following example illustrates calling the replace() method + with a QName as the first parameter: + +var xml:XML = + <ns:body xmlns:ns = "myNS"> + <ns:p>Hello</ns:p> + <ns:p>World</ns:p> + <hr/> + </ns:body>; + +var qname:QName = new QName("myNS", "p"); +xml.replace(qname, <p>Bob</p>); +trace(xml); + + This results in the following trace() output: + +

+ <ns:body xmlns:ns = "myNS">
+     <p>Bob</p>
+     <hr/>
+ </ns:body>
+ 
+
The following example illustrates calling the replace() method + with the string "*" as the first parameter: + +var xml:XML = + <body> + <p>Hello</p> + <p>World</p> + <hr/> + </body>; + +xml.replace("*", <img src = "hello.jpg"/>); +trace(xml); + This results in the following trace() output: + +

+ <body>
+     <img src="hello.jpg"/>
+ </body>
+ 
+
setChildren + Replaces the child properties of the XML object with the specified set of XML properties, + provided in the value parameter.The resulting XML object. + + XMLvalueObjectThe replacement XML properties. Can be a single XML object or an XMLList object. + + + Replaces the child properties of the XML object with the specified set of XML properties, + provided in the value parameter. + + The following example illustrates calling the setChildren() method, first + using an XML object as the parameter, and then using an XMLList object as the parameter: + +var xml:XML = + <body> + <p>Hello</p> + <p>World</p> + </body>; + +var list:XMLList = xml.p; + +xml.setChildren(<p>hello</p>); +trace(xml); + +// <body> +// <p>hello</p> +// </body> + +xml.setChildren(list); +trace(xml); + +// <body> +// <p>Hello</p> +// <p>World</p> +// </body> +setLocalName + Changes the local name of the XML object to the given name parameter.nameStringThe replacement name for the local name. + + + Changes the local name of the XML object to the given name parameter. + + The following example uses the setLocalName() method + to change the local name of an XML element: + +var xml:XML = + <ns:item xmlns:ns="http://example.com"> + toothbrush + </ns:item>; + +xml.setLocalName("orderItem"); +trace(xml.toXMLString()); // <ns:orderItem xmlns:ns="http://example.com">toothbrush</ns:orderItem> +setName + Sets the name of the XML object to the given qualified name or attribute name.nameStringThe new name for the object. + + + Sets the name of the XML object to the given qualified name or attribute name. + + The following example uses the setName() method + to change the name of an XML element: + +var xml:XML = + <item> + toothbrush + </item>; + +xml.setName("orderItem"); +trace(xml.toXMLString()); // <orderItem>toothbrush</orderItem> +setNamespace + Sets the namespace associated with the XML object.nsNamespaceThe new namespace. + + + Sets the namespace associated with the XML object. + + The following example uses the soap namespace defined in one XML object + and applies it to the namespace of another XML object (xml2): + +var xml1:XML = + <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" + soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> + <!-- ... --> + </soap:Envelope>; +var ns:Namespace = xml1.namespace("soap"); + +var xml2:XML = + <Envelope> + <Body/> + </Envelope>; + +xml2.setNamespace(ns); + +trace(xml2); +setSettings + Sets values for the following XML properties: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, + prettyIndent, and prettyPrinting.restAn object with each of the following properties: + +
  • ignoreComments
  • ignoreProcessingInstructions
  • ignoreWhitespace
  • prettyIndent
  • prettyPrinting
+ +
+ Sets values for the following XML properties: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, + prettyIndent, and prettyPrinting. + + The following are the default settings, which are applied if no setObj parameter + is provided: + +
  • XML.ignoreComments = true
  • XML.ignoreProcessingInstructions = true
  • XML.ignoreWhitespace = true
  • XML.prettyIndent = 2
  • XML.prettyPrinting = true
+ +

Note: You do not apply this method to an instance of the XML class; you apply it to + XML, as in the following code: XML.setSettings().

+ +
The following example shows: how to apply some custom settings (for including comments and processing + instructions) prior to setting an XML object; how to then revert back to the default settings before setting another XML + object; and then how to set the custom settings again (for setting any more XML objects): + +XML.ignoreComments = false; +XML.ignoreProcessingInstructions = false; +var customSettings:Object = XML.settings(); + +var xml1:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml1.toXMLString()); +// <foo> +// <!-- comment --> +// <?instruction ?> +// </foo> + +XML.setSettings(XML.defaultSettings()); +var xml2:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml2.toXMLString()); +
ignoreCommentsignoreProcessingInstructionsignoreWhitespaceprettyIndentprettyPrintingdefaultSettings()settings()
settings + Retrieves the following properties: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, + prettyIndent, and prettyPrinting.An object with the following XML properties: +
  • ignoreComments
  • ignoreProcessingInstructions
  • ignoreWhitespace
  • prettyIndent
  • prettyPrinting
+ +
Object
+ Retrieves the following properties: ignoreComments, + ignoreProcessingInstructions, ignoreWhitespace, + prettyIndent, and prettyPrinting. + + The following example shows: how to apply some custom settings (for including comments and processing + instructions) prior to setting an XML object; how to then revert back to the default settings before setting another XML + object; and then how to set the custom settings again (for setting any more XML objects): + +XML.ignoreComments = false; +XML.ignoreProcessingInstructions = false; +var customSettings:Object = XML.settings(); + +var xml1:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml1.toXMLString()); +// <foo> +// <!-- comment --> +// <?instruction ?> +// </foo> + +XML.setSettings(XML.defaultSettings()); +var xml2:XML = + <foo> + <!-- comment --> + <?instruction ?> + </foo>; +trace(xml2.toXMLString()); +
XML.ignoreCommentsXML.ignoreProcessingInstructionsXML.ignoreWhitespaceXML.prettyIndentXML.prettyPrintingXML.defaultSettings()XML.setSettings()
text + Returns an XMLList object of all XML properties of the XML object that represent XML text nodes.The list of properties. + + XMLList + Returns an XMLList object of all XML properties of the XML object that represent XML text nodes. + + The following example uses the text() method to get the text nodes of + an XML object: + +var xml:XML = + <body> + text1 + <hr/> + text2 + </body>; +trace(xml.text()[0]); // text1 +trace(xml.text()[1]); // text2 +toString + Returns a string representation of the XML object.The string representation of the XML object. + + String + Returns a string representation of the XML object. The rules for this conversion depend on whether + the XML object has simple content or complex content: + +
  • If the XML object has simple content, toString() returns the String contents of the + XML object with the following stripped out: the start tag, attributes, namespace declarations, and + end tag.
+ +
  • If the XML object has complex content, toString() returns an XML encoded String + representing the entire XML object, including the start tag, attributes, namespace declarations, + and end tag.
+ +

To return the entire XML object every time, use toXMLString().

+ + +
The following example shows what the toString() method returns when the + XML object has simple content: + +var test:XML = <type name="Joe">example</type>; +trace(test.toString()); //example + The following example shows what the toString() method returns when the + XML object has complex content: + +var test:XML = +<type name="Joe"> + <base name="Bob"></base> + example +</type>; +trace(test.toString()); + // <type name="Joe"> + // <base name="Bob"/> + // example + // </type> +
XML.hasSimpleContent()XML.hasComplexContent()XML.toXMLString()
toXMLString + Returns a string representation of the XML object.The string representation of the XML object. + + String + Returns a string representation of the XML object. Unlike the toString() method, + the toXMLString() method always returns the start tag, attributes, + and end tag of the XML object, regardless of whether the XML object has simple content or complex + content. (The toString() method strips out these items for XML objects that contain + simple content.) + + The following example shows the difference between using the toString() method + (which is applied to all parameters of a trace() method, by default) and using the + toXMLString() method: + +var xml:XML = + <p>hello</p>; +trace(xml); // hello +trace(xml.toXMLString()); // <p>hello</p> +XML.toString()valueOf + Returns the XML object.The primitive value of an XML instance. + + XML + Returns the XML object. + + The following example shows that the value returned by the valueOf() method + is the same as the source XML object: + +var xml:XML = <p>hello</p>; +trace(xml.valueOf() === xml); // true +ignoreComments + Determines whether XML comments are ignored + when XML objects parse the source XML data.Boolean + Determines whether XML comments are ignored + when XML objects parse the source XML data. By default, the comments are ignored + (true). To include XML comments, set this property to false. + The ignoreComments property is used only during the XML parsing, not during + the call to any method such as myXMLObject.child(~~).toXMLString(). + If the source XML includes comment nodes, they are kept or discarded during the XML parsing. + + This example shows the effect of setting XML.ignoreComments + to false and to true: + +XML.ignoreComments = false; +var xml1:XML = + <foo> + <!-- comment --> + </foo>; +trace(xml1.toXMLString()); // <foo><!-- comment --></foo> + +XML.ignoreComments = true; +var xml2:XML = + <foo> + <!-- example --> + </foo>; +trace(xml2.toXMLString()); // <foo/> +XML.child()XML.toXMLString()ignoreProcessingInstructions + Determines whether XML + processing instructions are ignored when XML objects parse the source XML data.Boolean + Determines whether XML + processing instructions are ignored when XML objects parse the source XML data. + By default, the processing instructions are ignored (true). To include XML + processing instructions, set this property to false. The + ignoreProcessingInstructions property is used only during the XML parsing, + not during the call to any method such as myXMLObject.child(~~).toXMLString(). + If the source XML includes processing instructions nodes, they are kept or discarded during + the XML parsing. + + This example shows the effect of setting XML.ignoreProcessingInstructions + to false and to true: + +XML.ignoreProcessingInstructions = false; +var xml1:XML = + <foo> + <?exampleInstruction ?> + </foo>; +trace(xml1.toXMLString()); // <foo><?exampleInstruction ?></foo> + +XML.ignoreProcessingInstructions = true; +var xml2:XML = + <foo> + <?exampleInstruction ?> + </foo>; +trace(xml2.toXMLString()); // <foo/> +XML.child()XML.toXMLString()ignoreWhitespace + Determines whether white space characters + at the beginning and end of text nodes are ignored during parsing.Boolean + Determines whether white space characters + at the beginning and end of text nodes are ignored during parsing. By default, + white space is ignored (true). If a text node is 100% white space and the + ignoreWhitespace property is set to true, then the node is not created. + To show white space in a text node, set the ignoreWhitespace property to + false. + +

When you create an XML object, it caches the current value of the ignoreWhitespace + property. Changing the ignoreWhitespace does not change the behavior of existing XML + objects.

+ +
This example shows the effect of setting XML.ignoreWhitespace + to false and to true: + +XML.ignoreWhitespace = false; +var xml1:XML = <foo> </foo>; +trace(xml1.children().length()); // 1 + +XML.ignoreWhitespace = true; +var xml2:XML = <foo> </foo>; +trace(xml2.children().length()); // 0 +
prettyIndent + Determines the amount of indentation applied by + the toString() and toXMLString() methods when + the XML.prettyPrinting property is set to true.int + Determines the amount of indentation applied by + the toString() and toXMLString() methods when + the XML.prettyPrinting property is set to true. + Indentation is applied with the space character, not the tab character. + + The default value is 2. + + This example shows the effect of setting the XML.prettyIndent + static property: + +var xml:XML = <foo><bar/></foo>; +XML.prettyIndent = 0; +trace(xml.toXMLString()); + +XML.prettyIndent = 1; +trace(xml.toXMLString()); + +XML.prettyIndent = 2; +trace(xml.toXMLString()); +prettyPrintingtoString()toXMLString()prettyPrinting + Determines whether the toString() + and toXMLString() methods normalize white space characters between some tags.Boolean + Determines whether the toString() + and toXMLString() methods normalize white space characters between some tags. + The default value is true. + + This example shows the effect of setting XML.prettyPrinting + static property: + +var xml:XML = <foo><bar/></foo>; +XML.prettyPrinting = false; +trace(xml.toXMLString()); + +XML.prettyPrinting = true; +trace(xml.toXMLString()); +prettyIndenttoString()toXMLString()
Array + Creates a new array.An array of length zero or more. + ArrayargsYou can pass no arguments for an empty array, a single integer argument for an array of a specific length, or a single object to create an array + containing the one specified object. + + Creates a new array. The array can be of length zero or more, or an array populated by a single + specified object. +
  • Calling Array() with no arguments returns an empty array.
  • Calling Array() with a single integer argument returns an array of the specified length, but whose elements have undefined values.
  • Calling Array() with a specified object returns an array with one element of the specified object.
+ Using the Array() function is similar to creating an array with the Array class constructor, but the Array() function only + allows one, or no, parameter value. You cannot use the the Array() function to populate the new array with several values. +

Note: If you try to use the Array() function to create a new array, and pass several values as parameters to populate + the array, you'll get a compiler error. The the Array() function only allows one parameter. Use the Array class constructor, instead, to create and + populate an array of several values.

+

The Array() function does not cast the type of an object to an array. Use the as operator for explicit type conversion, or type casting, + when the argument is not a primitive value. For more information, see the Example + section of this entry. If you pass an object as a parameter to the Array() function, a new array is created containing the object as an element.

+
The following example demonstrates the behavior of the Array() + function when an argument is not a primitive value. A common use case of casting to an array + is the conversion of an Object instance that stores its values in array format. + If Array() is called with an argument of type Object, + or any other non-primitive data type, a reference to the object is stored in an element + of the new array. In other words, if the only argument passed is an object, + a reference to that object becomes the first element of the new array. + +var obj:Object = [ "a", "b", "c" ]; + +var newArray:Array = Array( obj ); + +trace(newArray == obj); // false +trace(newArray[0] == obj); // true +trace(newArray[0][0]) // a +trace(newArray[0][1]) // b +trace(newArray[0][2]) // c + To cast obj to an array, use the as operator, which returns an array reference + if obj is a valid array and null otherwise: + +var obj:Object = [ "a", "b", "c" ]; + +var newArray:Array = obj as Array; + +trace(newArray == obj); // true +trace(newArray[0]); // a +trace(newArray[1]); // b +trace(newArray[2]); // c +
Array classas operator
Boolean + Converts the expression parameter to a Boolean value and returns the value.The result of the conversion to Boolean. + BooleanexpressionObjectAn expression or object to convert to Boolean. + + Converts the expression parameter to a Boolean value and returns the value. +

The return value depends on the data type and value of the argument, as described in the following table:

+ + Input ValueExampleReturn Value0Boolean(0)falseNaNBoolean(NaN)falseNumber (not 0 or NaN)Boolean(4)trueEmpty stringBoolean("")falseNon-empty stringBoolean("6")truenullBoolean(null)falseundefinedBoolean(undefined)falseInstance of Object classBoolean(new Object())trueNo argumentBoolean()false +

Unlike previous versions of ActionScript, the Boolean() function returns the same results as does the Boolean class constructor.

+
Number + Converts a given value to a Number value.The converted number value + NumberexpressionObjectA value to be converted to a number. + + Converts a given value to a Number value. The following table shows the result of various input types: + + Input Type/ValueExampleReturn ValueundefinedNumber(undefined)NaNnullNumber(null)0trueNumber(true)1falseNumber(false)0NaNNumber(NaN)NaNEmpty stringNumber("")0String that converts to NumberNumber("5")The number (e.g. 5)String that does not convert to NumberNumber("5a")NaN + Object + Every value in ActionScript 3.0 is an object, which means that calling Object() on a value returns that value.The value specified by the value parameter. + ObjectvalueObjectAn object or a number, string, or Boolean value to convert. + + Every value in ActionScript 3.0 is an object, which means that calling Object() on a value returns that value. + String + Returns a string representation of the specified parameter.A string representation of the value passed for the expression parameter. + StringexpressionObject An expression to convert to a string. + + Returns a string representation of the specified parameter. +

The following table shows the result of various input types:

+ Input Type/ValueReturn Valueundefinedundefinednull"null"true"true"false"false"NaN"NaN"StringStringObjectObject.toString()NumberString representation of the number +
Vector + Creates a new Vector instance whose elements are instances of the specified data type.If the sourceArray argument contains an element that can't be + converted to the specified data type. + + TypeErrorTypeErrorA Vector instance populated with the elements of the sourceArray array. + + sourceArrayObjectAn Array or Vector instance whose elements become the elements of the result + Vector. If the argument is a Vector instance whose associated data type is the same as the + specified data type, the argument is returned as the function result. + + + Creates a new Vector instance whose elements are instances of the specified data type. + When calling this function, you specify the data type of the result Vector's elements + (the Vector's base type) using a type parameter. This function + uses the same syntax that's used when declaring a Vector instance or calling the + new Vector.<T>() constructor: + + var v:Vector.<String> = Vector.<String>(["Hello", "World"]); + +

The resulting Vector is populated + with the values in the elements of the sourceArray argument. + If the sourceArray argument is already a Vector.<T> + instance where T is the base type, the function returns + that Vector. Otherwise, the result Vector + is populated with the elements of the sourceArray Array or Vector.

+ +

In either case, the data type of all the elements of the sourceArray + argument must match the base type T specified in the function call.

+ +

If the sourceArray argument has length 0, the function + returns an empty Vector.

+ +

If a Vector is passed as the sourceArray argument and its base type + is not T, or if an Array is passed and its elements are not all instances of + data type T, an attempt is made to convert the values to the base type. If + the values can be automatically converted, the result Vector contains the converted values. + If no conversion can be made, an error occurs.

+ +

Likewise, if an element in the sourceArray argument is an instance of + a subclass of the base type T, the call succeeds and the element is + added to the resulting Vector. This works even if the + sourceArray argument is a Vector whose base type is a subclass + of T. In fact, this is the only way to convert a Vector with base type + T to a Vector with a base type that's a superclass of T.

+ +

For example, the following code results in a compile error in strict mode, or a + TypeError at run time, because it attempts to assign a Vector.<Sprite> to a + Vector.<DisplayObject> variable (Sprite is a subclass of DisplayObject):

+ + + var v1:Vector.<Sprite> = new Vector.<Sprite>(); + v1[0] = new Sprite(); + var v2:Vector.<DisplayObject> = v1; + + +

The following alternative version of the code successfully copies the elements of a + Vector.<Sprite> instance to a Vector.<DisplayObject> instance:

+ + + var v1:Vector.<Sprite> = new Vector.<Sprite>(); + v1[0] = new Sprite(); + var v2:Vector.<DisplayObject> = Vector.<DisplayObject>(v1); + + +
Vector class
XMLList + Converts an object to an XMLList object.An XMLList object containing values held in the converted object. + XMLListexpressionObjectObject to be converted into an XMLList object. + + Converts an object to an XMLList object. +

The following table describes return values for various input types.

+ Parameter TypeReturn ValueBooleanValue is first converted to a string, then converted to an XMLList object.NullA runtime error occurs (TypeError exception).NumberValue is first converted to a string, then converted to an XMLList object.ObjectConverts to XMLList only if the value is a String, Number or Boolean value. Otherwise a runtime error occurs (TypeError exception).StringValue is converted to an XMLList object.UndefinedA runtime error occurs (TypeError exception).XMLValue is converted to an XMLList object.XMLListInput value is returned unchanged. +
XML()
XML + Converts an object to an XML object.An XML object containing values held in the converted object. + XMLexpressionObjectObject to be converted to XML. + + Converts an object to an XML object. +

The following table describes return values for various input types.

+ Parameter TypeReturn ValueBooleanValue is first converted to a string, then converted to an XML object.NullA runtime error occurs (TypeError exception).NumberValue is first converted to a string, then converted to an XML object.ObjectConverts to XML only if the value is a String, Number or Boolean value. Otherwise a runtime error occurs (TypeError exception).StringValue is converted to XML.UndefinedA runtime error occurs (TypeError exception).XMLInput value is returned unchanged.XMLListReturns an XML object only if the XMLList object contains only one property of type XML. Otherwise a runtime error occurs (TypeError exception). +
XMLList()
decodeURIComponent + Decodes an encoded URI component into a string.A string in which all characters previously escaped by the encodeURIComponent function are + restored to their unescaped representation. + StringuriStringA string encoded with the encodeURIComponent function. + + Decodes an encoded URI component into a string. Returns a string in which + all characters previously escaped by the encodeURIComponent + function are restored to their uncoded representation. +

This function differs from the decodeURI() function in that it is intended for use only with a part of a URI string, called a URI component. + A URI component is any text that appears between special characters called component separators + (: / ; and ? ). + Common examples of a URI component are "http" and "www.adobe.com".

+

Another important difference between this function and decodeURI() is that because this function + assumes that it is processing a URI component it treats the escape sequences that represent special separator characters (; / ? : @ & = + $ , #) as regular + text that should be decoded.

+
decodeURI()encodeURI()encodeURIComponent()
decodeURI + Decodes an encoded URI into a string.A string in which all characters previously escaped by the encodeURI function are + restored to their unescaped representation. + StringuriStringA string encoded with the encodeURI function. + + Decodes an encoded URI into a string. Returns a string in which all characters previously encoded + by the encodeURI function are restored to their unencoded representation. +

The following table shows the set of escape sequences that are not decoded to characters by the decodeURI function. Use decodeURIComponent() to decode the escape sequences in this table.

+ Escape sequences not decodedCharacter equivalents%23#%24$%26&%2B+%2C,%2F/%3A:%3B;%3D=%3F?%40@ + +
package { + import flash.display.Sprite; + + public class DecodeURIExample extends Sprite { + public function DecodeURIExample() { + var uri:String = "http://www.example.com/application.jsp?user=<user name='some user'></user>"; + var encoded:String = encodeURI(uri); + var decoded:String = decodeURI(encoded); + trace(uri); // http://www.example.com/application.jsp?user=<user name='some user'></user> + trace(encoded); // http://www.example.com/application.jsp?user=%3Cuser%20name='some%20user'%3E%3C/user%3E + trace(decoded); // http://www.example.com/application.jsp?user=<user name='some user'></user> + } + } +} +
decodeURIComponent()encodeURI()encodeURIComponent()
encodeURIComponent + Encodes a string into a valid URI component.StringuriString + Encodes a string into a valid URI component. Converts a substring of a URI into a + string in which all characters are encoded as UTF-8 escape sequences unless a character + belongs to a very small group of basic characters. +

The encodeURIComponent() function differs from the encodeURI() function in that it is intended for use only with a part of a URI string, called a URI component. + A URI component is any text that appears between special characters called component separators + (: / ; and ? ). + Common examples of a URI component are "http" and "www.adobe.com".

+

Another important difference between this function and encodeURI() is that because this function + assumes that it is processing a URI component it treats the special separator characters (; / ? : @ & = + $ , #) as regular + text that should be encoded.

+

The following table shows all characters that are not converted to UTF-8 escape sequences by the encodeURIComponent function.

+ Characters not encoded0 1 2 3 4 5 6 7 8 9a b c d e f g h i j k l m n o p q r s t u v w x y zA B C D E F G H I J K L M N O P Q R S T U V W X Y Z- _ . ! ~ ~~ ' ( ) +
decodeURI()decodeURIComponent()encodeURI()
encodeURI + Encodes a string into a valid URI (Uniform Resource Identifier).A string with certain characters encoded as UTF-8 escape sequences. + StringuriStringA string representing a complete URI. + + Encodes a string into a valid URI (Uniform Resource Identifier). + Converts a complete URI into a string in which all characters are encoded + as UTF-8 escape sequences unless a character belongs to a small group of basic characters. +

The following table shows the entire set of basic characters that are not converted to UTF-8 escape sequences by the encodeURI function.

+ Characters not encoded0 1 2 3 4 5 6 7 8 9a b c d e f g h i j k l m n o p q r s t u v w x y zA B C D E F G H I J K L M N O P Q R S T U V W X Y Z; / ? : @ & = + $ , #- _ . ! ~ ~~ ' ( ) +
package { + import flash.display.Sprite; + + public class EncodeURIExample extends Sprite { + public function EncodeURIExample() { + var uri:String = "http://www.example.com/application.jsp?user=<user name='some user'></user>"; + var encoded:String = encodeURI(uri); + var decoded:String = decodeURI(encoded); + trace(uri); // http://www.example.com/application.jsp?user=<user name='some user'></user> + trace(encoded); // http://www.example.com/application.jsp?user=%3Cuser%20name='some%20user'%3E%3C/user%3E + trace(decoded); // http://www.example.com/application.jsp?user=<user name='some user'></user> + } + } +} +
decodeURI()decodeURIComponent()encodeURIComponent()
escape + Converts the parameter to a string and encodes it in a URL-encoded format, + where most nonalphanumeric characters are replaced with % hexadecimal sequences.A URL-encoded string. + StringstrStringThe expression to convert into a string and encode in a URL-encoded format. + + Converts the parameter to a string and encodes it in a URL-encoded format, + where most nonalphanumeric characters are replaced with % hexadecimal sequences. + When used in a URL-encoded string, the percentage symbol (%) is used to introduce + escape characters, and is not equivalent to the modulo operator (%). +

The following table shows all characters that are not converted to escape sequences by the escape() function.

+ Characters not encoded0 1 2 3 4 5 6 7 8 9a b c d e f g h i j k l m n o p q r s t u v w x y zA B C D E F G H I J K L M N O P Q R S T U V W X Y Z@ - _ . ~~ + / +

Note: Use the encodeURIComponent() function, instead of the escape() function, to treat + special separator characters (@ + /) as regular + text to encode.

+
unescape()encodeURIComponent()
int + Converts a given numeric value to an integer value.The converted integer value. + intvalueNumberA value to be converted to an integer. + + Converts a given numeric value to an integer value. Decimal values are truncated at the decimal point. + uint()isFinite + Returns true if the value is a finite number, + or false if the value is Infinity or -Infinity.Returns true if it is a finite number + or false if it is infinity or negative infinity + BooleannumNumberA number to evaluate as finite or infinite. + + Returns true if the value is a finite number, + or false if the value is Infinity or -Infinity. + The presence of Infinity or -Infinity indicates a mathematical + error condition such as division by 0. + isNaN + Returns true if the value is NaN(not a number).Returns true if the value is NaN(not a number) and false otherwise. + BooleannumNumberA numeric value or mathematical expression to evaluate. + + Returns true if the value is NaN(not a number). The isNaN() function is useful for checking whether a mathematical expression evaluates successfully to a number. + The most common use of isNaN() is to check the value returned from the parseInt()and parseFloat() functions. The NaN value is a special member of the Number data type that represents a value that is "not a number." +

Note: The NaN value is not a member of the int or uint data types.

+

The following table describes the return value of isNaN() on various input types and + values. (If your compiler warnings are set to Strict Mode, some of the following operations will generate + compiler warnings.)

+ Input Type/ValueExampleReturn Value0 divided by 0isNaN(0/0)trueNon-zero number divided by 0isNaN(5/0)falseSquare root of a negative numberisNaN(Math.sqrt(-1))trueArcsine of number greater than 1 or less than 0isNaN(Math.asin(2))trueString that can be converted to NumberisNaN("5")falseString that cannot be converted to NumberisNaN("5a")true +
isXMLName + Determines whether the specified string is a valid name for an XML element or attribute.Returns true if the str argument is a valid XML name; false otherwise. + BooleanstrStringA string to evaluate. + + Determines whether the specified string is a valid name for an XML element or attribute. + parseFloat + Converts a string to a floating-point number.A number or NaN (not a number). + NumberstrStringThe string to read and convert to a floating-point number. + + Converts a string to a floating-point number. The function reads, or parses, and returns the numbers in a string until it reaches a character that is not a part of the initial number. If the string does not begin with a number that can be parsed, parseFloat() returns NaN. White space preceding valid integers is ignored, as are trailing nonnumeric characters. + parseInt + Converts a string to an integer.A number or NaN (not a number). + NumberstrStringA string to convert to an integer. + radixuint0An integer representing the radix (base) of the number to parse. Legal values are from 2 to 36. + + Converts a string to an integer. If the specified string in the parameters cannot be converted to a number, the function returns NaN. Strings beginning with 0x are interpreted as hexadecimal numbers. Unlike in previous versions of ActionScript, integers beginning with 0 are not interpreted as octal numbers. You must specify a radix of 8 for octal numbers. White space and zeroes preceding valid integers are ignored, as are trailing nonnumeric characters. + trace + Displays expressions, or writes to log files, while debugging.argumentsOne or more (comma separated) expressions to evaluate. For multiple expressions, a space is inserted between each expression in the output. + + Displays expressions, or writes to log files, while debugging. A single trace statement can support multiple arguments. If any argument + in a trace statement includes a data type other than a String, the trace function invokes the associated toString() method + for that data type. For example, if the argument is a Boolean value the trace function invokes Boolean.toString() and + displays the return value. + The following example uses the class TraceExample to + show how the trace() method can be used to print a simple string. Generally, + the message will be printed to a "Debug" console. + +package { + import flash.display.Sprite; + + public class TraceExample extends Sprite { + + public function TraceExample() { + trace("Hello World"); + } + } +} +uint + Converts a given numeric value to an unsigned integer value.The converted integer value. + uintvalueNumberA value to be converted to an integer. + + Converts a given numeric value to an unsigned integer value. Decimal values are truncated at the decimal point. +

The following table describes the return value of uint() on various input types and values.

+ Input Type/ValueExampleReturn Valueundefineduint(undefined)0nulluint(null)00uint(0)0NaNuint(NaN)0Positive floating-point numberuint(5.31)Truncated unsigned integer (e.g. 5)Negative floating-point numberuint(-5.78)Truncates to integer then applies rule for negative integersNegative integeruint(-5)Sum of uint.MAX_VALUE and the negative integer (for example, uint.MAX_VALUE + (-5))trueuint(true)1falseuint(false)0Empty Stringuint("")0String that converts to Numberuint("5")The numberString that does not convert to Numberuint("5a")0 + +
int()
unescape + Evaluates the parameter str as a string, decodes the string from URL-encoded format + (converting all hexadecimal sequences to ASCII characters), and returns the string.A string decoded from a URL-encoded parameter. + StringstrStringA string with hexadecimal sequences to escape. + + Evaluates the parameter str as a string, decodes the string from URL-encoded format + (converting all hexadecimal sequences to ASCII characters), and returns the string. + -Infinity + A special value representing negative Infinity.Number + A special value representing negative Infinity. The value of this constant is the same as Number.NEGATIVE_INFINITY. + The result of division by 0 is -Infinity, but only + when the divisor is a negative number. + + +trace(0 / 0); // NaN +trace(7 / 0); // Infinity +trace(-7 / 0); // -Infinity + + +Number.NEGATIVE_INFINITYInfinity + A special value representing positive Infinity.Number + A special value representing positive Infinity. The value of this constant is the same as Number.POSITIVE_INFINITY. + The result of division by 0 is Infinity, but only + when the divisor is a positive number. + + +trace(0 / 0); // NaN +trace(7 / 0); // Infinity +trace(-7 / 0); // -Infinity + + +Number.POSITIVE_INFINITYNaN + A special member of the Number data type that represents a value that is "not a number" (NaN).Number + A special member of the Number data type that represents a value that is "not a number" (NaN). + When a mathematical expression results in a value that cannot be expressed as a number, the result is NaN. + The following list describes common expressions that result in NaN. +
  • Division by 0 results in NaN only if the divisor is also 0. If the divisor is greater than 0, division by 0 results in Infinity. If the divisor is less than 0, division by 0 results in -Infinity;
  • Square root of a negative number;
  • The arcsine of a number outside the valid range of 0 to 1;
  • Infinity subtracted from Infinity;
  • Infinity or -Infinity divided by Infinity or -Infinity;
  • Infinity or -Infinity multiplied by 0;
+

The NaN value is not a member of the int or uint data types.

+

The NaN value is not considered equal to any other value, including NaN, which makes it impossible to use the equality operator to test whether an expression is NaN. To determine whether a number is the NaN function, use isNaN().

+ +
isNaN()Number.NaN
undefined + A special value that applies to untyped variables that have not been initialized or dynamic object properties that are not initialized. + A special value that applies to untyped variables that have not been initialized or dynamic object properties that are not initialized. + In ActionScript 3.0, only variables that are untyped can hold the value undefined, + which is not true in ActionScript 1.0 and ActionScript 2.0. + For example, both of the following variables are undefined because they are untyped and unitialized: +
  • var foo;
  • var bar:~~;
+

The undefined value also applies to uninitialized or undefined properties of dynamic objects. + For example, if an object is an instance of the Object class, + the value of any dynamically added property is undefined until a value is assigned to that property. +

+

Results vary when undefined is used with various functions:

+
  • The value returned by String(undefined) is "undefined" (undefined is + converted to a string).
  • The value returned by Number(undefined) is NaN.
  • The value returned by int(undefined) and uint(undefined) is 0.
  • The value returned by Object(undefined) is a new Object instance.
  • When the value undefined is assigned to a typed variable, + the value is converted to the default value of the data type.
+

Do not confuse undefined with null. + When null and undefined are compared with the equality + (==) operator, they compare as equal. However, when null and undefined are + compared with the strict equality (===) operator, they compare + as not equal.

+
In the following example, an untyped variable, myVar is declared but not initialized. + The value of myVar is undefined because the variable is untyped. + This is true whether the variable has no type annotation or uses the special (~~) untyped annotation (var myVar:~~;). + + +// trace value of untyped and uninitialized variable +var myVar; +trace(myVar); // undefined + The same rule applies to uninitialized properties of a dynamic object. For example, given an instance, obj, of the + dynamic class A, the value of obj.propName, which is an uninitialized + property of the obj instance, is undefined. + + +dynamic class A {} +var obj:A = new A() + +// trace undefined property of obj +trace(obj.propName); // undefined + +
null
uint + The uint class provides methods for working with a data type representing a 32-bit unsigned integer.Object + The uint class provides methods for working with a data type representing a 32-bit unsigned integer. Because an unsigned integer can only be + positive, its maximum value is twice that of the int class. +

The range of values represented by the uint class is 0 to 4,294,967,295 (2^32-1).

+

You can create a uint object by declaring a variable of type uint and assigning the variable a literal value. The default value of a variable of type uint is 0.

+

The uint class is primarily useful for pixel color values (ARGB and RGBA) and other situations where + the int data type does not work well. For example, the number 0xFFFFFFFF, which + represents the color value white with an alpha value of 255, can't be represented + using the int data type because it is not within the valid range of the int values.

+ +

The following example creates a uint object and calls the + toString() method:

+
+ var myuint:uint = 1234;
+ trace(myuint.toString()); // 1234
+ 
+

The following example assigns the value of the MIN_VALUE + property to a variable without the use of the constructor:

+
+ var smallest:uint = uint.MIN_VALUE;
+ trace(smallest.toString()); // 0
+ 
+ +
The following example declares a uint i within a for loop, + which prints out the digits 0 to 9 (since uint defaults to 0). + + +package { + import flash.display.Sprite; + + public class UintExample extends Sprite { + public function UintExample() { + for(var i:uint; i < 10; i++) { + trace(i); + } + } + } +} +
intNumberuint + Creates a new uint object.numObjectThe numeric value of the uint object being created, + or a value to be converted to a number. If num is not provided, + the default value is 0. + + + Creates a new uint object. You can create a variable of uint type and assign it a literal value. The new uint() constructor is primarily used + as a placeholder. A uint object is not the same as the + uint() function, which converts a parameter to a primitive value. + + The following code constructs two new uint objects; the first by assigning a literal value, and the second by using the constructor function: +
+	 var n1:uint = 3;
+	 var n2:uint = new uint(10);
+	 
+ +
toExponential + Returns a string representation of the number in exponential notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in exponential notation. The string contains + one digit before the decimal point and up to 20 digits after the decimal point, as + specified by the fractionDigits parameter. + The following example shows how toExponential(2) returns a string in + exponential notation. + + +var num:Number = 315003; +trace(num.toExponential(2)); // 3.15e+5 + +toFixed + Returns a string representation of the number in fixed-point notation.Throws an exception if the fractionDigits argument is outside the range 0 to 20. + RangeErrorRangeErrorStringfractionDigitsuintAn integer between 0 and 20, inclusive, that represents the desired number of decimal places. + + Returns a string representation of the number in fixed-point notation. + Fixed-point notation means that the string will contain a specific number of digits + after the decimal point, as specified in the fractionDigits parameter. + The valid range for the fractionDigits parameter is from 0 to 20. + Specifying a value outside this range throws an exception. + + The following example shows how toFixed(3) returns a string that rounds + to three decimal places. + + +var num:Number = 7.31343; +trace(num.toFixed(3)); // 7.313 + The following example shows how toFixed(2) returns a string that adds + trailing zeroes. + + +var num:Number = 4; +trace(num.toFixed(2)); // 4.00 +toPrecision + Returns a string representation of the number either in exponential notation or in + fixed-point notation.Throws an exception if the precision argument is outside the range 1 to 21. + RangeErrorRangeErrorStringprecisionuintAn integer between 1 and 21, inclusive, that represents the desired number of digits to represent in the resulting string. + + Returns a string representation of the number either in exponential notation or in + fixed-point notation. The string will contain the number of digits specified in the + precision parameter. + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in fixed-point notation because exponential notation is not required. + + +var num:Number = 31.570; +trace(num.toPrecision(3)); // 31.6 + The following example shows how toPrecision(3) returns a string with + only three digits. The string is in exponential notation because the resulting number does not + contain enough digits for fixed-point notation. + + +var num:Number = 4000; +trace(num.toPrecision(3)); // 4.00e+3 +toString + Returns the string representation of a uint object.The string representation of the uint object. + + StringradixuintSpecifies the numeric base (from 2 to 36) to use for the + number-to-string conversion. If you do not specify the radix + parameter, the default value is 10. + + + Returns the string representation of a uint object. + + The following example uses 2 and 8 for the radix + parameters and returns a string value with the corresponding + representation of the number 9: +
+	 var myuint:uint = 9;
+	 trace(myuint.toString(2)); // 1001
+	 trace(myuint.toString(8)); // 11
+	 
+ The following example creates hexadecimal values: +
+	 var r:uint = 250;
+	 var g:uint = 128;
+	 var b:uint = 114;
+	 var rgb:String = "0x" + r.toString(16) + g.toString(16) + b.toString(16);
+	 trace(rgb); // 0xfa8072 
+	 
+ +
valueOf + Returns the primitive uint type value of the specified + uint object.The primitive uint type value of this uint + object. + + uint + Returns the primitive uint type value of the specified + uint object. + + The following example outputs the primitive value of the + numSocks object. +
+	 var numSocks:uint = 2;
+	 trace(numSocks.valueOf()); // 2
+	 
+ +
MAX_VALUE + The largest representable 32-bit unsigned integer, which is 4,294,967,295.4294967295uint + The largest representable 32-bit unsigned integer, which is 4,294,967,295. + + The following ActionScript displays the largest and smallest representable + uint values: +
+	trace("uint.MIN_VALUE = " + uint.MIN_VALUE);
+	trace("uint.MAX_VALUE = " + uint.MAX_VALUE);
+	
+

The values are:

+
+	uint.MIN_VALUE = 0
+	uint.MAX_VALUE = 4294967295
+	
+ +
MIN_VALUE + The smallest representable unsigned integer, which is 0.0uint + The smallest representable unsigned integer, which is 0. + + The following ActionScript displays the largest and smallest representable + uint values: +
+	 trace("uint.MIN_VALUE = " + uint.MIN_VALUE);
+	 trace("uint.MAX_VALUE = " + uint.MAX_VALUE);
+	 
+

The values are:

+
+	 uint.MIN_VALUE = 0
+	 uint.MAX_VALUE = 4294967295
+	 
+ +
Vector + The Vector class lets you access and manipulate a vector &#8212; an array whose elements + all have the same data type.Lets you define Vectors (typed arrays). + Object + The Vector class lets you access and manipulate a vector — an array whose elements + all have the same data type. The data type of a Vector's elements is + known as the Vector's base type. The base type can be any class, + including built in classes and custom classes. The base type is specified when + declaring a Vector variable as well as when creating an instance by calling + the class constructor. + +

As with an Array, you can use the array access operator ([]) to + set or retrieve the value of a Vector element. Several Vector methods also + provide mechanisms for setting and retrieving element values. These include + push(), pop(), shift(), unshift(), + and others. The properties + and methods of a Vector object are similar — in most cases identical — to + the properties and methods of an Array. In most cases where you would use + an Array in which all the elements have the same data type, a Vector instance + is preferable. However, Vector instances are dense arrays, meaning it must have a value + (or null) in each index. Array instances + don't have this same restriction.

+ +

The Vector's base type is specified using postfix + type parameter syntax. Type parameter syntax is a sequence consisting of + a dot (.), left angle bracket (<), class name, + then a right angle bracket (>), as shown in this example:

+ +

In the first line of the example, the variable v is declared as a + Vector.<String> instance. In other words, it represents a Vector (an array) + that can only hold String instances and from which only String instances can be retrieved. + The second line constructs an instance of the same Vector type (that is, a + Vector whose elements are all String objects) and assigns it to v.

+ + + var v:Vector.<String>; + v = new Vector.<String>(); + + + + + + + + + + + + +

A variable declared with the Vector.<T> data type can only store + a Vector instance that is constructed with the same base type + T. For example, a Vector that's constructed by calling + new Vector.<String>() can't be assigned to a variable + that's declared with the Vector.<int> data type. The base types must match exactly. + For example, the following code doesn't compile because the object's base type isn't + the same as the variable's declared base type (even though Sprite is a subclass of + DisplayObject):

+ + + // This code doesn't compile even though Sprite is a DisplayObject subclass + var v:Vector.<DisplayObject> = new Vector.<Sprite>(); + + +

To convert a Vector with base type T to a Vector of a superclass of + T, use the Vector() global function.

+ +

In addition to the data type restriction, the Vector class has other restrictions + that distinguish it from the Array class:

+ +
  • A Vector is a dense array. Unlike an Array, which may have values in indices + 0 and 7 even if there are no values in positions 1 through 6, a Vector must have + a value (or null) in each index.
  • A Vector can optionally be fixed-length, meaning the number of elements + it contains can't change.
  • Access to a Vector's elements is bounds-checked. You can never read a value + from an index greater than the final element (length - 1). You + can never set a value with an index more than one beyond the current final + index (in other words, you can only set a value at an existing index or + at index [length]).
+ +

As a result of its restrictions, a Vector has three primary benefits over + an Array instance whose elements are all instances of a single class:

+
  • Performance: array element access and iteration are much faster when + using a Vector instance than they are when using an Array.
  • Type safety: in strict mode the compiler can identify data type errors. Examples + of data type errors include assigning a value of the incorrect data type to a Vector + or expecting the wrong data type when reading a value from a Vector. + Note, however, that when using the + push() method or unshift() method to add values to a Vector, the + arguments' data types are not checked at compile time. Instead, they are checked at run time.
  • Reliability: runtime range checking (or fixed-length checking) increases reliability + significantly over Arrays.
+ +
[] array accessVector() global functionArray classVector + Creates a Vector with the specified base type.lengthuint0The initial length (number of elements) of the Vector. If + this parameter is greater than zero, the specified number of Vector elements + are created and populated with the default value appropriate to + the base type (null for reference types). + + fixedBooleanfalseWhether the Vector's length is fixed (true) or + can be changed (false). This value can also be set using + the fixed property. + + + Creates a Vector with the specified base type. + +

When calling the Vector.<T>() constructor, specify the + base type using type parameter syntax. Type parameter syntax is a + sequence consisting of a dot (.), left angle bracket + (<), class name, then a right angle bracket + (>), as shown in this example:

+ + + var v:Vector.<String> = new Vector.<String>(); + + + + + + +

To create a Vector instance from an Array or another Vector (such as one with a different base type), + use the Vector() global function.

+ +

To create a pre-populated Vector instance, use the following syntax instead of using the parameters specified below:

+ + + // var v:Vector.<T> = new <T>[E0, ..., En-1 ,]; + // For example: + var v:Vector.<int> = new <int>[0,1,2,]; + + +

The following information applies to this syntax: +

  • It is supported in Flash Professional CS5 and later, Flash Builder 4 and later, and Flex 4 and later.
  • The trailing comma is optional.
  • Empty items in the array are not supported; a statement such as var v:Vector.<int> = new <int>[0,,2,] + throws a compiler error.
  • You can't specify a default length for the Vector instance. Instead, the length is the same as the number of elements + in the initialization list.
  • You can't specify whether the Vector instance has a fixed length. Instead, use the fixed property.
  • Data loss or errors can occur if items passed as values don't match the specified type. For example:
  • + var v:Vector.<int> = new <int>[4.2]; // compiler error when running in strict mode + trace(v[0]); //returns 4 when not running in strict mode +

+ +
fixedVector() global function
concat + Concatenates the elements specified in the parameters with the elements + in the Vector and creates a new Vector.If any argument is not an instance of the base type + and can't be converted to the base type. + + TypeErrorTypeErrorA Vector with the same base type as this Vector that contains + the elements from this Vector followed by elements from the parameters. + + argsOne or more values of the base type of this Vector + to be concatenated in a new Vector. + + Concatenates the elements specified in the parameters. + + Concatenates the elements specified in the parameters with the elements + in the Vector and creates a new Vector. If the parameters specify a Vector, + the elements of that Vector are concatenated. If you don't pass any parameters, + the new Vector is a duplicate (shallow clone) of the original Vector. + + every + Executes a test function on each item in the Vector until an item is + reached that returns false for the specified function.A Boolean value of true if the specified function returns + true when called on all items in the Vector; otherwise, false. + + BooleancallbackFunctionThe function to run on each item in the Vector. + This function is invoked + with three arguments: the current item from the Vector, the index of the item, + and the Vector object: +
function callback(item:T, index:int, vector:Vector.<T>):Boolean {
+       // your code here
+    }
+    
+ +

The callback function should return a Boolean value.

+ +
thisObjectObjectnullThe object that the identifer this in the + callback function refers to when the function is called. + +
+ Executes a test function on each item in the Vector until an item is + reached that returns false for the specified function. + You use this method to determine whether all items in a Vector meet + a criterion, such as having values less than a particular number. + +

For this method, the second parameter, + thisObject, must be null if the + first parameter, callback, is a method closure. That is + the most common way of using this method.

+ +

However, suppose you create a function on a frame on the main timeline using Flash Professional, + but you want it to be called in a different this context:

+ +
+    function myFunction(item:T, index:int, vector:Vector.<T>):Boolean {
+       // your code here
+    }
+    
+ +

Suppose you then use the every() + method on a Vector called myVector:

+ +
+    myVector.every(myFunction, someObject);
+    
+ +

Because myFunction is a member of the + main class of the SWF file, it cannot be executed in a different this context. Flash + runtimes throw an exception when this code runs. You can avoid this runtime error + by assigning the function to a variable, as follows:

+ +
+    var myFunction:Function = function(item:T, index:int, vector:Vector.<T>):Boolean {
+        //your code here
+    };
+    myVector.every(myFunction, someObject);
+    
+ +
Vector.some()
filter + Executes a test function on each item in the Vector and returns + a new Vector containing all items that return true for the + specified function.A new Vector that contains all items from the original Vector + for which the callback function returned true. + + callbackFunctionThe function to run on each item in the Vector. + This function is invoked + with three arguments: the current item from the Vector, the index of the item, + and the Vector object: +
function callback(item:T, index:int, vector:Vector.<T>):Boolean;
+ +
thisObjectObjectnullThe object that the identifer this in the + callback function refers to when the function is called. + +
+ Executes a test function on each item in the Vector and returns + a new Vector containing all items that return true for the + specified function. If an item returns false, + it is not included in the result Vector. The base type of the return + Vector matches the base type of the Vector on which the method is called. + +

For this method, the second parameter, + thisObject, must be null if the + first parameter, callback, is a method closure. That is + the most common way of using this method.

+ +

However, suppose you create a function on a frame on the main timeline using Flash Professional, + but you want it to be called in a different this context:

+ +
+     function myFunction(item:T, index:int, vector:Vector.<T>):Boolean {
+        // your code here
+     }
+     
+ +

Suppose you then use the filter() + method on a Vector called myVector:

+ +
+     var result:Vector.<T> = myVector.filter(myFunction, someObject);
+     
+ +

Because myFunction is a member of the + main class of the SWF file, it cannot be executed in a different this context. Flash + runtimes throw an exception when this code runs. You can avoid this runtime error + by assigning the function to a variable, as follows:

+ +
+     var myFunction:Function = function(item:T, index:int, vector:Vector.<T>):Boolean {
+         //your code here
+     };
+     myVector.filter(myFunction, someObject);
+     
+ +
Vector.map()
forEach + Executes a function on each item in the Vector.callbackFunctionThe function to run on each item in the Vector. + This function is invoked + with three arguments: the current item from the Vector, the index of the item, + and the Vector object: +
function callback(item:T, index:int, vector:Vector.<T>):void;
+

Any return value from the function call is discarded.

+ +
thisObjectObjectnullThe object that the identifer this in the + callback function refers to when the function is called. + +
+ Executes a function on each item in the Vector. + +

For this method, the second parameter, + thisObject, must be null if the + first parameter, callback, is a method closure. That is + the most common way of using this method.

+ +

However, suppose you create a function on a frame on the main timeline using Flash Professional, + but you want it to be called in a different this context:

+ +
+     function myFunction(item:T, index:int, vector:Vector.<T>):void {
+        // your code here
+     }
+     
+ +

Suppose you then use the forEach() + method on a Vector called myVector:

+ +
+     myVector.forEach(myFunction, someObject);
+     
+ +

Because myFunction is a member of the + main class of the SWF file, it cannot be executed in a different this context. Flash + runtimes throw an exception when this code runs. You can avoid this runtime error + by assigning the function to a variable, as follows:

+ +
+     var myFunction:Function = function(item:T, index:int, vector:Vector.<T>):void {
+         //your code here
+     };
+     myVector.forEach(myFunction, someObject);
+     
+ +
indexOf + Searches for an item in the Vector and returns the index position of the item.A zero-based index position of the item in the Vector. + If the searchElement argument is not found, + the return value is -1. + + intsearchElementThe item to find in the Vector. + + fromIndexint0The location in the Vector from which to start searching + for the item. If this parameter is negative, it is treated as length + + fromIndex, meaning the search starts -fromIndex items + from the end and searches from that position forward to the end of the Vector. + + + Searches for an item in the Vector and returns the index position of the item. + The item is compared to the Vector elements using strict equality (===). + + Vector.lastIndexOf()=== (strict equality)join + Converts the elements in the Vector to strings, inserts the specified separator between the + elements, concatenates them, and returns the resulting string.A string consisting of the elements of the Vector + converted to strings and separated by the specified string. + + + StringsepString,A character or string that separates Vector elements in + the returned string. If you omit this parameter, a comma is used as the default + separator. + + Converts the elements in the Vector to strings. + + + Converts the elements in the Vector to strings, inserts the specified separator between the + elements, concatenates them, and returns the resulting string. A nested Vector is always + separated by a comma (,), not by the separator passed to the join() method. + + String.split()lastIndexOf + Searches for an item in the Vector, working backward from the specified + index position, and returns the index position of the matching item.A zero-based index position of the item in the Vector. + If the searchElement argument is not found, + the return value is -1. + + intsearchElementThe item to find in the Vector. + + fromIndexint0x7fffffffThe location in the Vector from which to start searching + for the item. The default is the maximum allowable index value, meaning + that the search starts at the last item in the Vector. +

If this parameter is negative, it is treated as + length + fromIndex, meaning the search starts + -fromIndex items from the end and searches from that + position backward to index 0.

+ +
+ Searches for an item in the Vector, working backward from the specified + index position, and returns the index position of the matching item. The + item is compared to the Vector elements using strict equality (===). + +
Vector.indexOf()=== (strict equality)
map + Executes a function on each item in the Vector, and returns a new Vector + of items corresponding to the results of calling the function on + each item in this Vector.A new Vector that contains the results of calling the function + on each item in this Vector. The result Vector has the same base type + and length as the original. + + callbackFunctionThe function to run on each item in the Vector. + This function is invoked + with three arguments: the current item from the Vector, the index of the item, + and the Vector object: +
function callback(item:T, index:int, vector:Vector.<T>):T;
+ +
thisObjectObjectnullThe object that the identifer this in the + callback function refers to when the function is called. + +
+ Executes a function on each item in the Vector, and returns a new Vector + of items corresponding to the results of calling the function on + each item in this Vector. The result Vector has the same base + type and length as the original Vector. + The element at index i in the result Vector is the result of + the call on the element at index i in the original Vector. + +

For this method, the second parameter, + thisObject, must be null if the + first parameter, callback, is a method closure. That is + the most common way of using this method.

+ +

However, suppose you create a function on a frame on the main timeline, using Flash Professional + but you want it to be called in a different this context:

+ +
+     function myFunction(item:Object, index:int, vector:Vector.<T>):T {
+        // your code here
+     }
+     
+ +

Suppose you then use the map() + method on a Vector called myVector:

+ +
+     myVector.map(myFunction, someObject);
+     
+ +

Because myFunction is a member of the + main class of the SWF file, it cannot be executed in a different this context. Flash + runtimes throw an exception when this code runs. You can avoid this runtime error + by assigning the function to a variable, as follows:

+ +
+     var myFunction:Function = function(item:T, index:int, vector:Vector.<T>):void {
+         //your code here
+     };
+     myVector.map(myFunction, someObject);
+     
+ +
Vector.filter()
pop + Removes the last element from the Vector and returns that element.If this method is called while fixed is true. + + RangeErrorRangeErrorThe value of the last element in the specified Vector. + + + Removes the last element from the Vector and returns that element. The + length property of the Vector is decreased by one when + this function is called. + + Vector.push()Vector.shift()Vector.unshift()push + Adds one or more elements to the end of the Vector and returns + the new length of the Vector.If any argument is not an instance of the + base type T of the Vector. + + TypeErrorTypeErrorIf this method is called while fixed is true. + + RangeErrorRangeErrorThe length of the Vector after the new elements are added. + + uintargsOne or more values to append to the Vector. + + + Adds one or more elements to the end of the Vector and returns + the new length of the Vector. + +

Because this function can accept + multiple arguments, the data type of the arguments is not + checked at compile time even in strict mode. However, if an + argument is passed that is not an instance of the base type, + an exception occurs at run time.

+ +
Vector.pop()Vector.shift()Vector.unshift()
reverse + Reverses the order of the elements in the Vector.The Vector with the elements in reverse order. + + + Reverses the order of the elements in the Vector. This method + alters the Vector on which it is called. + + shift + Removes the first element from the Vector and returns that element.If fixed is true. + + RangeErrorRangeErrorThe first element in the Vector. + + + Removes the first element from the Vector and returns that element. + The remaining Vector elements are moved from their original position, + i, to i - 1. + + Vector.pop()Vector.push()Vector.unshift()slice + Returns a new Vector that consists of a range of elements from + the original Vector, without modifying the original Vector.a Vector that consists of a range of elements from the original Vector. + + startIndexint0A number specifying the index of the starting point + for the slice. If startIndex is a negative number, the starting + point begins at the end of the Vector, where -1 is the last element. + + endIndexint16777215A number specifying the index of the ending point for + the slice. If you omit this parameter, the slice includes all elements from the + starting point to the end of the Vector. If endIndex is a negative + number, the ending point is specified from the end of the Vector, where -1 is the + last element. + + Returns a new Vector that consists of a range of elements from the original Vector. + + + Returns a new Vector that consists of a range of elements from + the original Vector, without modifying the original Vector. The + returned Vector includes the startIndex element and + all elements up to, but not including, the endIndex element. + +

If you don't pass any parameters, the new Vector is a duplicate (shallow clone) of the original Vector. + If you pass a value of 0 for both parameters, a new, empty Vector is created of the same type + as the original Vector.

+ +
some + Executes a test function on each item in the Vector until an + item is reached that returns true.A Boolean value of true if any items in the Vector return + true for the specified function; otherwise, false. + + BooleancallbackFunctionThe function to run on each item in the Vector. + This function is invoked + with three arguments: the current item from the Vector, the index of the item, + and the Vector object: +
function callback(item:T, index:int, vector:Vector.<T>):Boolean
+ +

The callback function should return a Boolean value.

+ +
thisObjectObjectnullThe object that the identifer this in the + callback function refers to when the function is called. + +
+ Executes a test function on each item in the Vector until an + item is reached that returns true. Use this method + to determine whether any items in a Vector meet a criterion, such as + having a value less than a particular number. + +

For this method, the second parameter, + thisObject, must be null if the + first parameter, callback, is a method closure. That is + the most common way of using this method.

+ +

However, suppose you create a function on a frame on the main timeline, + but you want it to be called in a different this context:

+ +
+     function myFunction(item:Object, index:int, vector:Vector.<T>):Boolean {
+        // your code here
+     }
+     
+ +

Suppose you then use the some() + method on a Vector called myVector:

+ +
+     myVector.some(myFunction, someObject);
+     
+ +

Because myFunction is a member of the + main class of the SWF file, it cannot be executed in a different this context. Flash + runtimes throw an exception when this code runs. You can avoid this runtime error + by assigning the function to a variable, as follows:

+ +
+     var myFunction:Function = function(item:T, index:int, vector:Vector.<T>):Boolean {
+         //your code here
+     };
+     myVector.some(myFunction, someObject);
+     
+ +
every()
sort + Sorts the elements in the Vector.This Vector, with elements in the new order. + + compareFunctionFunctionA comparison method that determines + the behavior of the sort. + +

The specified method must take two arguments of the base type (T) + of the Vector and return a Number:

+ + function compare(x:T, y:T):Number {} + +

The logic of the compareFunction function is that, given two + elements x and y, the function returns one of the + following three values:

+ +
  • a negative number, if x should appear before y + in the sorted sequence
  • 0, if x equals y
  • a positive number, if x should appear after y + in the sorted sequence
+ +
+ Sorts the elements in the Vector. This method sorts according to the function + provided as the compareFunction parameter. + +
splice + Adds elements to and removes elements from the Vector.If the startIndex and deleteCount + arguments specify an index to be deleted that's outside the Vector's bounds. + + RangeErrorRangeErrorIf this method is called while fixed is true and the + splice() operation changes the length of the Vector. + + RangeErrorRangeErrora Vector containing the elements that were removed from the original Vector. + + startIndexintAn integer that specifies the index of the element + in the Vector where the insertion or deletion begins. You can use a + negative integer to specify a position relative to the end of the Vector + (for example, -1 for the last element of the Vector). + + deleteCountuint4294967295An integer that specifies the number of elements + to be deleted. This number includes the element specified in the + startIndex parameter. If you do not specify a value for the + deleteCount parameter, the method deletes all of the values + from the startIndex element to the last element in the Vector. + (The default value is uint.MAX_VALUE.) + If the value is 0, no elements are deleted. + + itemsAn optional list of one or more comma-separated values + to insert into the Vector at the position specified in the startIndex parameter. + + + Adds elements to and removes elements from the Vector. This method modifies + the Vector without making a copy. + +

Note: To override this method in a subclass of Vector, + use ...args for the parameters, as this example shows:

+ +
+     public override function splice(...args) {
+       // your statements here
+     }
+     
+ +
toLocaleString + Returns a string that represents the elements in the specified Vector.A string of Vector elements. + + String + Returns a string that represents the elements in the specified Vector. + Every element in the Vector, starting with index 0 and ending with the + highest index, is converted to a concatenated string and separated by + commas. In the ActionScript 3.0 implementation, this method returns + the same value as the Vector.toString() method. + + Vector.toString()toString + Returns a string that represents the elements in the Vector.A string of Vector elements. + + String + Returns a string that represents the elements in the Vector. Every element in the + Vector, starting with index 0 and ending with the highest index, is converted to a + concatenated string and separated by commas. To specify a custom separator, + use the Vector.join() method. + + String.split()Vector.join()unshift + Adds one or more elements to the beginning of the Vector and returns + the new length of the Vector.If any argument is not an instance of the + base type T of the Vector. + + TypeErrorTypeErrorIf this method is called while fixed is true. + + RangeErrorRangeErrorAn integer representing the new length of the Vector. + + uintargsOne or more instances of the base type of the Vector + to be inserted at the beginning of the Vector. + + + Adds one or more elements to the beginning of the Vector and returns + the new length of the Vector. The other elements in the Vector are moved + from their original position, i, to i + the number of new elements. + +

Because this function can accept + multiple arguments, the data type of the arguments is not + checked at compile time even in strict mode. However, if an + argument is passed that is not an instance of the base type, + an exception occurs at run time.

+ +
Vector.pop()Vector.push()Vector.shift()
fixed + Indicates whether the length property of the Vector can + be changed.Boolean + Indicates whether the length property of the Vector can + be changed. If the value is true, the length + property can't be changed. This means the following operations are not + allowed when fixed is true: + +
  • setting the length property directly
  • assigning a value to index position length
  • calling a method that changes the length property, including: +
    • pop()
    • push()
    • shift()
    • unshift()
    • splice() (if the splice() call changes + the length of the Vector).
    +
+ +
length + The range of valid indices available in the Vector.uintIf this property is changed + while fixed is true. + + RangeErrorRangeErrorIf this property is set to a value larger + than the maximum allowable index (232). + + RangeErrorRangeError + The range of valid indices available in the Vector. + A Vector instance has index positions up to but not including + the length value. + +

Every Vector element always has a value that is either an + instance of the base type or null. When the + length property is set to a value + that's larger than its previous value, additional elements are + created and populated with the default value appropriate to + the base type (null for reference types).

+ +

When the length property is set to a value + that's smaller than its previous value, all the elements + at index positions greater than or equal to the new length + value are removed from the Vector.

+ +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/adobe.utils.xml b/language-server/playerglobal_docs/adobe.utils.xml new file mode 100644 index 0000000..af08dd0 --- /dev/null +++ b/language-server/playerglobal_docs/adobe.utils.xml @@ -0,0 +1,170 @@ +adobe.utilsXMLUI + + The XMLUI class enables communication with SWF files that are used as custom user interfaces for the Flash + authoring tool's extensibility features.Object + The XMLUI class enables communication with SWF files that are used as custom user interfaces for the Flash + authoring tool's extensibility features. + +

Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 and later versions come with several extensibility + features including Behaviors, Commands (JavaScript API), Effects, and Tools. With these features, advanced + users can extend or automate the authoring tool's capabilities. The XML-to-UI engine works with each of + these extensibility features to create dialog boxes that the user sees if the extension either requires or + accepts parameters. You can define dialog boxes by using XML tags or by creating a SWF file to display. + The XMLUI object provides a mechanism by which an advanced user can communicate with a SWF file used in + such a manner.

+ +
accept + + Makes the current XMLUI dialog box close with an "accept" state. + + Makes the current XMLUI dialog box close with an "accept" state. This is identical to the user + clicking the OK button. + + + cancel + + Makes the current XMLUI dialog box close with a "cancel" state. + + Makes the current XMLUI dialog box close with a "cancel" state. This is identical to + the user clicking the Cancel button. + + getProperty + + Retrieves the value of the specified property of the current XMLUI dialog box.The value of the property. + + StringnameStringThe name of the XMLUI property to retrieve. + + + + Retrieves the value of the specified property of the current XMLUI dialog box. + + setProperty + + Modifies the value of the specified property of the current XMLUI dialog.nameStringThe name of the XMLUI property to modify. + valueStringThe value to which the specified property will be set. + + + + Modifies the value of the specified property of the current XMLUI dialog. + +
CustomActions + + The methods of the CustomActions class allow a SWF file playing in the Flash authoring + tool to manage any custom actions that are registered with the authoring tool.Object + + The methods of the CustomActions class allow a SWF file playing in the Flash authoring + tool to manage any custom actions that are registered with the authoring tool. A SWF + file can install and uninstall custom actions, retrieve the XML definition of a custom + action, and retrieve the list of registered custom actions. +

You can use these methods to build SWF files that are extensions of the Flash + authoring tool. Such an extension could, for example, use the Flash Application + Protocol to navigate a Universal Description, Discovery and Integration (UDDI) + repository and download web services into the Actions toolbox.

+ +
getActions + Reads the contents of the custom action XML definition file named name.If the custom action XML definition is located, returns a string; otherwise, returns undefined. + + StringnameStringThe name of the custom action definition to retrieve. + + Reads the contents of the custom action XML definition file named name. +

The name of the definition file must be a simple filename, without the .xml file extension, and without any directory separators (':', '/' or '\').

+

If the definition file specified by the name cannot be found, a value of undefined is returned. If the custom action XML definition specified by the name parameter is located, it is read in its entirety and returned as a string.

+ +
installActions + Installs a new custom action XML definition file indicated by the + name parameter.A Boolean value of false if an error occurs during + installation; otherwise, a value of true is returned to indicate that + the custom action has been successfully installed. + + nameStringThe name of the custom action definition to install. + dataStringThe text of the XML definition to install. + + Installs a new custom action XML definition file indicated by the + name parameter. The contents of the file is specified + by the string data. +

The name of the definition file must be a simple filename, without the .xml + file extension, and without any directory separators (':', '/' or + '\').

+

If a custom actions file already exists with the name + name, it is overwritten.

+

If the Configuration/ActionsPanel/CustomActions directory does not exist when + this method is invoked, the directory is created.

+ +
uninstallActions + Removes the Custom Actions XML definition file named name.nameStringThe name of the custom action definition to uninstall. + + + Removes the Custom Actions XML definition file named name. +

The name of the definition file must be a simple filename, without the .xml file extension, and without any directory separators (':', '/' or '\').

+ +
installActions()
actionsList + Returns an Array object containing the names of all the custom actions that are registered + with the Flash authoring tool.Array + Returns an Array object containing the names of all the custom actions that are registered + with the Flash authoring tool. The elements of the array are simple names, without the .xml file + extension, and without any directory separators (for example, ":", "/", + or "\"). If there are no registered custom actions, actionsList() + returns a zero-length array. If an error occurs, actionsList() returns the value + undefined. + +
MMEndCommand + Notifies an application hosting a SWF command that a command is done and instructs the application to commit or discard + the changes submitted by the MMExecute() command.endStatusBoolean A Boolean value; use true to commit changes, + otherwise false. If set to false, any pending changes are + discarded. + notifyStringString A string containing an error message or the reason the changes will + be discarded. If the endStatus parameter value is true, + use an empty string for the notifyString parameter value. + + Notifies an application hosting a SWF command that a command is done and instructs the application to commit or discard + the changes submitted by the MMExecute() command. + MMExecute + Lets you issue Flash JavaScript API (JSAPI) commands from ActionScript.A string representation of the result, if any, sent by the JavaScript statement. + StringnameString A string passed to MMExecute(). MMExecute() parses the string and + executes any JavaScript commands. + You can assign the string a variable and then pass the variable to MMExecute(). You can also + separate your JavaScript function into smaller strings; + MMExecute() returns the value of the last function called. + + Lets you issue Flash JavaScript API (JSAPI) commands from ActionScript. + In Flash Professional, the MMExecute() function can be called only by a movie that + is used as a Flash Panel, by an XMLtoUI dialog box, or by the Custom UI + of a component. JSAPI commands have no effect outside the authoring environment. +

The Flash JSAPI provides several objects, methods, and properties to duplicate + or emulate commands that a user can enter in the authoring environment. Using the JSAPI, + you can write scripts that extend Flash in several ways: adding commands to menus, + manipulating objects on the Stage, repeating sequences of commands, and so on.

+

In general, a user runs a JSAPI script by selecting Commands > Run Command. However, + you can use this function in an ActionScript script to call a JSAPI command directly. + If you use MMExecute() in a script on Frame 1 of your file, the command executes when + the SWF file is loaded.

+

For more information on the JSAPI, + see "Extending Flash" at http://www.adobe.com/go/jsapi_info_en.

+
\ No newline at end of file diff --git a/language-server/playerglobal_docs/air.desktop.xml b/language-server/playerglobal_docs/air.desktop.xml new file mode 100644 index 0000000..62dbec1 --- /dev/null +++ b/language-server/playerglobal_docs/air.desktop.xml @@ -0,0 +1,144 @@ +air.desktopURLFilePromise + + The URLFilePromise class allows resources accessible at a URL to be dragged out of an AIR application as a file promise.flash.desktop:IFilePromiseflash.events:EventDispatcher + The URLFilePromise class allows resources accessible at a URL to be dragged out of an AIR application as a file promise. + +

The URLFilePromise class implements the IFilePromise interface using URLStream and URLRequest objects as the data source. + The implementation provides drag and drop support for files that can be retrieved using HTTP or the other protocols supported + by the URLStream class.

+ +

To create a URL file promise:

+
  1. Construct and initialize one or more URLFilePromise objects.
  2. Add the URLFilePromise objects to an array.
  3. Add the array to a new Clipboard object using the ClipboardFormat, FILE_PROMISE_LIST.
  4. In response to a user gesture, call the NativeDragManager startDrag() method, passing in the + Clipboard object containing the array of file promises.
+ +

When the user completes the drag operation, the runtime downloads the data for each file promise. The data is + accessed at the URL specified by the request property of the URLFilePromise object and saved to the file + specified in the relativePath property. The file is saved relative to the drop location. Thus, if the + relative path is foo/bar.txt, and the file promise is dropped into a directory called home, then the location of the + created file is: home/foo/bar.txt. When an error occurs, the file is not created.

+ +

To support data sources that are not accessible through the URLStream class, implement the IFilePromise interface.

+ +

Note: The AIR runtime calls the IFilePromise methods, open(), close(), and reportError() + automatically. These methods should never be called by your application logic. Likewise, the open, progress, + complete, and close events dispatched by this URLFilePromise object are provided primarily for debugging + purposes. Your application does not need to respond to these events.

+ +

This class is included in the aircore.swc file. + Adobe® Flash Builder loads this class automatically when you create a project for + Adobe® AIR. The Adobe® Flex SDK also + includes this aircore.swc file, which you should include when compiling the application if you are using + the Flex SDK. +

+ +

To use air.desktop package in Adobe® Flash® Professional (CS4 or higher):

+ +
  1. Select the File > Publish Settings command.
  2. In the Flash panel, click the Settings button for ActionScript 3.0. Select Library Path.
  3. Click the Browse to SWC File button. Browse to Adobe Flash CSn/AIKn.n/frameworks/libs/air/aircore.swc + file in the Adobe Flash Professional installation folder.
  4. Click the OK button.
  5. Add the following import statement to your ActionScript 3.0 code: import air.desktop.~~;
+ + + + + +
IFilePromise interfaceClipboard classClipboardFormats classNativeDragManager classURLStream classURLRequest classsecurityError +Dispatched when a security error prevents the file download.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent +Dispatched when a security error prevents the file download. + +httpStatus +Dispatched for HTTP requests to report the request status code.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent +Dispatched for HTTP requests to report the request status code. + +httpResponseStatus +Dispatched for HTTP requests to report the response headers.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent +Dispatched for HTTP requests to report the response headers. + +ioError +Dispatched when an IOError prevents the file download.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent +Dispatched when an IOError prevents the file download. + +progress +Dispatched when a block of data is available to be read from the underlying URLStream.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent +Dispatched when a block of data is available to be read from the underlying URLStream. + +

Note: The AIR runtime uses this event to manage the asynchronous data retrieval process. +Typically, there is no need for your application to take any action in response to this event.

+ +
complete +Dispatched when the data for the file has been fully downloaded.flash.events.Event.COMPLETEflash.events.Event +Dispatched when the data for the file has been fully downloaded. + +

Note: The AIR runtime uses this event to manage the asynchronous data retrieval process. +Typically, there is no need for your application to take any action in response to this event.

+ +
open +Dispatched when the underlying URLStream connection is opened.flash.events.Event.OPENflash.events.Event +Dispatched when the underlying URLStream connection is opened. + +

Note: The AIR runtime uses this event to manage the asynchronous data retrieval process. +Typically, there is no need for your application to take any action in response to this event.

+ +
URLFilePromise + Creates a URLFilePromise object. + Creates a URLFilePromise object. + +

You must set the request and relativePath properties before + using this URLFilePromise object.

+ +
close + Allows the AIR runtime to close the data source at the appropriate time during the drag-and-drop operation. + Allows the AIR runtime to close the data source at the appropriate time during the drag-and-drop operation. + +

Do not call this function in your application logic.

+ +
open + Allows the AIR runtime to open the data source at the appropriate time during the drag-and-drop operation.flash.utils:IDataInput + Allows the AIR runtime to open the data source at the appropriate time during the drag-and-drop operation. + +

Do not call this function in your application logic.

+ +
reportError + Allows the AIR runtime to report errors that occur during the drag-and-drop operation.eflash.events:ErrorEvent + Allows the AIR runtime to report errors that occur during the drag-and-drop operation. + +

The URLFilePromise object redispatches any error events reported. Do not call this + function in your application logic.

+ +
isAsync + Indicates whether the resource data is available asynchronously.Boolean + Indicates whether the resource data is available asynchronously. + +

The isAsync property of a URLFilePrmise object is always true since URL streams are inherently asynchronous.

+ +
relativePath + The path and file name of the created file, relative to the drop destination.String + The path and file name of the created file, relative to the drop destination. + +

The path can include subdirectories, which are resolved based on the drop location. The subdirectories are created, + if needed. When including subdirectories, use the File.separator constant to insert the + proper path separator character for the current operating system. Using the .. shortcut to navigate to a parent directory + is not allowed.

+ +

The file name does not need to be the same as the file name of the remote resource.

+ +
request + The URLRequest identifying the resource to be copied as the result of the drag-and-drop operation.flash.net:URLRequest + The URLRequest identifying the resource to be copied as the result of the drag-and-drop operation. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/air.net.xml b/language-server/playerglobal_docs/air.net.xml new file mode 100644 index 0000000..55ad6ca --- /dev/null +++ b/language-server/playerglobal_docs/air.net.xml @@ -0,0 +1,427 @@ +air.netURLMonitor + + The URLMonitor class monitors availablity of an HTTP- or HTTPS-based service.air.net:ServiceMonitor + The URLMonitor class monitors availablity of an HTTP- or HTTPS-based service. + +

This class is included in the aircore.swc file. + Adobe® Flash Builder loads this class automatically when you create a project for + Adobe® AIR. The Adobe® Flex SDK also + includes this aircore.swc file, which you should include when compiling the application if you are using + the Flex SDK. +

+ +

In Adobe® Flash® CS3 Professional, + this class is included in the ServiceMonitorShim.swc file. To use classes in the air.net package , + you must first drag the ServiceMonitorShim component from the Components panel to the + Library and then add the following import statement to your ActionScript 3.0 code: +

+ + import air.net.~~; + +

To use air.net package in Adobe® Flash® Professional (CS4 or higher):

+ +
  1. Select the File > Publish Settings command.
  2. In the Flash panel, click the Settings button for ActionScript 3.0. Select Library Path.
  3. Click the Browse to SWC File button. Browse to Adobe Flash CSn/AIKn.n/frameworks/libs/air/aircore.swc + file in the Adobe Flash Professional installation folder.
  4. Click the OK button.
  5. Add the following import statement to your ActionScript 3.0 code: import air.net.~~;
+ + + + + +
URLMonitor + Creates a URLMonitor Object for a specified HTTP- or HTTPS-based service.urlRequestflash.net:URLRequestThe URLRequest object representing a probe request for polling the server. + + acceptableStatusCodesArraynullAn array of numeric status codes listing the codes that represent a successful result. + +

If you do not specify a value for the acceptableStatusCodes property, the following status + codes will be recognized as successful responses:

+ +
  • 200 (OK)
  • 202 (Accepted)
  • 204 (No content
  • 205 (Reset content)
  • 206 (Partial content, in response to request with a Range header)
+ +
+ Creates a URLMonitor Object for a specified HTTP- or HTTPS-based service. + +

After creating a URLMonitor, the caller should call the start() + method to begin monitoring the status of the service.

+ +

As with the Timer object, the caller should maintain a reference to the URLMonitor + object. Otherwise the runtime could delete the object, thereby ending the monitoring.

+ +

A URLRequest parameter specifies the probe request for polling the server. + Typically, the request method will be either "GET" or "HEAD".

+ +
checkStatus + Attempts to load content from a URL in the background, to check for a + returned HTTP status code. + Attempts to load content from a URL in the background, to check for a + returned HTTP status code. +

+ If it receives a status code that is listed in the acceptableStatusCodes + property, the available property will be set to true. + If it receives a status code that is not in the acceptableStatusCodes + list, or if there is a security error or I/O error, the available + property will be set to false. +

+ +
toString + + + Returns the string representation of the specified object.A string representation of the object. + + String + + + Returns the string representation of the specified object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

+ +
acceptableStatusCodes + The numeric status codes representing a successful result.Array + The numeric status codes representing a successful result. + + urlRequest + The URLRequest object representing the probe request.flash.net:URLRequest + The URLRequest object representing the probe request. + +
ServiceMonitor + The ServiceMonitor class implements the framework for monitoring the status and availability of network services.flash.events:EventDispatcher + The ServiceMonitor class implements the framework for monitoring the status and availability of network services. + The ServiceMonitor class acts as the base class for all other service monitors. + +

This class is included in the aircore.swc file. + Adobe® Flash™ Builder™ loads this class automatically + when you create a project for Adobe® AIR™. + Adobe® Flex™ SDK also includes this aircore.swc file, + which you should include when compiling the application if you are using Flex SDK. +

+ +

In Adobe® Flash® CS3 Professional, + this class is included in the ServiceMonitorShim.swc file. To use classes in the air.net package , + you must first drag the ServiceMonitorShim component from the Components panel to the + Library and then add the following import statement to your ActionScript 3.0 code: +

+ + import air.net.~~; + +

To use air.net package in Adobe® Flash® Professional (CS4 or higher):

+ +
  1. Select the File > Publish Settings command.
  2. In the Flash panel, click the Settings button for ActionScript 3.0. Select Library Path.
  3. Click the Browse to SWC File button. Browse to Adobe Flash CSn/AIKn.n/frameworks/libs/air/aircore.swc + file in the Adobe Flash Professional installation folder.
  4. Click the OK button.
  5. Add the following import statement to your ActionScript 3.0 code: import air.net.~~;
+ + + + + +
status + Indicates that the service status has changed.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Indicates that the service status has changed. + +

The value of the code property is either "Service.available" or "Service.unavailable", + but best practice is to check the value of the ServiceMonitor.available property.

+ +
ServiceMonitor + Creates a ServiceMonitor object. + Creates a ServiceMonitor object. + +

This class is typically subclassed to monitor specific service types.

+ + + +

After creating a ServiceMonitor object (or a subclass object), call the start() method + to begin monitoring the status of the service.

+ +

As with the Timer object, the caller should maintain a reference to the ServiceMonitor + object. Otherwise, the runtime deletes the object and monitoring ends.

+ +
checkStatus + Checks the status of the service. + Checks the status of the service. + +

A subclass override method for checking the status of the service.

+ +

Typically, this method will initiate a network operation whose completion or failure will result in + setting the available property.

+ +

JavaScript code can specialize this method by defining a checkStatus() method + in the "specializer" object.

+ +
makeJavascriptSubclass + Adds public ServiceMonitor methods to a JavaScript constructor function's prototype.constructorFunctionObjectThe JavaScript object's prototype property. For example, if the JavaScript + object that you are using to serve as a specializer object is named MyHTTPMonitor, pass + MyHTTPMonitor.prototype as the value for this parameter. + + + Adds public ServiceMonitor methods to a JavaScript constructor function's prototype. + +

Adds functions to the JavaScript constructor function's prototype that forward public + ServiceMonitor functions to the ServiceMonitor object. This approximates + a normal JavaScript subclass of the ActionScript base class.

+ +

A JavaScript class specializing a ServiceMonitor would look like this:

+ + + // JavaScript Constructor function + function MyHTTPMonitor(url, method) + { + // "that" variable makes "this" available in closures below + var that = this; + // Required initialization of the service monitor, returns the actual ServiceMonitor object. + this.monitor = this.initServiceMonitor(); + // Initializes URLStream and event handlers. + this._urlStream = new air.URLStream(); + this._urlRequest = new air.URLRequest(url); + if (method) + { + this._urlRequest.method = method; + } + else + { + this._urlRequest.method = "GET"; + } + function onStatus(event) { + that.monitor.available = Number(event.status) == 200; + that._urlStream.close(); + } + function onError(event) + { + that.monitor.available = false; + that._urlStream.close(); + } + this._urlStream.addEventListener(air.HTTPStatusEvent.HTTP_RESPONSE_STATUS, onStatus); + this._urlStream.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, onError); + this._urlStream.addEventListener(air.IOErrorEvent.IO_ERROR, onError); + } + + // Augment JavaScript prototype with public methods from ServiceMonitor + air.ServiceMonitor.makeJavascriptSubclass(MyHTTPMonitor); + + // Implement specializer functions, just as you would when subclassing a JavaScript class + MyHTTPMonitor.prototype.checkStatus = function() + { + air.trace('OVERRIDDEN checkStatus!', this); + this._urlStream.load(this._urlRequest); + } + + +

To use the JavaScript class:

+ + + var httpMon = new MyHTTPMonitor('http://www.adobe.com') + + +

Be sure to load the AIRAliases.js and aircore.swf files with script tags.

+ +
start + Starts the service monitor. + Starts the service monitor. + + stop + Stops monitoring the service. + Stops monitoring the service. + + toString + + Returns the string representation of the specified object.A string representation of the object. + + String + + Returns the string representation of the specified object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

+ +
available + Whether the service is currently considered "available." + + The initial value is false until either a status check sets the + property to true or the property is initialized to true explicitly. + + Typically, this property is set by the checkStatus() implementation in a subclass or specializer, + but if the application has independent information about a service's availability (for example, a request just succeeded + or failed), the property can be set explicitly. + + Boolean + Whether the service is currently considered "available." + +

The initial value is false until either a status check sets the + property to true or the property is initialized to true explicitly.

+ +

Typically, this property is set by the checkStatus() implementation in a subclass or specializer, + but if the application has independent information about a service's availability (for example, a request just succeeded + or failed), the property can be set explicitly.

+ +
lastStatusUpdate + The time of the last status update.Date + The time of the last status update. + + pollInterval + The interval, in milliseconds, for polling the server.Number0 + + + The interval, in milliseconds, for polling the server. + +

If zero, the server is not polled periodically, but only immediately after start() is called + and when the network status changes.

+ +

The ServiceMonitor object only dispatches a status event if service + status has changed (not on every poll interval). The object also dispatches a status + event as a result of network connectivity changes (regardles of the poll interval).

+ +
running + Whether the monitor has been started.Boolean + Whether the monitor has been started. + +
SecureSocketMonitor + A SecureSocketMonitor object monitors availablity of a TCP endpoint over Secure Sockets Layer (SSL) + and Transport Layer Security (TLS) protocols.air.net:SocketMonitor + A SecureSocketMonitor object monitors availablity of a TCP endpoint over Secure Sockets Layer (SSL) + and Transport Layer Security (TLS) protocols. + +

This class is included in the aircore.swc file. + Flash Builder loads this class automatically when you create a project for AIR. + The Flex SDK also includes this aircore.swc file, which you should include + when compiling the application if you are using Flex SDK. +

+ +

In Adobe® Flash® CS3 Professional, + this class is included in the ServiceMonitorShim.swc file. To use classes in the air.net package , + you must first drag the ServiceMonitorShim component from the Components panel to the + Library and then add the following import statement to your ActionScript 3.0 code: +

+ + import air.net.~~; + +

To use air.net package in Adobe® Flash® Professional (CS4 or higher):

+ +
  1. Select the File > Publish Settings command.
  2. In the Flash panel, click the Settings button for ActionScript 3.0. Select Library Path.
  3. Click the Browse to SWC File button. Browse to Adobe Flash CSn/AIKn.n/frameworks/libs/air/aircore.swc + file in the Adobe Flash Professional installation folder.
  4. Click the OK button.
  5. Add the following import statement to your ActionScript 3.0 code: import air.net.~~;
+ + + + + + +
SecureSocketMonitor + Creates a SecureSocketMonitor object for a specified TCP endpoint.hostStringThe host to monitor. + portintThe port to monitor. + + + Creates a SecureSocketMonitor object for a specified TCP endpoint. + +

After creating a SecureSocketMonitor object, the caller should call start + to begin monitoring the status of the service.

+ +

As with the Timer object, the caller should maintain a reference to the SecureSocketMonitor + object. Otherwise, the runtime deletes the object and monitoring ends.

+ +
createSocket + Creates a SecureSocket object.SecureSocket the SecureSocket object to be used by this SocketMonitor or null if + secure sockets are not supported on the current system. + + flash.net:Socket + Creates a SecureSocket object. + + toString + + + + Returns the string representation of the specified object.A string representation of the object. + + String + + + + Returns the string representation of the specified object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

+ +
SocketMonitor + A SocketMonitor object monitors availablity of a TCP endpoint.air.net:ServiceMonitor + A SocketMonitor object monitors availablity of a TCP endpoint. + +

This class is included in the aircore.swc file. + Flash Builder loads this class automatically when you create a project for AIR. + The Flex SDK also includes this aircore.swc file, which you should include + when compiling the application if you are using Flex SDK. +

+ +

In Adobe® Flash® CS3 Professional, + this class is included in the ServiceMonitorShim.swc file. To use classes in the air.net package , + you must first drag the ServiceMonitorShim component from the Components panel to the + Library and then add the following import statement to your ActionScript 3.0 code: +

+ + import air.net.~~; + +

To use air.net package in Adobe® Flash® Professional (CS4 or higher):

+ +
  1. Select the File > Publish Settings command.
  2. In the Flash panel, click the Settings button for ActionScript 3.0. Select Library Path.
  3. Click the Browse to SWC File button. Browse to Adobe Flash CSn/AIKn.n/frameworks/libs/air/aircore.swc + file in the Adobe Flash Professional installation folder.
  4. Click the OK button.
  5. Add the following import statement to your ActionScript 3.0 code: import air.net.~~;
+ + + + + +
SocketMonitor + Creates a SocketMonitor object for a specified TCP endpoint.hostStringThe host to monitor. + portintThe port to monitor. + + + Creates a SocketMonitor object for a specified TCP endpoint. + +

After creating a SocketMonitor object, the caller should call start + to begin monitoring the status of the service.

+ +

As with the Timer object, the caller should maintain a reference to the SocketMonitor + object. Otherwise, the runtime deletes the object and monitoring ends.

+ +
checkStatus + Calling the checkStatus() method of a SocketMonitor object causes + the application to try connecting to the socket, to check for a + connect event. + Calling the checkStatus() method of a SocketMonitor object causes + the application to try connecting to the socket, to check for a + connect event. + + createSocket + Creates a Socket object.the Socket object to be used by this SocketMonitor. + + flash.net:Socket + Creates a Socket object. + + toString + + + Returns the string representation of the specified object.A string representation of the object. + + String + + + Returns the string representation of the specified object. + +

Note: Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

+ +
host + The host being monitored.String + The host being monitored. + + port + The port being monitored.int + The port being monitored. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/air.update.events.xml b/language-server/playerglobal_docs/air.update.events.xml new file mode 100644 index 0000000..d9f9c50 --- /dev/null +++ b/language-server/playerglobal_docs/air.update.events.xml @@ -0,0 +1,361 @@ +air.update.eventsStatusUpdateEvent + + An updater object dispatches a StatusUpdateEvent object after the updater successfully + downloads and interprets the update descriptor file.air.update.events:UpdateEvent + An updater object dispatches a StatusUpdateEvent object after the updater successfully + downloads and interprets the update descriptor file. + +

The default behavior is to start downloading the update if the + available property of the StatusUpdateEvent object + is set to true. The default behavior can be prevented + only when using the ApplicationUpdater class.

+ +
air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIupdateStatusair.update.events:StatusUpdateEvent:UPDATE_STATUSair.update.events:StatusUpdateEventStatusUpdateEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + availableBooleanfalseText to be displayed as an error message. Event listeners can access this information through the text property. + versionStringA reference number to associate with the specific error. + detailsArraynullthe version string of the update. + versionLabelStringan array containing the description of update. The elements of the array alternate between local codes and a localized version of the description. + + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + UPDATE_STATUS + The StatusUpdateEvent.UPDATE_STATUS constant defines the value of the + type property of the event object for a updateStatus event.updateStatusString + The StatusUpdateEvent.UPDATE_STATUS constant defines the value of the + type property of the event object for a updateStatus event. + +

This event has the following properties:

+ + PropertyValueavailableSet to true if + the update descriptor file specifies a version that is different + than that of the current application; false otherwise + (the version is the same).versionThe string representing the new available version.detailsAn array defining the details string + for each of the supported languages. If there is no localized description, + this is defined as an array in which the first element is an empty + string ("") and the second element is the details + string. When there are localized descriptions, each element in the + array is an array itself with two elements. The first element is + the locale code, and the second is the description. For example, + the following array has sub-arrays for two languages (U.S. English + and French): ["en-US", "Hello World"], ["fr", "Bonjour monde"]. + The languages are listed in the same order as in the update descriptor. The + text for the details property is specified in the update descriptor file.versionLabel(AIR 2.5+) The version label from the application descriptor of + the update. The version label should be displayed to users instead of + version. If no version label is specified, this property is an empty string. + +
available + Indicates if an update is available.falseBoolean + Indicates if an update is available. This property is true if + the update descriptor file specifies a version that is different + than that of the current application; it is false otherwise + (the version is the same). + + details + An array defining the details string + for each of the supported languages.unknownArray + An array defining the details string + for each of the supported languages. If there is no localized description, + this is defined as an array in which the first element is an empty + string ("") and the second element is the details + string. When there are localized descriptions, each element in the + array is an array itself with two elements. The first element is + the locale code, and the second is the description. For example, + the following array has sub-arrays for two languages (U.S. English + and French): ["en-US", "Hello World"], ["fr", "Bonjour monde"]. + The languages are listed in the same order as in the update descriptor. + + versionLabel + The version label string of the update.String + The version label string of the update. + + version + The version string of the update.String + The version string of the update. + +

In AIR 2.5 and later, the version string is specified in the versionNumber + element of the application descriptor file. In earlier versions of AIR, the version string + is specified in the version element.

+ +
StatusUpdateErrorEvent + A StatusUpdateErrorEvent is dispatched when a call to the checkForUpdate() method + of an ApplicationUpdater object encounters an error while downloading or parsing the update descriptor file.flash.events:ErrorEvent + A StatusUpdateErrorEvent is dispatched when a call to the checkForUpdate() method + of an ApplicationUpdater object encounters an error while downloading or parsing the update descriptor file. + + air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIupdateErrorair.update.events:StatusUpdateErrorEvent:UPDATE_ERRORair.update.events:StatusUpdateErrorEventStatusUpdateErrorEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error. + subErrorIDint0Provides details about the error event, in addition to the errorID. + + + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + UPDATE_ERROR + The StatusUpdateErrorEvent.UPDATE_ERROR constant defines the value of the + type property of the event object for a statusUpdateError event.updateErrorString + The StatusUpdateErrorEvent.UPDATE_ERROR constant defines the value of the + type property of the event object for a statusUpdateError event. + + subErrorID + Provides information in addition to the errorId property.0int + Provides information in addition to the errorId property. + + DownloadErrorEvent + A DownloadErrorEvent object is dispatched by an ApplicationUpdater or ApplicationUpdaterUI + object when an error happens while downloading the update file.flash.events:ErrorEvent + A DownloadErrorEvent object is dispatched by an ApplicationUpdater or ApplicationUpdaterUI + object when an error happens while downloading the update file. + + air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIdownloadErrorair.update.events:DownloadErrorEvent:DOWNLOAD_ERRORair.update.events:DownloadErrorEventDownloadErrorEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error. + subErrorIDint0Provides details about the error event, in addition to the errorID. + + + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + DOWNLOAD_ERROR + The DownloadErrorEvent.DOWNLOAD_ERROR constant defines the value of the + type property of the event object for a downloadError event.downloadErrorString + The DownloadErrorEvent.DOWNLOAD_ERROR constant defines the value of the + type property of the event object for a downloadError event. + +

The errorID property of a DownloadErrorEvent object is + an integer defining error information (see the following + table). An additional subErrorID property may contain + more error information.

+ + errorID Error codeDescription16800Occurs during validating the downloaded + update file. The subErrorID property may contain additional + information.16801Invalid Adobe AIR file (missing application.xml).16802Invalid Adobe AIR file (missing MIME type).16803Invalid Adobe AIR file (format).16804Invalid Adobe AIR file (invalid flags).16805Invalid Adobe AIR file (unknown compression).16806Invalid Adobe AIR file (invalid filename).16807Invalid Adobe AIR file (corrupt).16808Configuration file does not exist.16809The updateURL property + is not set.16810Reserved.16811Invalid configuration file (unknown configuration + version).16812Invalid configuration file (URL missing).16813Invalid configuration file (delay format).16814Invalid configuration file (invalid defaultUI + values).16815Invalid update descriptor (unknown descriptor + version).16816Invalid update descriptor (missing update + version).16817Invalid update descriptor (invalid description).16818IO error while saving data to disk. The subErrorID property + may provide more information.16819Security error while downloading. The subErrorID property + may provide more information.16820Invalid HTTP status code. The subErrorID property + may contain the invalid status code.16821Reserved.16822I/O error while downloading. The subErrorID property + may provide more information.16823End-of-file error while saving data to disk. + The subErrorID property may provide more information.16824Invalid update descriptor. The subErrorID property may + provide more information.16825The update file contains an application + with a different application ID.16826The update file does not contain a newer + version of the application.16827The version contained in the update file + does not match the version from the update descriptor.16828Cannot update application, usually because + the application is running in the AIR Debug Launcher (ADL).16829Missing update file at install time. + +
subErrorID + Provides information in addition to the errorId property.0int + Provides information in addition to the errorId property. + +
StatusFileUpdateEvent + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method.air.update.events:UpdateEvent + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method. + +

The default behavior is to install the update if the available + of the available property of the StatusFileUpdateEvent object is + set to true. The default behavior can be prevented only when using + the ApplicationUpdater class.

+ +
air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIfileUpdateStatusair.update.events:StatusFileUpdateEvent:FILE_UPDATE_STATUSair.update.events:StatusFileUpdateEventStatusFileUpdateEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + availableBooleanfalseText to be displayed as an error message. Event listeners can access this information through the text property. + versionStringA reference number to associate with the specific error. + + pathString + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + FILE_UPDATE_STATUS + The StatusUpdateEvent.UPDATE_STATUS constant defines the value of the + type property of the event object for a updateStatus event.fileUpdateStatusString + The StatusUpdateEvent.UPDATE_STATUS constant defines the value of the + type property of the event object for a updateStatus event. + +

This event has the following properties:

+ +

PropertyValueavailableIndicates if if there is a different version + available than one of the current application (true); false otherwise (same version).pathThe nativePath property of + the update File object specified by the airFile parameter + in a call to the installFromAIRFile() method.versionIndicates the version of the new update.

+ +
available + Indicates if if there is a different version available than one of the current application + (true); false otherwise (same version).falseBoolean + Indicates if if there is a different version available than one of the current application + (true); false otherwise (same version). + + path + The nativePath property of + the update File object specified by the airFile parameter + in a call to the installFromAIRFile() method.nullString + The nativePath property of + the update File object specified by the airFile parameter + in a call to the installFromAIRFile() method. + + versionLabel + The version label string of the update.String + The version label string of the update. + + version + The version string of the update.String + The version string of the update. + +

In AIR 2.5 and later, the version string is specified in the versionNumber + element of the application descriptor file. In earlier versions of AIR, the version string + is specified in the version element.

+ +
StatusFileUpdateErrorEvent + A StatusUpdateFileErrorEvent is dispatched when a call to the checkForUpdate() method of a ApplicationUpdater object encounters an error + while downloading or parsing the update descriptor file.flash.events:ErrorEvent + A StatusUpdateFileErrorEvent is dispatched when a call to the checkForUpdate() method of a ApplicationUpdater object encounters an error + while downloading or parsing the update descriptor file. + + air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIfileUpdateErrorair.update.events:StatusFileUpdateErrorEvent:FILE_UPDATE_ERRORair.update.events:StatusFileUpdateErrorEventStatusFileUpdateErrorEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error. + + + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + FILE_UPDATE_ERROR + The StatusUpdateErrorEvent.UPDATE_ERROR constant defines the value of the + type property of the event object for a statusUpdateError event.fileUpdateErrorString + The StatusUpdateErrorEvent.UPDATE_ERROR constant defines the value of the + type property of the event object for a statusUpdateError event. + + UpdateEvent + A UpdateEvent is dispatched by a ApplicationUpdater object during the update process.flash.events:Event + A UpdateEvent is dispatched by a ApplicationUpdater object during the update process. + + air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIbeforeInstallair.update.events:UpdateEvent:BEFORE_INSTALLair.update.events:UpdateEventcheckForUpdateair.update.events:UpdateEvent:CHECK_FOR_UPDATEair.update.events:UpdateEventdownloadCompleteair.update.events:UpdateEvent:DOWNLOAD_COMPLETEair.update.events:UpdateEventdownloadStartair.update.events:UpdateEvent:DOWNLOAD_STARTair.update.events:UpdateEventinitializedair.update.events:UpdateEvent:INITIALIZEDair.update.events:UpdateEventUpdateEvent + The constructor function.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + + The constructor function. Do not call this function. The update framework calls it to create the event object. + + clone + Creates a copy of the object and sets the value of each property to match that of the original.flash.events:Event + Creates a copy of the object and sets the value of each property to match that of the original. + toString + Returns a string that contains all the properties of the object.String + Returns a string that contains all the properties of the object. + BEFORE_INSTALL + The UpdateEvent.BEFORE_INSTALL constant defines the value of the + type property of the event object for a beforeInstall event.beforeInstallString + The UpdateEvent.BEFORE_INSTALL constant defines the value of the + type property of the event object for a beforeInstall event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe updater object. + +
CHECK_FOR_UPDATE + The UpdateEvent.CHECK_FOR_UPDATE constant defines the value of the + type property of the event object for a checkForUpdate event.checkForUpdateString + The UpdateEvent.CHECK_FOR_UPDATE constant defines the value of the + type property of the event object for a checkForUpdate event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe updater object. + +
DOWNLOAD_COMPLETE + The UpdateEvent.DOWNLOAD_COMPLETE constant defines the value of the + type property of the event object for a downloadComplete event.downloadCompleteString + The UpdateEvent.DOWNLOAD_COMPLETE constant defines the value of the + type property of the event object for a downloadComplete event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe updater object. + +
DOWNLOAD_START + The UpdateEvent.DOWNLOAD_START constant defines the value of the + type property of the event object for a downloadStart event.downloadStartString + The UpdateEvent.DOWNLOAD_START constant defines the value of the + type property of the event object for a downloadStart event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe updater object. + +
INITIALIZED + The UpdateEvent.INITIALIZED constant defines the value of the + type property of the event object for a initialized event.initializedString + The UpdateEvent.INITIALIZED constant defines the value of the + type property of the event object for a initialized event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe updater object. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/air.update.xml b/language-server/playerglobal_docs/air.update.xml new file mode 100644 index 0000000..223aec4 --- /dev/null +++ b/language-server/playerglobal_docs/air.update.xml @@ -0,0 +1,1003 @@ +air.updateApplicationUpdater + + The ApplicationUpdater class defines the basic functionality of the update framework for + Adobe&#xAE; AIR&#xAE; applications, without providing any default user interface.flash.events:EventDispatcher + The ApplicationUpdater class defines the basic functionality of the update framework for + Adobe® AIR® applications, without providing any default user interface. + (The ApplicationUpdaterUI class includes update functionality and a default user interface.) + +

This class is included in the applicationupdater_ui.swc file, + included in the Adobe AIR SDK. The applicationupdater_ui.swc file is in the + frameworks/libs/air directory of the AIR SDK.

+ +

Adobe® Flex™ Builder™ loads this class automatically + when you create a project for Adobe AIR. You should include the SWC file when compiling + the application using the Adobe® Flex™ SDK.

+ + + + + +

Managing updates of applications can be complicated. The AIR update framework provides + APIs to assist developers in providing good update capabilities + in AIR applications. The functionality in the AIR update framework + assists developers in the following:

+ +
  • +

    Periodically checking for updates based on an interval + or at the request of the user

    +
  • +

    Downloading AIR files (updates) from a web source

    +
  • +

    Alerting the user on the first run of the newly installed + version

    +
  • +

    Confirming that the user wants to check for updates

    +
  • +

    Displaying information on the new update version to the user

    +
  • +

    Displaying download progress and error information to the + user

    +
+ +

The AIR update framework lets you store information about the + update version of an AIR application in simple XML configuration + files. For most applications, setting up these configuration files + and including some basic code provides good update functionality + to the end user.

+ +

Use the AIRUpdater class if you want to define your own user interface + for use with the AIR update framework.

+ +

The update process includes a sequence of states. The currentState + property of the updater object reflects the current state of the updater:

+ +

+ currentState value + + Description + "UNINITIALIZED"The updater has not been initialized."INITIALIZING"The updater is initializing."READY"The updater has been initialized"BEFORE_CHECKING"The updater has not yet checked for the update descriptor file."CHECKING"The updater is checking for an update descriptor file."AVAILABLE"The update descriptor file is available."DOWNLOADING"The updater is downloading the AIR file."DOWNLOADED"The updater has downloaded the AIR file."INSTALLING"The updater is installing the AIR file."PENDING_INSTALLING"The updater has initialized and there are pending updates.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, attempting to update the application + results in an IllegalOperationError exception.

+ +

The AIR update framework is only supported in the desktop profile. It is not supported + for extended desktop applications (applications installed with a native installer), + and it is not supported on the mobile profile (iPhone applications written with + ActionScript 3.0). Check the Updater.isSupported property at runtime + to see if the update framework is supported.

+ +

For details on using the AIR update framework, see the "Updating AIR Applications" + chapter of Developing Adobe AIR Applications with Apache Flex.

+ +

For details on using the AIR update framework, see the "Updating AIR Applications" + chapter of Developing Adobe AIR Applications with Adobe Flash.

+ + + +
ApplicationUpdaterUIflash.desktop.Updatererror + Dispatched when an error occurred either during initialization + or during the update process (if something unexpected happens).flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + Dispatched when an error occurred either during initialization + or during the update process (if something unexpected happens). + + progress + Dispatched as the update file is downloaded.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched as the update file is downloaded. + + fileUpdateError + Dispatched when an error occurs validating the file passed + as the airFile parameter in a call to the installFromAIRFile() method.air.update.events.StatusFileUpdateErrorEvent.FILE_UPDATE_ERRORair.update.events.StatusFileUpdateErrorEvent + Dispatched when an error occurs validating the file passed + as the airFile parameter in a call to the installFromAIRFile() method. + + fileUpdateStatus + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method.air.update.events.StatusFileUpdateEvent.FILE_UPDATE_STATUSair.update.events.StatusFileUpdateEvent + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method. + + downloadError + Dispatched if there is an error while connecting or downloading + the update file.air.update.events.DownloadErrorEvent.DOWNLOAD_ERRORair.update.events.DownloadErrorEvent + Dispatched if there is an error while connecting or downloading + the update file. It is also dispatched for invalid HTTP statuses + (such as 404 - File not found). + +

When this event is dispatched the periodic timer is automatically + restarted (if the delay is greater than 0).

+ +
updateError + Dispatched if an error occurs while trying to download or parse the update descriptor file.air.update.events.StatusUpdateErrorEvent.UPDATE_ERRORair.update.events.StatusUpdateErrorEvent + Dispatched if an error occurs while trying to download or parse the update descriptor file. + +

When the updater dispatches this event, the periodic timer + is automatically restarted (if the delay setting is greater than + 0). The application should consider hiding any error dialog boxes + when the updater dispatches a new checkForUpdate event.

+ +
updateStatus + Dispatched after the updater successfully downloads and + interprets the update descriptor file.air.update.events.StatusUpdateEvent.UPDATE_STATUSair.update.events.StatusUpdateEvent + Dispatched after the updater successfully downloads and + interprets the update descriptor file. + +

The default behavior is to start downloading the update if the + available of the available property of the StatusUpdateEvent object + is set to true. The default behavior can be prevented + only when using the ApplicationUpdater class, not when using the + ApplicationUpdatorUI class..

+ +
beforeInstall + Dispatched just before installing the update, after the installUpdate() method + was called.air.update.events.UpdateEvent.BEFORE_INSTALLair.update.events.UpdateEvent + Dispatched just before installing the update, after the installUpdate() method + was called. Sometimes, it is useful to prevent the installation + of the update at this time, because the user could lose all current work when + the runtime exits the application to install the update. + +

Calling this event's preventDefault() method + postpones the installation until the next restart. If you call + the preventDefault() method, no additional update + process can be started during this application session (via a call + to the installUpdate() method or because of the periodic check).

+ +

The default behavior for ApplicationUpdater library is to download + the update descriptor file. You can call the preventDefault() method + to cancel this behavior.

+ +
downloadComplete + Dispatched when the download of the update file is complete.air.update.events.UpdateEvent.DOWNLOAD_COMPLETEair.update.events.UpdateEvent + Dispatched when the download of the update file is complete. + +

Usually this event is used to display a message asking if + the user wants to proceed with the installation of the update.

+ +

The default behavior for the the ApplicationUpdater library is + to automatically call the installUpdate() method.

+ +
downloadStart + Dispatched after a call to the downloadUpdate() method + and the connection to the server is established.air.update.events.UpdateEvent.DOWNLOAD_STARTair.update.events.UpdateEvent + Dispatched after a call to the downloadUpdate() method + and the connection to the server is established. When using ApplicationUpdater + library, you may want the event handler for this event to display + a progress bar to report the download progress to the user. + + checkForUpdate + Dispatched before the update process begins, just before the + updater tries to download the update descriptor file.air.update.events.UpdateEvent.CHECK_FOR_UPDATEair.update.events.UpdateEvent + Dispatched before the update process begins, just before the + updater tries to download the update descriptor file. + The updater can dispatch this event as a result of directly + calling the checkNow() method or because the periodic + check timer expired. + + initialized + Dispatched after the initialization is complete.air.update.events.UpdateEvent.INITIALIZEDair.update.events.UpdateEvent + Dispatched after the initialization is complete. + + ApplicationUpdater + The constructor function. + The constructor function. + + cancelUpdate + Cancels the update process. + Cancels the update process. Calling this method cancels any + pending downloads, deleting any incomplete downloaded files, and + restarts the periodic check timer. + +

The update process can be canceled at any time except when the state + machine is in "UNINITIALIZED" or "INITIALIZING" state. It does nothing + when it is called in one of the "UNINITIALIZED" or "INITIALIZING" + states.

+ +
checkForUpdate + Asynchronously downloads and interprets + the update descriptor file. + Asynchronously downloads and interprets + the update descriptor file. Calling this method advances the updater + state to "CHECKING". Call this method only if the checkForUpdate event + was cancelled. + +

This method only executes when the updater is in the "BEFORE_CHECKING" + state.

+ +
updateStatusair.update.events:StatusUpdateEventThe updater has successfully downloaded and interpreted the update descriptor file. + + The updater has successfully downloaded and interpreted the update descriptor file.updateErrorair.update.events:StatusUpdateErrorEventAn error occured while trying to download or parse the update descriptor file. + + An error occured while trying to download or parse the update descriptor file.
checkNow + Starts the update process. + Starts the update process. Calling + this method does not stop the periodic timer; however, the method detects + that an update process is running and will skip the current iteration. + +

This method only executes if the current state is "READY".

+ +

This method can result in the updater object dispatching the following event:

+ +
checkForUpdateair.update.events:UpdateEventDispatched just before the update process begins. + + Dispatched just before the update process begins.
downloadUpdate + Asynchronously downloads the update file. + Asynchronously downloads the update file. Calling this method + advances the state machine to "DOWNLOADING". This method needs to be called + only if the StatusUpdateEvent.UPDATE_STATUS event was cancelled when + the available property of the event was true. + +

This method only executes if the current state is "AVAILABLE".

+ +
downloadStartair.update.events:UpdateEventDispatched after the connection to the server is established. + + Dispatched after the connection to the server is established.progressflash.events:ProgressEventDispatched after the initialization is complete. + + Dispatched after the initialization is complete.downloadErrorair.update.events:DownloadErrorEventDispatched if there is an error while connecting or downloading the update file. + It is also dispatched for invalid HTTP statuses (such as 404 - File not found). + + Dispatched if there is an error while connecting or downloading the update file.
initialize + Initializes the updater. + Initializes the updater. Calling this method + does the following: + +

  1. +

    It initializes the update framework, + silently (and synchronously) installing any pending updates. You + should call this method during application startup, since it may + restart the application.

    +
  2. + +

    It checks if there is a postponed update and installs it.

    +
  3. +

    If something went wrong with a prior update, it clears the + update file and version information from the storage area.

    +
  4. +

    If the periodic timer delay has expired, it starts the update process; otherwise + it starts the periodic timer. However, when testing an application using + the AIR Debug Launcher (ADL) application, attempting to update the + application results in a IllegalOperationError exception.

    +

+ +
initializedair.update.events:UpdateEventThe initialization is complete. + + The initialization is complete.errorflash.events:ErrorEventThere is an error during initialization. + + There is an error during initialization.
installFromAIRFile + Starts the update process using a local AIR file.fileflash.filesystem:FileThe local AIR file to install. + + + Starts the update process using a local AIR file. + +

Calling this + method has no effect if an update process is running (if the state + is not "DOWNLOADED").

+ +

This function is useful + for an application that has the customUpdateUI element + set to true in the application descriptor file.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, + calling this method results in an IllegalOperationError exception.

+ +
fileUpdateStatusair.update.events:StatusFileUpdateEventDispatched after the updater successfully + validates the AIR file. + + Dispatched after the updater successfully + validates the AIR file.updateErrorair.update.events:StatusFileUpdateErrorEventDispatched if an error occurs while trying + parse the update descriptor file. + + Dispatched if an error occurs while trying + parse the update descriptor file.
installUpdate + Installs the update file. + Installs the update file. Calling the method + advances the state machine to "INSTALLING" and needs to be called + only if the downLoadComplete event was cancelled. + +

Call this method when the updater is in the "DOWNLOADED" state. Calling + it in any other state will do nothing.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, + calling this method results in an IllegalOperationError exception.

+ +
beforeInstallair.update.events:UpdateEventDispatched just before installing the update. Sometimes it is useful + to prevent the installation of the update at this time, because the user could lose all current work when + the runtime exits the application to install the update. + + Dispatched just before installing the update.
configurationFile + The location of the configuration file that sets the values for delay and + updateURL properties.flash.filesystem:File + The location of the configuration file that sets the values for delay and + updateURL properties. If this property points to a non-existent file, calling + the initialize() method results in an Error being thrown. + +

Here is a sample configuration file:

+ + <?xml version="1.0" encoding="utf-8"?> + <configuration xmlns="http://ns.adobe.com/air/framework/update/configuration/1.0" > + <url>app:/server/update.xml</url> + <delay>1</delay> + </configuration> + +

Instead of loading a configuration file, you can use ActionScript + code to set the delay and updateURL + properties.

+ +
delayupdateURL
currentState + The internal state of the updater.String + The internal state of the updater. The property can be set to the following values: + +

  • +

    "UNINITIALIZED"—The updater has not been initialized.

    +
  • +

    "INITIALIZING"—The updater is initializing.

    +
  • +

    "READY"—The updater has been initialized

    +
  • +

    "BEFORE_CHECKING"—The updater has not yet + checked for the update descriptor file.

    +
  • +

    "CHECKING"—The updater is checking for an + update descriptor file.

    +
  • +

    "AVAILABLE"—The update descriptor file is + available.

    +
  • +

    "DOWNLOADING"—The updater is downloading + the AIR file.

    +
  • +

    "DOWNLOADED"—The updater has downloaded + the AIR file.

    +
  • +

    "INSTALLING"—The updater is installing the + AIR file.

    +
  • +

    "PENDING_INSTALLING"—The updater has initialized + and there are pending updates.

    +

+ +
currentVersion + The current version of the application.String + The current version of the application. This property is set during + a call to the initialize() method. It is set to + the version from the application descriptor file. + + delay + The interval, in days, between periodic checks of new updates.Number0 + + + The interval, in days, between periodic checks of new updates. + +

A value of 0 (the default value) indicates + that the timer is not active, so no periodic check is done. This + can be set either via this property or via the configuration file. + When the value is set using both methods, the value set using the + property is used.

+ +
isFirstRun + Whether this is the first run after a successful update (true) or not + (false).Boolean + Whether this is the first run after a successful update (true) or not + (false). The updater sets this value during the call to the initialize() + method. The developer should check that isFirstRun is set to true if + there is a need to migrate data from one version to another. + + wasPendingUpdateisNewerVersionFunction + A function that the updater should use to perform version comparisons.Function + A function that the updater should use to perform version comparisons. + By default, the update framework does a + version comparison to detect whether the version from the + remote site is newer than the version of the installed application. + However, sometimes the default comparison does not match the developer's + versioning scheme. Set this property to provide a new function that + does the comparison. + +

The default comparision function accepts + versions like x.y.z, where x, y, and z can contain letters + and digits. There are some special conditions that the default comparision function + recognizes. If the test function finds "alpha", "beta", + or "rc" in the version strings, + the order is alpha < beta < rc.

+ +
The following code defines a custom function, customFn, for the appUpdate updater object. + The example function is intentionally simple. Your custom function should return a Boolean value based on the rules of your + versioning scheme. + +appUpdate.isNewerVersionFunction = customFn; + +function customFn (currentVersion:String, updateVersion:String):Boolean +{ + return updateVersion > currentVersion; +} +
previousApplicationStorageDirectory + The previous location of the application storage directory, if it changed + after an update.flash.filesystem:File + The previous location of the application storage directory, if it changed + after an update. The application storage directory location changes after + an upgrade with a certificate migration. If there is no certificate + migration, the application storage directory does not change when the + user updates the application. and this property is set to null. + This property is set during a call to the initialize() method. + +

A developer can sign new version of AIR application with a new certificate + if the developer uses the -migrate option when packaging the AIR + file with ADT. If a new version of an AIR application uses a new signing certificate, + the local storage directory of the application changes when the user installs + the new version. Use this property to transfer data from the old application + storage directory to the new application storage directory + (File.applicationStorageDirectory). For more information, + see "Signing an AIR file to change the application certificate" in the + "Creating an AIR application using the command line tools" chapter of the + Adobe AIR developer's guide.

+ +
previousVersion + The previous version of the application.String + The previous version of the application. This property is set during + a call to the initialize() method. Returns the previous version of + the application before the upgrade (set only if isfirstRun is true); + otherwise it is set to null. + + updateDescriptor + The content of the update descriptor file downloaded from the update URL.XML + The content of the update descriptor file downloaded from the update URL. This property is + non-null only the updater object dispatches an updateStatus event. + + updateURL + The location of the update descriptor file.String + The location of the update descriptor file. Any location + valid for a URLRequest path is accepted. This is the only mandatory + setting required by the updater. You can set the update URL either via this + property or via the configuration file. When the value is set using + both methods, the updater uses the value set using this property. + + wasPendingUpdate + Whether there was a postponed update, even if it failed + to install (true); false otherwise.Boolean + Whether there was a postponed update, even if it failed + to install (true); false otherwise. + The updater sets this property during a call to the initialize() method. + Use the wasPendingUpdate and isFirstRun properties + to check if an update failed to install (in which case wasPendingUpdate + is set to true and isFirstRun is set to false). + + isFirstRun
ApplicationUpdaterUI + The ApplicationUpdaterUI class defines the basic functionality of the update framework for + Adobe&#xAE; AIR&#xAE; applications, and it provides a default user interface.flash.events:EventDispatcher + The ApplicationUpdaterUI class defines the basic functionality of the update framework for + Adobe® AIR® applications, and it provides a default user interface. + (The ApplicationUpdater class defines update functionality without implementing + a default user interface.) + +

This class is included in the applicationupdater_ui.swc file, + included in the Adobe AIR SDK. The applicationupdater_ui.swc file is in the + frameworks/libs/air directory of the AIR SDK. The version in the frameworks/libs/air + directory in the AIR 2 SDK is for Flex 4 development. If you use Flex 3, use the version + in the frameworks/libs/air/flex3 subdirectory.

+ +

Adobe® Flex™ Builder™ loads this class automatically + when you create a project for Adobe AIR. You should include the SWC file when compiling + the application using the Adobe® Flex™ SDK.

+ + + + + +

Managing updates of applications can be complicated. The AIR update framework provides + APIs to assist developers in providing good update capabilities + in AIR applications. The functionality in the AIR update framework + assists developers in the following:

+ +
  • +

    Periodically checking for updates based on an interval + or at the request of the user

    +
  • +

    Downloading AIR files (updates) from a web source

    +
  • +

    Alerting the user on the first run of the newly installed + version

    +
  • +

    Confirming that the user wants to check for updates

    +
  • +

    Displaying information on the new update version to the user

    +
  • +

    Displaying download progress and error information to the + user

    +
+ +

The AIR update framework lets you store information about the + update version of an AIR application in simple XML configuration + files. For most applications, setting up these configuration files + and including some basic code provides good update functionality + to the end user.

+ +

The AIRUpdateUI class implements a default user interface that + your application can use. It provides the user with basic information + and options related to application updates.

+ +

The update process goes through a sequence of states:

+ +

+ State + + Description + UninitializedThe updater has not been initialized.InitializingThe updater is initializing.ReadyThe updater has been initializedBefore checkingThe updater has not yet checked for the update descriptor file.CheckingThe updater is checking for an update descriptor file.AvailableThe update descriptor file is available.DownloadingThe updater is downloading the AIR file.DownloadedThe updater has downloaded the AIR file.InstallingThe updater is installing the AIR file.Pending installThe updater has initialized and there are pending updates.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, attempting to update the application + results in an IllegalOperationError exception.

+ +

The AIR update framework is only supported in the desktop profile. It is not supported + for extended desktop applications (applications installed with a native installer), + and it is not supported on the mobile profile (iPhone applications written with + ActionScript 3.0). Check the Updater.isSupported property at runtime + to see if the update framework is supported.

+ +

For details on using the AIR update framework, see the "Updating AIR Applications" + chapter of Developing Adobe AIR Applications with Apache Flex.

+ +

For details on using the AIR update framework, see the "Updating AIR Applications" + chapter of Developing Adobe AIR Applications with Adobe Flash.

+ + + +
ApplicationUpdaterflash.desktop.Updatererror + Dispatched when an error occurred either during initialization + or during the update process (if something unexpected happens).flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + Dispatched when an error occurred either during initialization + or during the update process (if something unexpected happens). + + progress + Dispatched as the update file is downloaded.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched as the update file is downloaded. + + fileUpdateError + Dispatched when an error occurs validating the file passed + as the airFile parameter in a call to the installFromAIRFile() method.air.update.events.StatusFileUpdateErrorEvent.FILE_UPDATE_ERRORair.update.events.StatusFileUpdateErrorEvent + Dispatched when an error occurs validating the file passed + as the airFile parameter in a call to the installFromAIRFile() method. + + fileUpdateStatus + + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method.air.update.events.StatusFileUpdateEvent.FILE_UPDATE_STATUSair.update.events.StatusFileUpdateEvent + + Dispatched after the updater successfully validates the + file in the call to the installFromAIRFile() method. + + + downloadError + Dispatched if there is an error while connecting or downloading + the update file.air.update.events.DownloadErrorEvent.DOWNLOAD_ERRORair.update.events.DownloadErrorEvent + Dispatched if there is an error while connecting or downloading + the update file. It is also dispatched for invalid HTTP statuses + (such as 404 - File not found). + +

When this event is dispatched the periodic timer is automatically + restarted (if the delay is greater than 0).

+ + +
updateError + + Dispatched if an error occurs while trying to download or parse the update descriptor file.air.update.events.StatusUpdateErrorEvent.UPDATE_ERRORair.update.events.StatusUpdateErrorEvent + + Dispatched if an error occurs while trying to download or parse the update descriptor file. + +

When the updater dispatches this event, the periodic timer + is automatically restarted (if the delay setting is greater than + 0). The application should consider hiding any error dialog boxes + when the updater dispatches a new checkForUpdate event.

+ +
updateStatus + + Dispatched after the updater successfully downloads and + interprets the update descriptor file.air.update.events.StatusUpdateEvent.UPDATE_STATUSair.update.events.StatusUpdateEvent + + Dispatched after the updater successfully downloads and + interprets the update descriptor file. + + beforeInstall + Dispatched just before installing the update, after the installUpdate() method + was called.air.update.events.UpdateEvent.BEFORE_INSTALLair.update.events.UpdateEvent + Dispatched just before installing the update, after the installUpdate() method + was called. Sometimes, it is useful to prevent the installation + of the update at this time, because the user could lose all current work when + the runtime exits the application to install the update. + +

Calling this event's preventDefault() method + postpones the installation until the next restart. If you call + the preventDefault() method, no additional update + process can be started during this application session (via a call + to the installUpdate() method or because of the periodic check).

+ +
downloadComplete + + Dispatched when the download of the update file is complete.air.update.events.UpdateEvent.DOWNLOAD_COMPLETEair.update.events.UpdateEvent + + Dispatched when the download of the update file is complete. + + downloadStart + + Dispatched after a call to the downloadUpdate() method + and the connection to the server is established.air.update.events.UpdateEvent.DOWNLOAD_STARTair.update.events.UpdateEvent + + Dispatched after a call to the downloadUpdate() method + and the connection to the server is established. When using ApplicationUpdater + library, you may want the event handler for this event to display + a progress bar to report the download progress to the user. + + checkForUpdate + Dispatched before the update process begins, just before the + updater tries to download the update descriptor file.air.update.events.UpdateEvent.CHECK_FOR_UPDATEair.update.events.UpdateEvent + Dispatched before the update process begins, just before the + updater tries to download the update descriptor file. + The updater can dispatch this event as a result of directly + calling the checkNow() method or because the periodic + check timer expired. + + initialized + + Dispatched after the initialization is complete.air.update.events.UpdateEvent.INITIALIZEDair.update.events.UpdateEvent + + Dispatched after the initialization is complete. + +

This event has the following read-only properties:

+
  • +

    isFirstRun (Boolean) true if + this is the first run after a successful update; false otherwise.

    +
  • +

    previousVersion (String) The previous version + of the application before the upgrade (set only if isfirstRun is true).

    +
  • +

    currentVersion (String) The version from + the application descriptor file of the currently installed version.

    +
+ +
ApplicationUpdaterUI + The constructor function. + The constructor function. + + addResources + Dynamically adds a new resource bundle for the specified language.langStringThe language code (such as "ro" for Romanian). + + resObjectThe object contains the keys and values for the translation. The keys are the ones from + the language property file. The following table lists the possible keys (property names). + +

+ Key English value Dialog Box Description appWidth 530 All Width of the dialog box. titleWindow Updating: All Displayed in the native window title bar before + the application name. titleCheck Check for updates Check For Updates Dialog box title. msgCheck Allow the application to check for updates? Check For Updates Dialog box message. btnCheck Check for Updates Check For Updates Check for Updates button label. btnCancel Cancel All dialog boxes with a Cancel button Cancel button label. titleCheckNoUpdates No updates available CheckForUpdates - No updates available Dialog box title. msgCheckNoUpdates There are no updates available for the application. Check For Updates - No updates available Dialog box message. btnClose Close All dialog boxes with Close button Close button label. titleCheckError Update error Check For Updates - Connection Error Dialog box title. msgCheckError There was an error checking for updates. + Error# {0} Check For Updates - Connection Error Dialog box message. {0} will be replaced + with the error ID. titleUpdate Update available Update Available Dialog box title. msgUpdate An updated version of the application is + available for download. Update Available Dialog box message. lblApplication Application: Update Available Label displayed before the application name. lblInstalledVersion Installed Version: Update Available Label displayed before the installed version. lblAvailableVersion Update Version: Update Available Label displayed before the update version. btnDownload Download now Update Available Download Now button label. btnDownloadLater Download later Update Available Download Later button label. lnkReleaseNotes Release notes All with release notes link The "Release notes" link name. titleProgress Download progress... Download Progress Dialog box title. msgProgress Downloading update Download Progress Dialog box message. titleDownloadError Download failed Download Error Dialog box title. msgDownloadError There was an error downloading the update. + Error# {0} Download Error Dialog box message. {0} + will be replaced with the error ID. titleInstall Install update Install Update Dialog box title. msgInstall The update for the application is downloaded + and ready to be installed. Install Update Dialog box message. btnInstall Install now Install Update "Install" button label btnInstallLater Postpone until restart Install Update "Postpone until restart" button label titleFileUpdate Update available File - Update Available Dialog box title. msgFileUpdate The file contains an updated version of + the application. Install? File - Update Available Dialog box message. lblFile File: File - Update Available Label displayed before the file name titleFileNoUpdate No update available File - No updates available Dialog box title. msgFileNoUpdate The file doesn't contain a newer version + of the application. File - No updates available Dialog box message. titleFileError File error File - Error Dialog box title. msgFileError An error occurred validating the update + file. Error# {0} File - Error Dialog box message. {0} + will be replaced with the error ID. titleUnexpectedError Unexpected error Unexpected Error Dialog box title. msgUnexpectedError An unexpected error occurred. Error# {0} Unexpected Error Dialog box message. {0} + will be replaced with the error ID. + +

+ +
+ Dynamically adds a new resource bundle for the specified language. + JavaScript developers use this method to dynamically add a new language for the + dialog boxes that the application updater UI displays. (Flex developers + can directly add a new language to the "ApplicationUpdaterDialogs" + resource bundle.) + +
localeChain
cancelUpdate + Cancels the update process. + Cancels the update process. Calling this method cancels any + pending downloads, deleting any incomplete downloaded files, and + restarts the periodic check timer. + +

The update process can be canceled at any time except when the state + machine is in "uninitialized" or "initializing" state. It does nothing + when it is called in one of the "uninitialized" or "initializing" + states.

+ +
checkNow + Starts the update process. + Starts the update process. Calling + this method does not stop the periodic timer; however, the method detects + that an update process is running and will skip the current iteration. + +

This method only executes if the current state is "Ready".

+ +

This method can result in the updater object dispatching the following event:

+ +
checkForUpdateair.update.events:UpdateEventDispatched just before the update process begins. + + Dispatched just before the update process begins.
initialize + Initializes the updater. + Initializes the updater. Calling this method + does the following: + +

  1. +

    It initializes the update framework, + silently (and synchronously) installing any pending updates. You + should call this method during application startup, since it may + restart the application.

    +
  2. + +

    It checks if there is a postponed update and installs it.

    +
  3. +

    If something went wrong with a prior update, it clears the + update file and version information from the storage area.

    +
  4. +

    If the periodic timer delay has expired, it starts the update process; otherwise + it starts the periodic timer. However, when testing an application using + the AIR Debug Launcher (ADL) application, attempting to update the + application results in a IllegalOperationError exception.

    +

+ +
initializedair.update.events:UpdateEventThe initialization is complete. + + The initialization is complete.errorflash.events:ErrorEventThere is an error during initialization. + + There is an error during initialization.
installFromAIRFile + Starts the update process using a local AIR file.fileflash.filesystem:FileThe local AIR file to install. + + + Starts the update process using a local AIR file. + +

Calling this + method has no effect if an update process is running (if the state + is not "Downloaded").

+ +

This function is useful + for an application that has the customUpdateUI element + set to true in the application descriptor file.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, + calling this method results in an IllegalOperationError exception.

+ +
fileUpdateStatusair.update.events:StatusFileUpdateEventDispatched after the updater successfully + validates the AIR file. + + Dispatched after the updater successfully + validates the AIR file.updateErrorair.update.events:StatusFileUpdateErrorEventDispatched if an error occurs while trying + parse the update descriptor file. + + Dispatched if an error occurs while trying + parse the update descriptor file.
configurationFile + The location of the configuration file that sets the values for delay and + updateURL properties.flash.filesystem:File + The location of the configuration file that sets the values for delay and + updateURL properties. It also has settings for determining whether the application + displays various confirmation dialog boxes during the update process. + If this property points to a non-existent file, calling the initialize() method + results in an Error being thrown. + +

Here is a sample configuration file:

+ + <?xml version="1.0" encoding="utf-8"?> + <configuration xmlns="http://ns.adobe.com/air/framework/update/configuration/1.0" > + <url>app:/server/update.xml</url> + <delay>1</delay> + <defaultUI> + <dialog name="checkForUpdate" visible="true" /> + <dialog name="downloadUpdate" visible="false" /> + <dialog name="downloadProgress" visible="true" /> + <dialog name="installUpdate" visible="true" /> + </defaultUI> + </configuration> + +

Instead of loading a configuration file, you can use ActionScript + code to set the following properties of the ApplicationUpdaterUI + object: delay, isCheckForUpdateVisible, isDownloadProgressVisible, + isDownloadUpdateVisible, isFileUpdateVisible, isInstallUpdateVisible, + and updateURL properties.

+ +
delayupdateURL
currentVersion + The current version of the application.String + The current version of the application. This property is set during + a call to the initialize() method. It is set to + the version from the application descriptor file. + + delay + The interval, in days, between periodic checks of new updates.Number0 + + + The interval, in days, between periodic checks of new updates. + +

A value of 0 (the default value) indicates + that the timer is not active, so no periodic check is done. The delay + can be set either via this property or via the configuration file. + When the value is set using both methods, the value set using this + property is used.

+ +
configurationFile
isCheckForUpdateVisible + Enables the visibility of the Check for + Update, No Update, and Update Error dialog boxes.Boolean + Enables the visibility of the Check for + Update, No Update, and Update Error dialog boxes. When set to true, + the updater displays these dialog boxes as part of the + update process. This can also be set in the update configuration + file. A value set using this property overrides the setting in the + update configuration file. + + isDownloadProgressVisible + + Enables the visibility of the Download Update + dialog box.Boolean + + Enables the visibility of the Download Update + dialog box. When set to true, the updater + displays this dialog box as part of the update process. This can + also be set in the update configuration file. A value set using + this property overrides the setting in the update configuration file. + + isDownloadUpdateVisible + Enables the visibility of the Download Update + dialog box.Boolean + Enables the visibility of the Download Update + dialog box. When set to true, the updater + displays these dialog boxes as part of the update process. This + can also be set in the update configuration file. A value set using + this property overrides the setting in the update configuration file. + + isFileUpdateVisible + + Enables the visibility of the File Update, + File No Update, and File Error dialog boxes.Boolean + + Enables the visibility of the File Update, + File No Update, and File Error dialog boxes. When set to true, + the updater displays these dialog boxes as part of the + update process. This can also be set in the update configuration + file. A value set using this property overrides the setting in the + update configuration file. + + isFirstRun + Whether this is the first run after a successful update (true) or not + (false).Boolean + Whether this is the first run after a successful update (true) or not + (false). The updater sets this value during the call to the initialize() + method. The developer should check that isFirstRun is set to true if + there is a need to migrate data from one version to another. + + wasPendingUpdateisInstallUpdateVisible + Enables the visibility of the Install Update + dialog box.Boolean + Enables the visibility of the Install Update + dialog box. When set to true, the updater + displays this dialog box as part of the update process. This can + also be set in the update configuration file. A value set using + this property overrides the setting in the update configuration file. + + isNewerVersionFunction + A function that the updater should use to perform version comparisons.Function + A function that the updater should use to perform version comparisons. + By default, the update framework does a + version comparison to detect whether the version from the + remote site is newer than the version of the installed application. + However, sometimes the default comparison does not match the developer's + versioning scheme. Set this property to provide a new function that + does the comparison. + +

The default comparision function accepts + versions like x.y.z, where x, y, and z can contain letters + and digits. There are some special conditions that the default comparision function + recognizes. If the test function finds "alpha", "beta", + or "rc" in the version strings, + the order is alpha < beta < rc.

+ +
The following code defines a custom function, customFn, for the appUpdate updater object. + The example function is intentionally simple. Your custom function should return a Boolean value based on the rules of your + versioning scheme. + +appUpdate.isNewerVersionFunction = customFn; + +function customFn (currentVersion:String, updateVersion:String):Boolean +{ + return updateVersion > currentVersion; +} +
isUnexpectedErrorVisible + Enables the visibility of the Unexpected + Error dialog box.Boolean + Enables the visibility of the Unexpected + Error dialog box. When set to true, the Application + Updater displays this dialog box as part of the update process. + This can also be set in the update configuration file. A value set + using this property overrides the setting in the update configuration + file. + + isUpdateInProgress + A Boolean property, which is true if + an update is running, false otherwise.Boolean + A Boolean property, which is true if + an update is running, false otherwise. + + localeChain + An array defining the locale chain used + by the user interface.Array + An array defining the locale chain used + by the user interface. Typically, only JavaScript (HTML) developers + use this property. + +

Flex developers can use the ResourceManager to handle the locale chain.

+ +

By default, in an HTML-based application, the languages are sorted between those languages in + the Capabilities.languages array and the ten languages supported by the + user interface. If no match is found, the user interface uses the English language.

+ +

This JavaScript example uses the AIR HTML localization framework, included in the AIR SDK. It sorts + the languages against the list of languages, and then it sets English as the default fallback language:

+ + appUpdater.addResources("ro_RO", {titleCheck: "Titlu", msgCheck: "Mesaj", btnCheck: "Buton"}); + appUpdater.addResources("hu", {titleCheck: "Cím", msgCheck: "Üzenet"}); + var languages = ["ro", "hu"]; + languages = languages.concat(air.Capabilities.languages); + var sortedLanguages = air.Localizer.sortLanguagesByPreference(languages, air.Capabilities.language, "en-US"); + sortedLanguages.push("en-US"); + appUpdater.localeChain = sortedLanguages; + +
addResources()
previousApplicationStorageDirectory + The previous location of the application storage directory, if it changed + after an update.flash.filesystem:File + The previous location of the application storage directory, if it changed + after an update. The application storage directory location changes after + an upgrade with a certificate migration. If there is no certificate + migration, the application storage directory does not change when the + user updates the application. and this property is set to null. + This property is set during a call to the initialize() method. + +

A developer can sign new version of AIR application with a new certificate + if the developer uses the -migrate option when packaging the AIR + file with ADT. If a new version of an AIR application uses a new signing certificate, + the local storage directory of the application changes when the user installs + the new version. Use this property to transfer data from the old application + storage directory to the new application storage directory + (File.applicationStorageDirectory). For more information, + see "Signing an AIR file to change the application certificate" in the + "Creating an AIR application using the command line tools" chapter of the + Adobe AIR developer's guide.

+ +
previousVersion + The previous version of the application.String + The previous version of the application. This property is set during + a call to the initialize() method. Returns the previous version of + the application before the upgrade (set only if isfirstRun is true); + otherwise it is set to null. + + updateDescriptor + The content of the update descriptor file downloaded from the update URL.XML + The content of the update descriptor file downloaded from the update URL. This property is + non-null only after the updater object dispatches an updateStatus event. + + updateURL + The location of the update descriptor file.String + The location of the update descriptor file. Any location + valid for a URLRequest path is accepted. This is the only mandatory + setting required by the updater. You can set the update URL either via this + property or via the configuration file. When the value is set using + both methods, the updater uses the value set using this property. + + configurationFilewasPendingUpdate + Whether there was a postponed update, even if it failed + to install (true); false otherwise.Boolean + Whether there was a postponed update, even if it failed + to install (true); false otherwise. + The updater sets this property during a call to the initialize() method. + Use the wasPendingUpdate and isFirstRun properties + to check if an update failed to install (in which case wasPendingUpdate + is set to true and isFirstRun is set to false). + + isFirstRun
\ No newline at end of file diff --git a/language-server/playerglobal_docs/authoring.xml b/language-server/playerglobal_docs/authoring.xml new file mode 100644 index 0000000..5866485 --- /dev/null +++ b/language-server/playerglobal_docs/authoring.xml @@ -0,0 +1,20 @@ + + +authoringauthExternalShapeflash.display:DisplayObjectauthExternalShapekeyuintClearFlagflaguintSetBoundsboundsflash.geom:RectangleSetFlagflaguintDatauint \ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.accessibility.xml b/language-server/playerglobal_docs/flash.accessibility.xml new file mode 100644 index 0000000..a626f73 --- /dev/null +++ b/language-server/playerglobal_docs/flash.accessibility.xml @@ -0,0 +1,1140 @@ +flash.accessibilityISimpleTextSelection + + + The ISimpleTextSelection class can be used to add support for + the MSAA ISimpleTextSelection interface to an AccessibilityImplementation. + + The ISimpleTextSelection class can be used to add support for + the MSAA ISimpleTextSelection interface to an AccessibilityImplementation. + +

If an AccessibilityImplementation subclass implements the two getters in this class, + a screen reader such as JAWS can determine the text selection range by calling them. + The AccessibilityImplementation subclass does not have to formally declare that it implements + this interface; you can simply declare getters for these two properties, as follows:

+ + + class TextAreaAccImpl extends AccesibilityImplementation + { + ... + public function get selectionAnchorIndex():int + { + ... + } + public function get selectionActiveIndex():int + { + ... + } + } + +
flash.accessibility.AccessibilityImplementationselectionActiveIndex + The zero-based character index value of the last character in the current selection.int + The zero-based character index value of the last character in the current selection. + If you want a component to support inline IME or accessibility, override this method. + + selectionAnchorIndex + The zero-based character index value of the first character in the current selection.int + The zero-based character index value of the first character in the current selection. + If you want a component to support inline IME or accessibility, override this method. + +
AccessibilityImplementation + + The AccessibilityImplementation class is the base class in Flash Player + that allows for the implementation of accessibility in components.Object + + The AccessibilityImplementation class is the base class in Flash Player + that allows for the implementation of accessibility in components. + This class enables communication between a component and a screen reader. + Screen readers are used to translate screen content into synthesized speech + or braille for visually impaired users. + +

The AccessibilityImplementation class provides a set of methods that allow a component + developer to make information about system roles, object based events, and states available + to assistive technology.

+ +

Adobe Flash Player uses Microsoft Active Accessibility (MSAA), which provides a descriptive + and standardized way for applications and screen readers to communicate. For more information + on how the Flash Player works with MSAA, see the accessibility chapter in Using Flex SDK.

+ +

The methods of the AccessibilityImplementation class are a subset of the + IAccessible interface + for a component instance.

+ +

The way that an AccessibilityImplementation implements the IAccessible interface, + and the events that it sends, depend on the kind of component being implemented.

+ +

Do not directly instantiate AccessibilityImplementation by calling its constructor. + Instead, create new accessibility implementations by extending the + AccImpl class for each new component. + In Flash, see the fl.accessibility package. + In Flex, see the mx.accessibility package and + the accessibility chapter in Using Flex SDK.

+

Note: The AccessibilityImplementation class is not supported in AIR runtime versions before AIR 2. The class is + available for compilation in AIR versions before AIR 2, but is not supported in the runtime until AIR 2.

+ +
AccessibilityImplementation + Static constructor. + Static constructor. Do not directly instantiate AccessibilityImplementation by calling its constructor. + Instead, create new accessibility implementations by extending the mx.accessibility.AccImpl + class for each new component. + + mx.accessibility.AccImplaccDoDefaultAction + An IAccessible method that performs the default action associated with the component + that this AccessibilityImplementation represents or of one of its child elements.childIDuintAn unsigned integer corresponding to one of the component's child elements, + as defined by getChildIDArray(). + + Performs the default action associated with the component. + + An IAccessible method that performs the default action associated with the component + that this AccessibilityImplementation represents or of one of its child elements. + +

Implement this method only if the AccessibilityImplementation represents a UI element + that has a default action in the MSAA model.

+ +

If you are implementing accDoDefaultAction() only for the AccessibilityImplementation + itself, or only for its child elements, you will need in some cases to indicate that there + is no default action for the particular childID that was passed. + Do this by setting the errno property to E_MEMBERNOTFOUND.

+ +
Following is an example showing how this method is implemented to perform + the appropriate default action in + the Flex mx.accessibility.ListBaseAccImpl class, the ListBase Accessibility Implementation. + For the ListBase and classes that inherit from it, + performing the default action "Double Click" for one of its child list item elements + selects that element. + + override public function accDoDefaultAction(childID:uint):void + { + if (childID > 0) + ListBase(master).selectedIndex = childID - 1; + } +
accLocation + MSAA method for returning a DisplayObject or Rectangle + specifying the bounding box of a child element in the AccessibilityImplementation.DisplayObject or Rectangle specifying the bounding box + of the child element specified by childID parameter. + + + childIDuintAn unsigned integer corresponding to one of the component's child elements + as defined by getChildIDArray(). + + Returns a DisplayObject or Rectangle object that specifies the bounding box of a child element. + + MSAA method for returning a DisplayObject or Rectangle + specifying the bounding box of a child element in the AccessibilityImplementation. + +

This method is never called with a childID of zero. + If your AccessibilityImplementation will never contain child elements, you should not implement + this method. If your AccessibilityImplementation can contain child elements, + this method is mandatory.

+ +

You can usually satisfy the requirements of this method by returning an + object that represents the child element itself. This works as long as the + child element is a DisplayObject. + In these cases, simply return the DisplayObject that corresponds to + the instance name associated with the relevant visual object in display list.

+ +

If a child element does not qualify for the technique described above, + you may do the bounding-box math yourself and return a Rectangle with: + x, y, width, and height properties. + The x and y members specify the upper-left corner of the bounding box, and + the width and height members specify its size. All four members + should be in units of Stage pixels, and relative to the origin of the component + that the AccessibilityImplementation represents. The x and y properties may have + negative values, since the origin of a DisplayObject is not necessarily in its + upper-left corner.

+ +

If the child element specified by childID is not visible (that is, get_accState + for that child would return a value including STATE_SYSTEM_INVISIBLE), you + may return null from accLocation. You can also + return a Rectangle representing the coordinates where the child element would + appear if it were visible.

+ +
The following example shows how this method is implemented to return the location + of a given child element in + the Flex mx.accessibility.ListBaseAccImpl class, the ListBase accessibility implementation. + + override public function accLocation(childID:uint):* + + { + var listBase:ListBase = ListBase(master); + + var index:uint = childID - 1; + + if (index &lt; listBase.verticalScrollPosition || + index &gt;= listBase.verticalScrollPosition + listBase.rowCount) + { + return null; + } + var item:Object = getItemAt(index); + + return listBase.itemToItemRenderer(item); + } + +
flash.display.DisplayObjectflash.geom.RectanglegetChildIDArray()Microsoft Accessibility Developer Center: IAccessible::accLocation
accSelect + IAccessible method for altering the selection in the component + that this AccessibilityImplementation represents.operationuintA bitfield consisting of one or more selection flag constants to indicate + how the item is selected or takes focus. + childIDuintAn unsigned integer corresponding to one of the component's child elements + as defined by getChildIDArray(). + + + IAccessible method for altering the selection in the component + that this AccessibilityImplementation represents. + +

The childID parameter will always be nonzero. This method + always applies to a child element rather than the overall component; + Flash Player manages the selection of the overall component itself.

+ +

The selFlag parameter is a bitfield consisting of one or more selection flag constants + that allows an MSAA client to indicate how the item referenced by the childID + should be selected or take focus. What follows are descriptions of the selection flag constants + and what they communicate to the accessibility implementation. + As a practical matter, most implementations of this method in accessibility implementations + that inherit from the Flex mx.accessibility.ListBaseAccImpl class + ignore the selFlag constant and instead rely on the component's keyboard selection behavior + to handle multi-selection.

+ +

The selFlag parameter may or may not contain the SELFLAG_TAKEFOCUS + flag. If it does, you should set the child focus to the specified childID, + and, unless SELFLAG_EXTENDSELECTION is also present, make that child element + the selection anchor. Otherwise, the child focus and selection anchor should + remain unmodified, despite the fact that additional flags described below + may modify the selection.

+ +

The selFlag argument will always contain one of the following four + flags, which indicate what kind of selection modification is desired:

+
  • SELFLAG_TAKESELECTION: Clear any existing selection, and set the selection + to the specified childID.

    +
  • SELFLAG_EXTENDSELECTION: Calculate the range of child elements between + and including the selection anchor and the specified childID. If + SELFLAG_ADDSELECTION is present, add all of these child elements to the + selection. If SELFLAG_REMOVESELECTION is present, remove all of these child + elements from the selection. If neither SELFLAG_ADDSELECTION nor SELFLAG_REMOVESELECTION + is present, all of these child elements should take on the selection anchor's + selection state: if the selection anchor is selected, add these child elements + to the selection; otherwise remove them from the selection.

    +
  • SELFLAG_ADDSELECTION (without SELFLAG_EXTENDSELECTION): Add the specified + childID to the selection.

    +
  • SELFLAG_REMOVESELECTION (without SELFLAG_EXTENDSELECTION): Remove the + specified childID from the selection.

+ +

Note that for a non-multi-selectable component, the only valid selFlag + parameter values are SELFLAG_TAKEFOCUS and SELFLAG_TAKESELECTION. + You could in theory + also choose to support SELFLAG_REMOVESELECTION for a non-multi-selectable + component that allowed the user to force a null selection, but in practice + most non-multi-selectable components do not work this way, and MSAA clients + may not attempt this type of operation.

+ +

If you encounter flags that seem invalid, set errno to E_INVALIDARG.

+

Finally, note that when accSelect is called, Flash Player + ensures that it has host focus (the window focus of its container + application), and that your component has focus within Flash Player.

+ +
The following example shows how this method is implemented to select a child + item in the Flex mx.accessibility.ListBaseAccImpl class, the ListBase accessibility implementation. + override public function accSelect(selFlag:uint, childID:uint):void + { + + var listBase:ListBase = ListBase(master); + + var index:uint = childID - 1; + + if (index &gt;= 0 && index &lt; listBase.dataProvider.length) + listBase.selectedIndex = index; + } + + +
getChildIDArray()Microsoft Accessibility Developer Center: IAccessible::accSelect
getChildIDArray + Returns an array containing the unsigned integer IDs of all child elements + in the AccessibilityImplementation.Array containing the unsigned integer IDs of all child elements in the AccessibilityImplementation. + + Array + Returns an array containing the unsigned integer IDs of all child elements + in the AccessibilityImplementation. + +

The length of the array may be zero. The IDs in the array should + appear in the same logical order as the child elements they represent. If your + AccessibilityImplementation can contain child elements, this method is mandatory; otherwise, do + not implement it.

+ +

In assigning child IDs to your child elements, use any scheme that + preserves uniqueness within each instance of your AccessibilityImplementation. Child IDs need not + be contiguous, and their ordering need not match the logical ordering of the + child elements. You should arrange so as to not reuse child IDs; if a child + element is deleted, its ID should never be used again for the lifetime of + that AccessibilityImplementation instance. Be aware that, due to implementation choices in the Flash + player code, undesirable behavior can result if you use child IDs that exceed + one million.

+ +
The following example shows how this method is implemented to return an array + of childIDs in the Flex mx.accessibility.ListBaseAccImpl class, + the ListBase Accessibility Implementation. + + + override public function getChildIDArray():Array + { + var childIDs:Array = []; + + if (ListBase(master).dataProvider) + { + var n:uint = ListBase(master).dataProvider.length; + for (var i:int = 0; i &lt; n; i++) + { + childIDs[i] = i + 1; + } + } + return childIDs; + } + + +
get_accDefaultAction + MSAA method for returning the default action of the component + that this AccessibilityImplementation represents or of one of its child elements.The default action string specified in the MSAA model for the AccessibilityImplementation + or for one of its child elements. + StringchildIDuintAn unsigned integer corresponding to one of the component's child elements, + as defined by getChildIDArray(). + + Returns the default action of the component. + + MSAA method for returning the default action of the component + that this AccessibilityImplementation represents or of one of its child elements. + +

Implement this method only if the AccessibilityImplementation represents a UI element + that has a default action in the MSAA model; be sure to return the exact string + that the MSAA model specifies. + For example, the default action string for a Button component is "Press."

+ +

If you are implementing get_accDefaultAction only for the + AccessibilityImplementation itself, or only for its child elements, + you will need in some cases to indicate that there is no default action + for the particular childID that was passed. + Do this by simply returning null.

+ +
The following example shows how this method is implemented to return + the appropriate default actions in the Flex mx.accessibility.ListBaseAccImpl class, + the ListBase accessibility implementation. + override public function get_accDefaultAction(childID:uint):String + { + if (childID == 0) + return null; + + return "Double Click"; + } + +
getChildIDArray()Microsoft Accessibility Developer Center: IAccessible::get_accDefaultAction
get_accFocus + MSAA method for returning the unsigned integer ID of the child element, if any, + that has child focus within the component.The unsigned integer ID of the child element, if any, that has child focus within the component. + uintReturns the unsigned integer ID of the child element that has child focus within the component. + + MSAA method for returning the unsigned integer ID of the child element, if any, + that has child focus within the component. If no child has child focus, the method returns zero. + + The following example shows how this method is implemented to return the focused childID in + the Flex mx.accessibility.ListBaseAccImpl class, the ListBase accessibility implementation. + + override public function get_accFocus():uint + { + var index:uint = ListBase(master).selectedIndex; + + return index >= 0 ? index + 1 : 0; + } + + getChildIDArray()Microsoft Accessibility Developer Center: IAccessible::get_accFocusget_accName + MSAA method for returning the name for the component + that this AccessibilityImplementation represents or for one of its child elements.Name of the component or one of its child elements. + + StringchildIDuintAn unsigned integer corresponding to one of the component's child elements + as defined by getChildIDArray(). + + Returns the name of the component + + MSAA method for returning the name for the component + that this AccessibilityImplementation represents or for one of its child elements. + +

In the case of the AccessibilityImplementation itself (childID == 0), + if this method is not implemented, or does not return a value, Flash Player + uses the AccessibilityProperties.name property value, if it is present.

+ +

For AccessibilityImplementations that can have child elements, this method must be implemented, + and must return a string value when childID is nonzero.

+ +

Depending on the type of user interface element, names in MSAA mean one of two different + things: an author-assigned name, or the actual text content of the element. + Usually, an AccessibilityImplementation itself will fall into the former category. + Its name property is an author-assigned name. Child elements + always fall into the second category. Their names indicate their text content.

+ +

When the name property of an AccessibilityImplementation has the meaning + of an author-assigned name, there are two ways in which components can acquire names from authors. + The first entails names present within the component itself; for example, a checkbox + component might include a text label that serves as its name. The second—a fallback from + the first—entails names specified in the UI and ending + up in AccessibilityProperties.name. This fallback option allows users to specify + names just as they would for any other Sprite or MovieClip.

+ +

This leaves three possibilities for the AccessibilityImplementation itself (childID == zero):

+
  • Author-assigned name within component. The get_accName method + should be implemented and should return a string value that contains the + AccessibilityImplementation's name when childID is zero. If childID is zero but the + AccessibilityImplementation has no name, get_accName should return an empty string to prevent + the player from falling back to the AccessibilityProperties.name property.

    +
  • Author-assigned name from UI. If the AccessibilityImplementation can have child + elements, the get_accName method should be implemented but should not return a value when + childID is zero. If the AccessibilityImplementation will never have child elements, + get_accName should not be implemented.

    +
  • Name signifying content. The get_accName method should be + implemented and should return an appropriate string value when childID + is zero. If childId is zero but the AccessibilityImplementation has no content, + get_accName should return an empty string to prevent the player from falling back to + the AccessibilityProperties.name property.

    +
+

Note that for child elements (if the AccessibilityImplementation can have them), the third case + always applies. The get_accName method should be implemented and should + return an appropriate string value when childID is nonzero.

+ +
The following example shows how this method is implemented in + the Flex mx.accessibility.AccImpl class, + the base accessibility implementation in Flex. + override public function get_accName(childID:uint):String + { + // Start with the name of the component's parent form + // if the component is contained within a form + var accName:String = UIComponentAccImpl.getFormName(master); + + // If the element requested is the component itself, + // append the value of any assigned accessibilityProperties.name + if (childID == 0 && master.accessibilityProperties + && master.accessibilityProperties.name + && master.accessibilityProperties.name != "") + accName += master.accessibilityProperties.name + " "; + + // Append the value of the childIDs name + // returned by the component-specific override + // of the mx.accessibility.AccImpl.getName() utility function, + // and append the component's status returned by the + // component-specific override of the + // mx.accessibility.AccImpl.getStatusName() utility function + accName += getName(childID) + getStatusName(); + + // Return the assembled String if it is neither empty nor null, + // otherwise return null + return (accName != null && accName != "") ? accName : null; + } + + +
getChildIDArray()flash.accessibility.AccessibilityPropertiesflash.accessibility.AccessibilityProperties.namemx.accessibility.AccImpl.get_accName()mx.accessibility.AccImpl.getName()mx.accessibility.AccImpl.getStatusName()Microsoft Accessibility Developer Center: IAccessible::get_accName
get_accRole + MSAA method for returning the system role for the component + that this AccessibilityImplementation represents or for one of its child elements.Error code 2143, AccessibilityImplementation.get_accRole() must be overridden from its default. + ErrorErrorSystem role associated with the component. + + uintchildIDuintAn unsigned integer corresponding to one of the component's + child elements as defined by getChildIDArray(). + + Returns the system role for the component + + + + MSAA method for returning the system role for the component + that this AccessibilityImplementation represents or for one of its child elements. + System roles are predefined for all the components in MSAA. + + getChildIDArray()AccessibilityImplementation Constants: Object Role ConstantsMicrosoft Accessibility Developer Center: IAccessible::get_accRoleget_accSelection + MSAA method for returning an array containing the IDs of all child elements that are selected.An array of the IDs of all child elements that are selected. + + ArrayReturns an array containing the IDs of all selected child elements. + + MSAA method for returning an array containing the IDs of all child elements that are selected. + The returned array may contain zero, one, or more IDs, all unsigned integers. + + The following example shows how this method is implemented to return the selected childIDs in + the Flex mx.accessibility.ListBaseAccImpl class, the ListBase accessibility implementation. + + + override public function get_accSelection():Array + { + var accSelection:Array = []; + + var selectedIndices:Array = ListBase(master).selectedIndices; + + var n:int = selectedIndices.length; + for (var i:int = 0; i &lt; n; i++) + { + accSelection[i] = selectedIndices[i] + 1; + } + + return accSelection; + } + + + getChildIDArray()Microsoft Accessibility Developer Center: IAccessible::get_accSelectionget_accState + IAccessible method for returning the current runtime state of the component that this + AccessibilityImplementation represents or of one of its child elements.Error code 2144, AccessibilityImplementation.get_accState() must be overridden from its default. + ErrorErrorA combination of zero, one, or more of the system state constants. + Multiple constants are assembled into a bitfield using |, the bitwise OR operator. + + + uintchildIDuintAn unsigned integer corresponding to one of the component's child elements + as defined by getChildIDArray(). + + Returns the state of the component + + + IAccessible method for returning the current runtime state of the component that this + AccessibilityImplementation represents or of one of its child elements. + +

This method must return a combination of zero, one, or more of the predefined + object state constants for components in MSAA. + When more than one state applies, the state constants should be combined into a bitfield + using |, the bitwise OR operator.

+ +

To indicate that none of the state constants currently applies, this method should return zero.

+ +

You should not need to track or report the STATE_SYSTEM_FOCUSABLE or STATE_SYSTEM_FOCUSED states. + Flash Player handles these states automatically.

+ +
The following example shows how this method is implemented to combine + more than one state constant in + mx.accessibility.ListBaseAccImpl, the Flex ListBase Accessibility Implementation. + + + override public function get_accState(childID:uint):uint + { + var accState:uint = getState(childID); + + if (childID &gt; 0) + { + var listBase:ListBase = ListBase(master); + + var index:uint = childID - 1; + + // For returning states (OffScreen and Invisible) + // when the list Item is not in the displayed rows. + if (index &lt; listBase.verticalScrollPosition || + index &gt;= listBase.verticalScrollPosition + listBase.rowCount) + { + accState |= (STATE_SYSTEM_OFFSCREEN | + STATE_SYSTEM_INVISIBLE); + } + else + { + accState |= STATE_SYSTEM_SELECTABLE; + + var item:Object = getItemAt(index); + + var renderer:IListItemRenderer = + listBase.itemToItemRenderer(item); + + if (renderer != null && listBase.isItemSelected(renderer.data)) + accState |= STATE_SYSTEM_SELECTED | STATE_SYSTEM_FOCUSED; + } + } + + return accState; + } + +
getChildIDArray()AccessibilityImplementation Constants: Object State ConstantsMicrosoft Accessibility Developer Center: IAccessible::get_accState
get_accValue + MSAA method for returning the runtime value of the component that this + AccessibilityImplementation represents or of one of its child elements.A string representing the runtime value of the component of of one of its child elements. + + StringchildIDuintAn unsigned integer corresponding to one of the component's child elements + as defined by getChildIDArray(). + + Returns the value of the component + + + MSAA method for returning the runtime value of the component that this + AccessibilityImplementation represents or of one of its child elements. + +

Implement this method only if your AccessibilityImplementation represents a UI element + that has a value in the MSAA model. Be aware that some UI elements that have an apparent 'value' + actually expose this value by different means, such as + get_accName (text, for example), + get_accState (check boxes, for example), or get_accSelection + (list boxes, for example).

+ +

If you are implementing get_accValue only for the AccessibilityImplementation itself, or + only for its child elements, you will need in some cases to indicate that + there is no concept of value for the particular childID that was passed. + Do this by simply returning null.

+ +
The following example shows how this method is implemented to return the appropriate value based on + the component's selectedIndex value in the Flex mx.accessibility.ListBaseAccImpl class, + the ListBase accessibility implementation. + + override public function get_accValue(childID:uint):String + { + var accValue:String; + + var listBase:ListBase = ListBase(master); + + var index:int = listBase.selectedIndex; + if (childID == 0) + { + if (index > -1) + { + var item:Object = getItemAt(index); + + if (item is String) + { + accValue = item + " " + (index + 1) + " of " + listBase.dataProvider.length; + } + else + { + accValue = listBase.itemToLabel(item) + " " + (index + 1) + + " of " + listBase.dataProvider.length; + } + } + } + + return accValue; + } + +
getChildIDArray()Microsoft Accessibility Developer Center: IAccessible::get_accValue
isLabeledBy + + Returns true or false to indicate whether a text object having + a bounding box specified by a x, y, width, and height + should be considered a label for the component that this AccessibilityImplementation represents.true or false to indicate whether a text object having the given label bounds should be considered a label for the component that this AccessibilityImplementation represents. + BooleanlabelBoundsflash.geom:RectangleA Rectangle representing the bounding box of a text object. + Indicates whether a nearby text object is a label for this component. + + + Returns true or false to indicate whether a text object having + a bounding box specified by a x, y, width, and height + should be considered a label for the component that this AccessibilityImplementation represents. + +

The x and y coordinates are relative to the upper-left corner + of the component to which the AccessibilityImplementation applies, and may be negative. All coordinates + are in units of Stage pixels.

+ +

This method allows accessible components to fit into the Flash Player's search + for automatic labeling relationships, which allow text external to an object + to supply the object's name. This method is provided because it is expected + that the criteria for recognizing labels will differ from component to component. + If you implement this method, you should aim to use geometric criteria similar + to those in use inside the player code for buttons and textfields. Those criteria + are as follows:

+ +

  • For buttons, any text falling entirely inside the button is considered a label.
  • For textfields, any text appearing nearby above and left-aligned, + or nearby to the left, is considered a label.

+ +

If the component that the AccessibilityImplementation represents should never participate in automatic + labeling relationships, do not implement isLabeledBy. This is equivalent + to always returning false. One case in which isLabeledBy should + not be implemented is when the AccessibilityImplementation falls into the "author-assigned name + within component" case described under get_accName above.

+

Note that this method is not based on any IAccessible method; it is + specific to Flash.

+ +
errno + Indicates an error code.uint + Indicates an error code. Errors are indicated out-of-band, rather than in return values. + To indicate an error, set the errno property to one of the error codes + documented in the AccessibilityImplementation Constants appendix. + This causes your return value to be ignored. The errno property + of your AccessibilityImplementation is always cleared (set to zero) by the player + before any AccessibilityImplementation method is called. + + AccessibilityImplementation Constantsstub + Used to create a component accessibility stub.Boolean + Used to create a component accessibility stub. + If a component is released without an ActionScript accessibility implementation, + Adobe recommends that you add a component accessibility stub. + This stub causes Flash Player, for accessibility purposes, to treat the component + as a simple graphic rather than exposing the internal structure of buttons, + textfields, and so on, within the component. + +

To create a component accessibility stub, + subclass the relevant AccImpl class, overriding the property stub + with a value of true.

+ +
The mx.accessibility.AccImpl class in Flex (\sdks\4.0.0\frameworks\projects\framework\src\mx\accessibility\AccImpl.as)The fl.accessibility.AccImpl class in Flash (\Local Settings\Application Data\Adobe\Flash CS5\en_US\Configuration\Classes\mx\accessibility\AccImpl.as)
AccessibilityProperties + The AccessibilityProperties class lets you control the presentation of Flash objects to accessibility + aids, such as screen readers.Object + The AccessibilityProperties class lets you control the presentation of Flash objects to accessibility + aids, such as screen readers. + +

You can attach an AccessibilityProperties object to any display object, but Flash Player will read + your AccessibilityProperties object only for certain kinds of objects: entire + SWF files (as represented by DisplayObject.root), container objects + (DisplayObjectContainer and subclasses), buttons + (SimpleButton and subclasses), and text (TextField and subclasses).

+ +

The name property of these objects is the most important property to specify because + accessibility aids provide the names of objects to users as a basic means of navigation. Do not + confuse AccessibilityProperties.name with DisplayObject.name; these are + separate and unrelated. The AccessibilityProperties.name property is a name + that is read aloud by the accessibility aids, whereas DisplayObject.name is essentially a + variable name visible only to ActionScript code.

+ +

In Flash Professional, the properties of AccessibilityProperties objects override + the corresponding settings available in the Accessibility panel during authoring.

+ +

To determine whether Flash Player is running in an environment that supports accessibility aids, use + the Capabilities.hasAccessibility property. If you modify AccessibilityProperties + objects, you need to call the Accessibility.updateProperties() method for the changes to + take effect.

+ + +
The following example uses the AccessibilityExample, + CustomAccessibleButton, CustomSimpleButton, and ButtonDisplayState classes + to create an accessibility-compliant menu that works with common screen readers. The main + functionality of the AccessibilityProperties class is as follows: + +
  1. Call configureAssets, which creates a custom button and sets its label and + description. These are the values that the screen reader conveys to the end user.
  2. Call setTimeOut() to ensure that Flash Player has enough time to detect the + screen reader before updating the properties.
+ +

Note: Call setTimeout() before checking Accessibility.active. + to give Flash Player the 2 seconds it needs to connect to a screen reader, + if one is available. If you do not provide a sufficient delay time, the setTimeout call might return false, even + if a screen reader is available.

+ +

The following example processes the Accessibility.updateProperties() + method only if the call to Accessibility.active returns true, which + occurs only if Flash Player is currently connected to an active screen reader. If updateProperties + is called without an active screen reader, it throws an IllegalOperationError exception.

+ +package { + import flash.display.Sprite; + import flash.accessibility.Accessibility; + import flash.utils.setTimeout; + + public class AccessibilityPropertiesExample extends Sprite { + public static const BUTTON_WIDTH:uint = 90; + public static const BUTTON_HEIGHT:uint = 20; + + private var gutter:uint = 5; + private var menuLabels:Array = new Array("PROJECTS", "PORTFOLIO", "CONTACT"); + private var menuDescriptions:Array = new Array("Learn more about our projects" + , "See our portfolio" + , "Get in touch with our team"); + + public function AccessibilityPropertiesExample() { + configureAssets(); + setTimeout(updateAccessibility, 2000); + } + + private function updateAccessibility():void { + trace("Accessibility.active: " + Accessibility.active); + if(Accessibility.active) { + Accessibility.updateProperties(); + } + } + + private function configureAssets():void { + var child:CustomAccessibleButton; + for(var i:uint; i < menuLabels.length; i++) { + child = new CustomAccessibleButton(); + child.y = (numChildren * (BUTTON_HEIGHT + gutter)); + child.setLabel(menuLabels[i]); + child.setDescription(menuDescriptions[i]); + addChild(child); + } + } + } + + +import flash.accessibility.AccessibilityProperties; +import flash.display.Shape; +import flash.display.SimpleButton; +import flash.display.Sprite; +import flash.events.Event; +import flash.text.TextFormat; +import flash.text.TextField; + +class CustomAccessibleButton extends Sprite { + private var button:SimpleButton; + private var label1:TextField; + private var description:String; + private var _name:String; + + public function CustomAccessibleButton(_width:uint = 0, _height:uint = 0) { + _width = (_width == 0) ? AccessibilityPropertiesExample.BUTTON_WIDTH : _width; + _height = (_height == 0) ? AccessibilityPropertiesExample.BUTTON_HEIGHT : _height; + + button = buildButton(_width, _height); + label1 = buildLabel(_width, _height); + + addEventListener(Event.ADDED, addedHandler); + } + + private function addedHandler(event:Event):void { + trace("addedHandler: " + name); + var accessProps:AccessibilityProperties = new AccessibilityProperties(); + accessProps.name = this._name; + accessProps.description = description; + accessibilityProperties = accessProps; + removeEventListener(Event.ADDED, addedHandler); + } + + private function buildButton(_width:uint, _height:uint):SimpleButton { + var child:SimpleButton = new CustomSimpleButton(_width, _height); + addChild(child); + return child; + } + + private function buildLabel(_width:uint, _height:uint):TextField { + var format:TextFormat = new TextFormat(); + format.font = "Verdana"; + format.size = 11; + format.color = 0xFFFFFF; + format.align = TextFormatAlign.CENTER; + format.bold = true; + + var child:TextField = new TextField(); + child.y = 1; + child.width = _width; + child.height = _height; + child.selectable = false; + child.defaultTextFormat = format; + child.mouseEnabled = false; + + addChild(child); + return child; + } + + public function setLabel(text:String):void { + label1.text = text; + this._name = text; + } + + public function setDescription(text:String):void { + description = text; + } +} + +class CustomSimpleButton extends SimpleButton { + private var upColor:uint = 0xFFCC00; + private var overColor:uint = 0xCCFF00; + private var downColor:uint = 0x00CCFF; + + public function CustomSimpleButton(_width:uint, _height:uint) { + downState = new ButtonDisplayState(downColor, _width, _height); + overState = new ButtonDisplayState(overColor, _width, _height); + upState = new ButtonDisplayState(upColor, _width, _height); + hitTestState = new ButtonDisplayState(upColor, _width, _height); + useHandCursor = true; + } +} + +class ButtonDisplayState extends Shape { + private var bgColor:uint; + private var _width:uint; + private var _height:uint; + + public function ButtonDisplayState(bgColor:uint, _width:uint, _height:uint) { + this.bgColor = bgColor; + this._width = _width; + this._height = _height; + draw(); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, _width, _height); + graphics.endFill(); + } +} +} +
flash.accessibility.Accessibility.updateProperties()flash.display.DisplayObject.accessibilityPropertiesflash.display.InteractiveObject.tabIndexflash.system.Capabilities.hasAccessibilityAccessibilityProperties + Creates a new AccessibilityProperties object. + Creates a new AccessibilityProperties object. + description + Provides a description for this display object in the accessible presentation.String + Provides a description for this display object in the accessible presentation. + If you have a lot of information to present about the object, it is + best to choose a concise name and put most of your content in the + description property. + Applies to whole SWF files, containers, buttons, and text. The default value + is an empty string. +

In Flash Professional, this property corresponds to the Description field in the Accessibility panel.

+
forceSimple + If true, causes Flash Player to exclude child objects within this + display object from the accessible presentation.Boolean + If true, causes Flash Player to exclude child objects within this + display object from the accessible presentation. + The default is false. Applies to whole SWF files and containers. + name + Provides a name for this display object in the accessible presentation.String + Provides a name for this display object in the accessible presentation. + Applies to whole SWF files, containers, buttons, and text. Do not confuse with + DisplayObject.name, which is unrelated. The default value + is an empty string. +

In Flash Professional, this property corresponds to the Name field in the Accessibility panel.

+
noAutoLabeling + If true, disables the Flash Player default auto-labeling system.Boolean + If true, disables the Flash Player default auto-labeling system. + Auto-labeling causes text objects inside buttons to be treated as button names, + and text objects near text fields to be treated as text field names. + The default is false. Applies only to whole SWF files. +

The noAutoLabeling property value is ignored unless you specify it before the + first time an accessibility aid examines your SWF file. If you plan to set + noAutoLabeling to true, you should do so as early as + possible in your code.

+
shortcut + Indicates a keyboard shortcut associated with this display object.String + Indicates a keyboard shortcut associated with this display object. + Supply this string only for UI controls that you have associated with a shortcut key. + Applies to containers, buttons, and text. The default value + is an empty string. + +

Note: Assigning this property does not automatically assign the specified key + combination to this object; you must do that yourself, for example, by + listening for a KeyboardEvent.

+ +

The syntax for this string uses long names for modifier keys, and + the plus(+) character to indicate key combination. Examples of valid strings are + "Ctrl+F", "Ctrl+Shift+Z", and so on.

+
silent + If true, excludes this display object from accessible presentation.Boolean + If true, excludes this display object from accessible presentation. + The default is false. Applies to whole SWF files, containers, buttons, and text. +
ISearchableText + The ISearchableText interface can be implemented by objects that + contain text which should be searchable on the web. + The ISearchableText interface can be implemented by objects that + contain text which should be searchable on the web. + + searchText + Gets the search text from a component implementing ISearchableText.String + Gets the search text from a component implementing ISearchableText. + + Accessibility + The Accessibility class manages communication with screen readers.Object + The Accessibility class manages communication with screen readers. Screen readers are a + type of assistive technology for visually impaired users that provides an audio version of + screen content. The methods of the Accessibility class are static—that is, you don't + have to create an instance of the class to use its methods. + +

Mobile Browser Support: This class is not supported in mobile browsers.

+

AIR profile support: This feature is supported on all desktop operating systems, + but is not supported on mobile devices or on AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

To get and set accessible properties for a specific object, such as a button, movie + clip, or text field, use the DisplayObject.accessibilityProperties property. + To determine whether the player or runtime is running in an environment that supports accessibility aids, use + the Capabilities.hasAccessibility property.

+ +

Note: AIR 2 supports the JAWS 11 (or higher) screen reader software. For additional information, + please see http://www.adobe.com/accessibility/.

+ +
The following example uses AccessibilityExample, + CustomAccessibleButton, CustomSimpleButton, and + ButtonDisplayState sample classes to create an accessibility-compliant + menu that works with most screen readers. The example carries out the following tasks: +
  1. It traces the Accessibility.active property to determine whether a screen + reader is currently active and the player is communicating with it.
  2. If the active property returns true, the example calls the + updateProperties() method to apply the accessibility changes made to the buttons in + this example.
  3. The example calls the flash.utils.setTimeout() method, specifying that the updateAccessibility() closure method + should be called after 2 seconds.
+ +

Note: Call setTimeout() before checking Accessibility.active + to give Flash Player the 2 seconds it needs to connect to a screen reader if one is available. + If you do not supply a sufficient delay time, the setTimeout call might return false even if a screen reader is available. +

+

The following example processes the Accessibility.updateProperties() + method only if the call to Accessibility.active returns true, which occurs + only if Flash Player is currently connected to an active screen reader. If updateProperties + is called without an active screen reader, it throws an IllegalOperationError exception.

+ +package { + import flash.display.Sprite; + import flash.accessibility.Accessibility; + import flash.utils.setTimeout; + + public class AccessibilityExample extends Sprite { + public static const BUTTON_WIDTH:uint = 90; + public static const BUTTON_HEIGHT:uint = 20; + + private var gutter:uint = 5; + private var menuLabels:Array = new Array("PROJECTS", "PORTFOLIO", "CONTACT"); + private var menuDescriptions:Array = new Array("Learn more about our projects" + , "See our portfolio" + , "Get in touch with our team"); + + public function AccessibilityExample() { + configureAssets(); + setTimeout(updateAccessibility, 2000); + } + + private function updateAccessibility():void { + trace("Accessibility.active: " + Accessibility.active); + if(Accessibility.active) { + Accessibility.updateProperties(); + } + } + + private function configureAssets():void { + var child:CustomAccessibleButton; + for(var i:uint; i < menuLabels.length; i++) { + child = new CustomAccessibleButton(); + child.y = (numChildren * (BUTTON_HEIGHT + gutter)); + child.setLabel(menuLabels[i]); + child.setDescription(menuDescriptions[i]); + addChild(child); + } + } + } +} + +import flash.accessibility.AccessibilityProperties; +import flash.display.Shape; +import flash.display.SimpleButton; +import flash.display.Sprite; +import flash.events.Event; +import flash.text.TextFormat; +import flash.text.TextField; + + +class CustomAccessibleButton extends Sprite { + private var button:SimpleButton; + private var label:TextField; + private var description:String; + private var _name:String; + + public function CustomAccessibleButton(_width:uint = 0, _height:uint = 0) { + _width = (_width == 0) ? AccessibilityExample.BUTTON_WIDTH : _width; + _height = (_height == 0) ? AccessibilityExample.BUTTON_HEIGHT : _height; + + button = buildButton(_width, _height); + label = buildLabel(_width, _height); + + addEventListener(Event.ADDED, addedHandler); + } + + private function addedHandler(event:Event):void { + trace("addedHandler: " + this._name); + var accessProps:AccessibilityProperties = new AccessibilityProperties(); + accessProps.name = this._name; + accessProps.description = description; + accessibilityProperties = accessProps; + removeEventListener(Event.ADDED, addedHandler); + } + + private function buildButton(_width:uint, _height:uint):SimpleButton { + var child:SimpleButton = new CustomSimpleButton(_width, _height); + addChild(child); + return child; + } + + private function buildLabel(_width:uint, _height:uint):TextField { + var format:TextFormat = new TextFormat(); + format.font = "Verdana"; + format.size = 11; + format.color = 0xFFFFFF; + format.align = TextFormatAlign.CENTER; + format.bold = true; + + var child:TextField = new TextField(); + child.y = 1; + child.width = _width; + child.height = _height; + child.selectable = false; + child.defaultTextFormat = format; + child.mouseEnabled = false; + + addChild(child); + return child; + } + + public function setLabel(text:String):void { + label.text = text; + this._name = text; + } + + public function setDescription(text:String):void { + description = text; + } +} + +class CustomSimpleButton extends SimpleButton { + private var upColor:uint = 0xFFCC00; + private var overColor:uint = 0xCCFF00; + private var downColor:uint = 0x00CCFF; + + public function CustomSimpleButton(_width:uint, _height:uint) { + downState = new ButtonDisplayState(downColor, _width, _height); + overState = new ButtonDisplayState(overColor, _width, _height); + upState = new ButtonDisplayState(upColor, _width, _height); + hitTestState = new ButtonDisplayState(upColor, _width, _height); + useHandCursor = true; + } +} + +class ButtonDisplayState extends Shape { + private var bgColor:uint; + private var _width:uint; + private var _height:uint; + + public function ButtonDisplayState(bgColor:uint, _width:uint, _height:uint) { + this.bgColor = bgColor; + this._width = _width; + this._height = _height; + draw(); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, _width, _height); + graphics.endFill(); + } +} +
flash.display.DisplayObject.accessibilityPropertiesflash.system.Capabilities.hasAccessibilitySockethttp://www.adobe.com/accessibility/updateProperties + Tells Flash Player to apply any accessibility changes made by using the DisplayObject.accessibilityProperties property.Accessibility is not supported in this version of + Flash Player. Do not call the Accessibility.updateProperties() method + if the flash.system.Capabilities.hasAccessibility property is false. + + IllegalOperationErrorflash.errors:IllegalOperationError + Tells Flash Player to apply any accessibility changes made by using the DisplayObject.accessibilityProperties property. + You need to call this method for your changes to take effect. + +

If you modify the accessibility properties for multiple objects, only one call to the + Accessibility.updateProperties() method is necessary; multiple calls can result in + reduced performance and erroneous screen reader output.

+ +
activeflash.display.DisplayObject.accessibilityPropertiesflash.system.Capabilities.hasAccessibility
active + Indicates whether a screen reader is active and the application is + communicating with it.Boolean + Indicates whether a screen reader is active and the application is + communicating with it. Use this method when you want your application to behave + differently in the presence of a screen reader. + +

Once this property is set to true, it remains true for the duration + of the application. (It is unusual for a user to turn off the screen reader once it is + started.)

+ +

Note: Before calling this method, wait 1 or 2 seconds after launching your + AIR application or after the first appearance of the Flash® Player window in which + your document is playing. Otherwise, you might get a return value of false + even if there is an active accessibility client. This happens because of an asynchronous + communication mechanism between accessibility clients and Flash Player or AIR.

+ + To determine whether the player is running in an environment that supports screen readers, use the + Capabilities.hasAccessibility property. + +
flash.system.Capabilities.hasAccessibilityupdateProperties()
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.data.xml b/language-server/playerglobal_docs/flash.data.xml new file mode 100644 index 0000000..3fcfcd8 --- /dev/null +++ b/language-server/playerglobal_docs/flash.data.xml @@ -0,0 +1,3051 @@ +flash.dataSQLViewSchema + + A SQLViewSchema instance provides information describing a specific view + in a database.flash.data:SQLTableSchema + A SQLViewSchema instance provides information describing a specific view + in a database. + + It contains the name of the view (the name property), the + SQL statement used to create the view (the sql property), and + information about the view's columns (the columns property). + +

To obtain view schema information for a database, use the + SQLConnection.loadSchema() method to load the schema information, making certain to + use null or SQLViewSchema for the type argument's value. + In the resulting SQLSchemaResult instance, the views property contains an array + of SQLViewSchema instances representing the views in the database.

+ +

Generally, developer code does not construct SQLViewSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()flash.data.SQLColumnSchemaSQLViewSchema + Creates a SQLViewSchema instance.databaseStringThe name of the associated database. + + nameStringThe name of the view. + + sqlStringThe SQL statement used to create the view. + + columnsArrayArray of SQLColumnSchema instances describing this view's columns. + + + Creates a SQLViewSchema instance. Generally, developer code does not call the SQLViewSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + +
SQLColumnSchema + The SQLColumnSchema class provides information describing the characteristics of a specific column + within a table in a database.Object + The SQLColumnSchema class provides information describing the characteristics of a specific column + within a table in a database. + +

To obtain column schema information for one or more tables in a database, use the + SQLConnection.loadSchema() method to load the schema information, making certain to + use true for the includeColumnSchema argument's value. In the resulting + SQLSchemaResult instance, each table and view definition includes a columns + property — an array of SQLColumnSchema instances representing the columns in the + table or view.

+ +

Generally, developer code does not construct SQLColumnSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()flash.data.SQLTableSchemaflash.data.SQLViewSchemaSQLColumnSchema + Constructs a SQLColumnSchema instance.nameStringThe name of the column. + + primaryKeyBooleanIndicates whether this column is a part of the primary + key for the associated table. + + allowNullBooleanIndicates whether this column can contain NULL values. + + autoIncrementBooleanIndicates whether this is an auto increment column. + + dataTypeStringThe declared type of the column. + + defaultCollationTypeStringThe collation sequence defined for this column. + This value corresponds to one of the constants in the SQLCollationType class: +
  • SQLCollationType.BINARY indicates that the column uses the + BINARY collation sequence.
  • SQLCollationType.NO_CASE indicates that the column uses the NOCASE + collation sequence, meaning text comparisons are made in a case-insensitive manner.
+ +
+ Constructs a SQLColumnSchema instance. Generally, developer code does not call the SQLColumnSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + +
flash.data.SQLConnection.loadSchema()flash.data.SQLCollationType
allowNull + Indicates whether NULL values are allowed in this column.Boolean + Indicates whether NULL values are allowed in this column. A column + that is declared with a NOT NULL constraint has a false + value for the allowNull property. + + autoIncrement + Indicates whether this is an auto-increment column.Boolean + Indicates whether this is an auto-increment column. An auto-increment column is a special type + of PRIMARY KEY column whose value is automatically generated as the next value + in a sequence of integers when a new row is inserted into the table. + + dataType + Gets the data type of the column as a string.String + Gets the data type of the column as a string. The value is the literal data type name that was + specified in the CREATE TABLE statement that was used to define the table, or + null if no data type was specified. + + defaultCollationType + Indicates the default collation sequence that is defined for this column.String + Indicates the default collation sequence that is defined for this column. + The value of this property corresponds to one of the constants in the SQLCollationType class: +
  • SQLCollationType.BINARY indicates that the column uses the + BINARY collation sequence.
  • SQLCollationType.NO_CASE indicates that the column uses the NOCASE + collation sequence, meaning that text comparisons are made in a case-insensitive manner.
+ +
flash.data.SQLCollationType
name + Gets the name of the column.String + Gets the name of the column. + + primaryKey + Indicates whether this column is the primary key column (or one of the primary key columns + in a composite key) for its associated table.Boolean + Indicates whether this column is the primary key column (or one of the primary key columns + in a composite key) for its associated table. + +
SQLColumnNameStyle + This class contains the constants that represent the possible values for the + SQLConnection.columnNameStyle property.Object + This class contains the constants that represent the possible values for the + SQLConnection.columnNameStyle property. These values indicate + different options that control how column names (property names) are formatted in the objects + returned as a result of a SQL SELECT statement. + + flash.data.SQLConnection.columnNameStyleDEFAULT + Indicates that column names returned from a SELECT statement + use the default format.defaultString + Indicates that column names returned from a SELECT statement + use the default format. In the default format, column names have the form + [table-name]_[column-name] when multiple tables are + included in the SELECT statement, or [column-name] when + the SELECT statement includes a single table. + + flash.data.SQLConnection.columnNameStyleLONG + Indicates that column names returned from a SELECT statement use + long-column-name format.longString + Indicates that column names returned from a SELECT statement use + long-column-name format. In this format, column names use the form + [table-name]_[column-name] regardless of how many + tables are included in the SELECT statement. + + flash.data.SQLConnection.columnNameStyleSHORT + Indicates that column names returned from a SELECT statement use short-column-name + format.shortString + Indicates that column names returned from a SELECT statement use short-column-name + format. In this format, column names use the form [column-name], + regardless of how many tables are included in the SELECT statement. + +

If the result set contains multiple columns with the same name, only one property with that + name is added to the result object. The value assigned to that property is taken from the last + column with that name in the result row. For example, consider the following SELECT + statement:

+ +
+	 SELECT customers.customerId, addresses.customerId
+	 FROM customers INNER JOIN addresses
+	    ON customers.customerId = addresses.customerId
+	 
+ +

When this statement is executed on a SQLConnection instance with short column name format, + each result object has a property named customerId, containing the + value from the addresses table's customerId column.

+ +
flash.data.SQLConnection.columnNameStyle
SQLSchema + The SQLSchema class is the base class for schema information for database objects + such as tables, views, and indices.Object + The SQLSchema class is the base class for schema information for database objects + such as tables, views, and indices. + +

To obtain schema information for a database, use the + SQLConnection.loadSchema() method to load the schema information. + The resulting SQLSchemaResult instance contains arrays of instances representing the objects + in the database.

+ +

Generally, developer code does not construct SQLSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()SQLSchema + Creates a SQLSchema instance.databaseStringThe name of the associated database. + + nameStringThe name of the database object. + + sqlStringThe SQL used to construct the database + object. + + + Creates a SQLSchema instance. Generally, developer code does not call the SQLSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + + database + The name of the database to which this schema object belongs.String + The name of the database to which this schema object belongs. The name is "main" for the main + database associated with a SQLConnection instance (the database file that is + opened by calling a SQLConnection instance's open() or openAsync() method). For other + databases that are attached to the connection using the + SQLConnection.attach() method, the value is the name specified in the attach() + method call. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()flash.data.SQLConnection.attach()name + The name of this schema object.String + The name of this schema object. Each object within a + database has a unique name. The name is defined in the SQL statement that creates the object + (such as the CREATE TABLE statement for a table). + +

For example, if a database index is created using the following SQL statement, the value of the + name property for that index's schema would be "customer_index":

+ + CREATE INDEX customer_index ON customers (id) + +
sql + Returns the entire text of the SQL statement that was used to create this schema object.String + Returns the entire text of the SQL statement that was used to create this schema object. + Each object within a database is created using a SQL statement. + +

For example, if a database index is created using the following SQL:

+ CREATE INDEX customer_index ON customers (id) +

the sql property for that index's schema would be the entire text of + the statement.

+ +
SQLCollationType + This class contains the constants that represent the possible values for the + defaultCollationType parameter of the SQLColumnSchema constructor, as well as the + SQLColumnSchema.defaultCollationType property.Object + This class contains the constants that represent the possible values for the + defaultCollationType parameter of the SQLColumnSchema constructor, as well as the + SQLColumnSchema.defaultCollationType property. + +

These values represent different collation sequences that can be specified for a column + in a database table. A collation sequence is a way of sorting and comparing data, + for example whether the database differentiates between uppercase and lowercase characters.

+ +

For more information about defining and using collation sequences, see the + "COLLATE" section in the appendix + "SQL support in local databases."

+ +
flash.data.SQLColumnSchema.defaultCollationTypeBINARY + Indicates that the column is defined to use the BINARY collation sequence.binaryString + Indicates that the column is defined to use the BINARY collation sequence. + A SQLCollationType.BINARY collation compares two + values using their byte values, regardless of the text encoding of the characters. + +

When binary collation is used with values of the TEXT storage class, the database + differentiates between uppercase and lowercase characters when sorting and comparing the column's + values.

+ +
flash.data.SQLColumnSchema.defaultCollationType
NO_CASE + Indicates that the column is defined to use the NOCASE collation sequence.noCaseString + Indicates that the column is defined to use the NOCASE collation sequence. + A SQLCollationType.NO_CASE collation ignores uppercase and lowercase differences + when sorting and comparing two values. + + flash.data.SQLColumnSchema.defaultCollationType
SQLSchemaResult + A SQLSchemaResult instance contains the information resulting from a call to + the SQLConnection.loadSchema() method.Object + A SQLSchemaResult instance contains the information resulting from a call to + the SQLConnection.loadSchema() method. It contains four Array properties + that hold the requested schema data, based on the argument values + used when calling SQLConnection.loadSchema(). + +

To retrieve the SQLSchemaResult instance for a SQLConnection.loadSchema() + call, call the SQLConnection instance's getSchemaResult() method. Generally, developer + code does not create SQLSchemaResult instances directly.

+ +
flash.data.SQLConnection.loadSchema()flash.data.SQLConnection.getSchemaResult()SQLSchemaResult + Creates a SQLSchemaResult instance.tablesArrayAn array of SQLTableSchema instances as specified in the loadSchema() request. + + viewsArrayAn array of SQLViewSchema instances as specified in the loadSchema() request. + + indicesArrayAn array of SQLIndexSchema instances as specified in the loadSchema() request. + + triggersArrayAn array of SQLTriggerSchema instances as specified in the loadSchema() request. + + + Creates a SQLSchemaResult instance. Generally, developer code does not call the SQLSchemaResult + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + + flash.data.SQLConnection.loadSchema()indices + An array of SQLIndexSchema instances requested in a call + to SQLConnection.loadSchema().Array + An array of SQLIndexSchema instances requested in a call + to SQLConnection.loadSchema(). If the specified databases + do not contain any indices, or if the loadSchema() call + specifies to exclude indices from the result, the indices + property is an empty array (an array whose length property + is 0). + + flash.data.SQLConnection.loadSchema()flash.data.SQLIndexSchematables + An array of SQLTableSchema instances requested in a call + to SQLConnection.loadSchema().Array + An array of SQLTableSchema instances requested in a call + to SQLConnection.loadSchema(). If the specified databases + do not contain any tables, or if the loadSchema() call + specifies to exclude tables from the result, the tables + property is an empty array (an array whose length property + is 0). + + flash.data.SQLConnection.loadSchema()flash.data.SQLTableSchematriggers + An array of SQLTriggerSchema instances requested in a call + to SQLConnection.loadSchema().Array + An array of SQLTriggerSchema instances requested in a call + to SQLConnection.loadSchema(). If the specified databases + do not contain any triggers, or if the loadSchema() call + specifies to exclude triggers from the result, the triggers + property is an empty array (an array whose length property + is 0). + + flash.data.SQLConnection.loadSchema()flash.data.SQLTriggerSchemaviews + An array of SQLViewSchema instances requested in a call + to SQLConnection.loadSchema().Array + An array of SQLViewSchema instances requested in a call + to SQLConnection.loadSchema(). If the specified databases + do not contain any views, or if the loadSchema() call + indicates that views should be excluded from the result, the views + property is an empty array (an array whose length property + is 0). + + flash.data.SQLConnection.loadSchema()flash.data.SQLViewSchema
SQLTransactionLockType + This class contains the constants that represent the possible values for the + option parameter of the SQLConnection.begin() method.Object + This class contains the constants that represent the possible values for the + option parameter of the SQLConnection.begin() method. + + flash.data.SQLConnection.begin()DEFERRED + Specifies the deferred locking transaction option.deferredString + Specifies the deferred locking transaction option. + A deferred-lock transaction does not acquire a lock on the database + until the database is first accessed. With a deferred + transaction, a lock is not acquired until the first read or write + operation. + + flash.data.SQLConnection.begin()EXCLUSIVE + Specifies the exclusive locking transaction option.exclusiveString + Specifies the exclusive locking transaction option. + An exclusive-locked transaction acquires a lock on the database immediately. + Other SQLStatement objects executing against the same database through a + different SQLConnection (in the same AIR application or a different one) + can't read data from or write data to the database. + + flash.data.SQLConnection.begin()IMMEDIATE + Specifies the immediate locking transaction option.immediateString + Specifies the immediate locking transaction option. + An immediate-locked transaction acquires a lock on the database immediately. + SQLStatement objects executing against the same database through a + different SQLConnection (in the same AIR application or a different one) + can read data from the database but can't write data to it. However, for those + other connections reading data from the database, the initial state of the data + in the database is identical to the state of the database before the + in-transaction SQLConnection instance's begin() method was called. + Any uncommitted data changes made within the immediate-locked transaction are + not available to the other connections. + + flash.data.SQLConnection.begin()SQLConnection + A SQLConnection instance is used to manage the creation of and connection to local SQL database files + (local databases).flash.events:EventDispatcher + A SQLConnection instance is used to manage the creation of and connection to local SQL database files + (local databases). + + +

The functionality of the SQLConnection class falls into several categories:

+ +
  • A local SQL database file is created or opened by calling the open() method or the + SQLConnection instance to the SQLStatement's sqlConnection property.

  • The SQLConnection class also provides state for SQL statements, including a + mechanism for executing multiple statements in a transaction. Transactions are managed using the + begin(), commit(), and rollback() methods. In addition, the + setSavepoint(), releaseSavepoint(), and rollbackToSavepoint() methods + allow code to define and manage savepoints. These are used to subdivide transactions into sets of operations.

  • The SQLConnection class provides access to database schema information for connected + databases. A database's schema describes the definitions of its tables, columns, indices, and triggers. + See the loadSchema() method for more information.

  • The SQLConnection class provides the ability to encrypt databases using AES with CCM. This provides + both authentication and privacy for data. To encrypt a database, a 16 byte key (specified using a + ByteArray) must be specified when the database is created. This key can later be changed + using the SQLConnection.reencrypt() method. Encryption imposes a performance penalty on + writes to and reads from the database. Encryption is applied to data stored on the disk, but not to a + temporary data cache in memory. Encryption is not supported for in-memory databases.

  • A SQLConnection instance can be used to receive database-level + event notifications and provide configuration control for + all aspects of a database, including cache page size, process canceling, and statement execution + options.

+ +

A SQLConnection instance operates in one of two distinct execution modes: asynchronous + and synchronous. To use synchronous execution, you use the open() method to connect to the + main database for the SQLConnection instance. To use asynchronous execution, use the openAsync() + method to connect to the main database for the instance.

+ +

When you're using asynchronous execution, you use event listeners or a Responder instance to + determine when an operation completes or fails. The operations run in the + background rather than in the main application thread, so the application continues + to run and respond to user interaction even while the database operations are being performed. Each + asynchronous SQLConnection instance executes SQL statements in its own thread.

+ +

In asynchronous execution mode, you begin a specific operation + by calling the appropriate method, and you can detect the completion (or failure) of the operation + by registering a listener for the appropriate event. Each operation has an associated event that + is dispatched when the operation completes successfully; for example, when an openAsync() + method call completes successfully (when the database connection is opened) the open + event is dispatched. When any operation fails, + an error event is dispatched. The SQLError instance in the SQLErrorEvent + object's error property contains information about the specific error, + including the operation that was being attempted and the reason the operation failed.

+ +

When you're using synchronous execution, you do not need to register event + listeners to determine when an operation completes or fails. To identify errors, + enclose the error-throwing statements in a try..catch block. Because + synchronous operations execute in the main execution thread, all application + functionality (including refreshing the screen and allowing mouse and keyboard + interaction) is paused while the database operation or operations are performed. + For long-running operations this can cause a noticeable pause in the application.

+ +
flash.data.SQLStatementflash.events.SQLEventflash.events.SQLErrorEventflash.errors.SQLErrorQuick Start: Working asynchronously with a local SQL database (Flex)Quick Start: Working asynchronously with a local SQL database (Flash)Quick Start: Working asynchronously with a local SQL database (HTML)Quick Start: Working synchronously with a local SQL database (Flex)Quick Start: Working synchronously with a local SQL database (Flash)Quick Start: Working synchronously with a local SQL database (HTML)update + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL UPDATE command.flash.events.SQLUpdateEvent.UPDATEflash.events.SQLUpdateEvent + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL UPDATE command. The data change can be a direct result of a UPDATE + statement executed through a SQLStatement instance, or an indirect result caused by a trigger firing + in response to a statement execution. + + flash.data.SQLStatementsetSavepoint + Dispatched when a setSavepoint() method call's operation + completes successfully.flash.events.SQLEvent.SET_SAVEPOINTflash.events.SQLEvent + Dispatched when a setSavepoint() method call's operation + completes successfully. + + setSavepoint()schema + Dispatched when a loadSchema() method call's operation completes + successfully and the schema results are ready.flash.events.SQLEvent.SCHEMAflash.events.SQLEvent + Dispatched when a loadSchema() method call's operation completes + successfully and the schema results are ready. + + loadSchema()rollbackToSavepoint + Dispatched when a rollbackToSavepoint() method call's operation + completes successfully.flash.events.SQLEvent.ROLLBACK_TO_SAVEPOINTflash.events.SQLEvent + Dispatched when a rollbackToSavepoint() method call's operation + completes successfully. + + rollbackToSavepoint()rollback + Dispatched when a rollback() method call's operation + completes successfully.flash.events.SQLEvent.ROLLBACKflash.events.SQLEvent + Dispatched when a rollback() method call's operation + completes successfully. + + rollback()releaseSavepoint + Dispatched when a releaseSavepoint() method call's operation + completes successfully.flash.events.SQLEvent.RELEASE_SAVEPOINTflash.events.SQLEvent + Dispatched when a releaseSavepoint() method call's operation + completes successfully. + + releaseSavepoint()reencrypt + Dispatched when a reencrypt() method call's operation completes + successfully.flash.events.SQLEvent.REENCRYPTflash.events.SQLEvent + Dispatched when a reencrypt() method call's operation completes + successfully. + + reencrypt()open + Dispatched when an openAsync() method call's operation + completes successfully.flash.events.SQLEvent.OPENflash.events.SQLEvent + Dispatched when an openAsync() method call's operation + completes successfully. + + openAsync()insert + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL INSERT command.flash.events.SQLUpdateEvent.INSERTflash.events.SQLUpdateEvent + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL INSERT command. The data change can be a direct result of an INSERT + statement executed through a SQLStatement instance, or an indirect result caused by a trigger firing + in response to a statement execution. + + flash.data.SQLStatementerror + Dispatched when any of the SQLConnection object's asynchronous operations results + in an error.flash.events.SQLErrorEvent.ERRORflash.events.SQLErrorEvent + Dispatched when any of the SQLConnection object's asynchronous operations results + in an error. The SQLErrorEvent instance that's dispatched as the event object + has an error property that contains information about the operation that + was attempted and the cause of the failure. + + detach + Dispatched when a detach() method call's operation + completes successfully.flash.events.SQLEvent.DETACHflash.events.SQLEvent + Dispatched when a detach() method call's operation + completes successfully. + + detach()delete + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL DELETE command.flash.events.SQLUpdateEvent.DELETEflash.events.SQLUpdateEvent + Dispatched when data in any table in any of the connected databases changes as a result + of a SQL DELETE command. The data change can be a direct result of a DELETE + statement executed through a SQLStatement instance, or an indirect result caused by a trigger firing + in response to a statement execution. + + flash.data.SQLStatementdeanalyze + Dispatched when a deanalyze() method call's operation + completes successfully.flash.events.SQLEvent.DEANALYZEflash.events.SQLEvent + Dispatched when a deanalyze() method call's operation + completes successfully. + + deanalyze()commit + Dispatched when a commit() method call's operation + completes successfully.flash.events.SQLEvent.COMMITflash.events.SQLEvent + Dispatched when a commit() method call's operation + completes successfully. + + commit()close + Dispatched when a close() method call's operation + completes successfully.flash.events.SQLEvent.CLOSEflash.events.SQLEvent + Dispatched when a close() method call's operation + completes successfully. + + close()compact + Dispatched when a compact() method call's operation + completes successfully.flash.events.SQLEvent.COMPACTflash.events.SQLEvent + Dispatched when a compact() method call's operation + completes successfully. + + compact()cancel + Dispatched when a cancel() method call's operation completes + successfully.flash.events.SQLEvent.CANCELflash.events.SQLEvent + Dispatched when a cancel() method call's operation completes + successfully. + + cancel()begin + Dispatched when a begin() method call's operation + completes successfully.flash.events.SQLEvent.BEGINflash.events.SQLEvent + Dispatched when a begin() method call's operation + completes successfully. + + begin()attach + Dispatched when an attach() method call's operation + completes successfully.flash.events.SQLEvent.ATTACHflash.events.SQLEvent + Dispatched when an attach() method call's operation + completes successfully. + + attach()analyze + Dispatched when an analyze() operation + completes successfully.flash.events.SQLEvent.ANALYZEflash.events.SQLEvent + Dispatched when an analyze() operation + completes successfully. + + analyze()SQLConnection + Creates a SQLConnection instance.if constructor is called from any sandbox outside + of the main application sandbox. + + SecurityErrorSecurityError + Creates a SQLConnection instance. + + addEventListener + + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.typeStringThe type of event. + + listenerFunctionThe listener function that processes the event. This function must accept + an Event object as its only parameter and must return nothing, as this example shows: + + + function(evt:Event):void + +

The function can have any name.

+ +
useCaptureBooleanfalse + + Determines whether the listener works in the capture phase or the + target and bubbling phases. If useCapture is set to true, + the listener processes the event only during the capture phase and not in the + target or bubbling phase. If useCapture is false, the + listener processes the event only during the target or bubbling phase. To listen for + the event in all three phases, call addEventListener twice, once with + useCapture set to true, then again with + useCapture set to false. + + priorityint0.0The priority level of the event listener. The priority is designated by + a signed 32-bit integer. The higher the number, the higher the priority. All listeners + with priority n are processed before listeners of priority n-1. If two + or more listeners share the same priority, they are processed in the order in which they + were added. The default priority is 0. + + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or + weak. A strong reference (the default) prevents your listener from being garbage-collected. + A weak reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbage-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. + + + +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's + priority, you must first call removeListener(). Then you can register the + listener again with the new priority level.

+ +

Keep in mind that after the listener is registered, subsequent calls to + addEventListener() with a different type or + useCapture value result in the creation of a separate listener registration. + For example, if you first register a listener with useCapture set to + true, it listens only during the capture phase. If you call + addEventListener() again using the same listener object, but with + useCapture set to false, you have two separate listeners: one + that listens during the capture phase and another that listens during the target and + bubbling phases. +

+ +

You cannot register an event listener for only the target phase or the bubbling + phase. Those phases are coupled during registration because bubbling + applies only to the ancestors of the target node.

+ +

If you no longer need an event listener, remove it by calling + removeEventListener(), or memory problems could result. Event listeners are not automatically + removed from memory because the garbage + collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference + parameter is set to true).

+ +

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event listeners + attached to it move along with it.

+ + +

If the event listener is being registered on a node while an event is being processed + on this node, the event listener is not triggered during the current phase but can be + triggered during a later phase in the event flow, such as the bubbling phase.

+ +

If an event listener is removed from a node while an event is being processed on the node, + it is still triggered by the current actions. After it is removed, the event listener is + never invoked again (unless registered again for future processing).

+ +
analyze + Gathers statistics about database indices and + stores them in the database.When this method is called while the SQLConnection instance + isn't connected to a database (the connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorif the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresourceNameStringnullThe name of the database or + table whose indices are to be analyzed. If the specified resource is a table + whose name is unique among all the attached databases, only the table name needs + to be specified. However, a table name can be specified in the form + [database-name].[table-name] to prevent ambiguity when the table name + is not unique. If the resourceName parameter is null + (the default), all the indices in all attached databases are analyzed. + + responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null an analyze + or error event is dispatched when execution completes. + + + Gathers statistics about database indices and + stores them in the database. These statistics can then be used by the query optimizer + (the portion of the database engine that determines the most efficient way to + execute each statement). The statistics help the query optimizer make better + choices about which index or indices to use when executing a particular query. + +

If a database has indices defined, but the analyze() method hasn't + been called, the runtime still uses those indices to execute statements. However, + without the additional statistical information generated by the analyze() method, + the runtime may not choose the most efficient index for a particular query.

+ +

When a table's data changes (as a result of INSERT, UPDATE, + or DELETE statements) the indices associated with that table change as well. + The statistical information generated by analyze() is not automatically + updated. Consequently, after a large number of data changes, calling the + analyze() method again might be beneficial. However, the benefit obtained + from calling analyze() again depends on several factors, including the + number of indices defined on a table, the relationship between the number of changed + rows and the total number of rows in the table, how much variation there is in the + table's indexed data, and how different the changed data is from the prechange data.

+ +

The resourceName parameter indicates whether the operation is + performed on the indices of all attached databases, a specific database, or a specific + table.

+ +

Each time this method is called, any previously created statistical + data is purged and recreated for the database or table specified in the resourceName + parameter (or all tables in all connected databases if resourceName is null). + This method can be called at any time + while a database connection is open. The analyze() operation and its statistical + data are not included in a transaction; however, it is best + not to call analyze() when the database has a current transaction (the + inTransaction property is true). This is because any data, table schema, + or index changes that have been executed in the transaction but not yet committed + are not taken into account by the analyze() call, and the + analyze() data is out of date as soon as the transaction is committed.

+ +

To remove the statistical data created with the analyze() method, use + the deanalyze() method.

+ +
deanalyze()analyzeflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
attach + Adds another database to the SQLConnection instance, giving the new database + the specified name.When the name parameter is an empty string ("") + or null + + ArgumentErrorArgumentErrorWhen the value specified for the reference parameter is not a + flash.filesystem.File instance + + ArgumentErrorArgumentErrorWhen the encryptionKey argument is not null and + its length is not 16 bytes + + ArgumentErrorArgumentErrorWhen the reference parameter is null and the + encryptionKey argument is not null + + ArgumentErrorArgumentErrorWhen the SQLConnection instance isn't connected to a database + (the connected property is false); + or if a transaction is currently open (the inTransaction property is true). + + IllegalOperationErrorflash.errors:IllegalOperationErrorif the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornameStringThe name that is used to identify the newly attached database. + This name can be used in SQL statements to explicitly indicate that a table belongs + to the specified database, when using the format [database-name].[table-name]. + The names "main" and "temp" are reserved and cannot be used. + + referenceObjectnullA reference to the database file to attach + (a flash.filesystem.File instance). If the reference refers to a file that doesn't exist, either + a new database file is created or an error is thrown according to the value that was specified for the + openMode parameter in the open() or openAsync() call that + connected the main database. + +

If the parameter's value is null, an in-memory database is created and attached.

+ +
responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null an attach + or error event is dispatched when execution completes. + + encryptionKeyflash.utils:ByteArraynullThe encryption key for the database file. + If the attach() call creates a database, the database is encrypted and the + specified key is used as the encryption key for the database. If the call attaches an + existing encrypted database, the value must match the database's encryption key or an error occurs. + If the database being attached is not encrypted, or to create an unencrypted database, + the value must be null (the default). + +

A valid encryption key is 16 bytes long. An in-memory database cannot be encrypted, so this + parameter must be null when the reference parameter's value is + null.

+ +

When attaching an encrypted database, if the encryption key provided doesn't match the + database's encryption key, an exception occurs. In synchronous execution mode, a SQLError + exception is thrown. In asynchronous execution mode, a SQLErrorEvent is dispatched, and the event + object's error property contains a SQLError instance. In either case, the + SQLError object's errorID property is 3138 ("File opened is not a database file").

+ +

The encryptionKey parameter is available starting with AIR 1.5.

+ +
+ Adds another database to the SQLConnection instance, giving the new database + the specified name. Attaching a database allows that database to be used in SQL + statements executed against this SQLConnection instance. + +

If a database is already attached using the specified name, calling attach() + results in an error. However, the same database may + be attached multiple times using unique names. Only ten databases can be attached + to a single SQLConnection instance.

+ +

Any SQL statement can be executed on a database connected using + attach() that can be executed on the main database (the database + connected using open() or openAsync()). + A SQL statement can access tables in any of the databases attached to the + statement's associated SQLConnection instance, including accessing tables from + multiple databases in a single statement. When the runtime is resolving table names + in a statement, it searches through the SQLConnection instance's databases in the order + in which the databases were attached, starting with the database that was connected + using the open() or openAsync() method. Use the database name (as specified in the + attach() method's name parameter) in the statement + to explicitly qualify a table name.

+ +

To remove a database attached using the attach() method, + use the detach() method. When the SQLConnection instance is closed (by + calling the close() method), all + attached databases are detached.

+ +

The attached database uses the same execution mode (synchronous or asynchronous) as + the main database, depending on whether the main database was connected using the open() + method or the openAsync() method.

+ +
open()openAsync()detach()attachflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
begin + Begins a transaction within which all SQL statements executed against + the connection's database or databases are grouped.When this method is called while the SQLConnection instance + isn't connected to a database (the connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the option specified is not one of the SQLTransactionLockType + constants. + + ArgumentErrorArgumentErrorif the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErroroptionStringnullIndicates the locking strategy that is used by + the transaction. The value can be one of the constants defined + in the SQLTransactionLockType class: +
  • SQLTransactionLockType.DEFERRED indicates that a lock is not acquired + until the first read or write operation.
  • SQLTransactionLockType.EXCLUSIVE indicates that a lock is acquired as soon + as possible, and no other SQLConnection instance can read from or write to the database.
  • SQLTransactionLockType.IMMEDIATE indicates that a lock is acquired as soon + as possible, in which other SQLConnection instances can read from but can't write to the database.
+

The default value (null) is equivalent to SQLTransactionLockType.DEFERRED.

+ +
responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a begin + or error event is dispatched when execution completes. + +
+ Begins a transaction within which all SQL statements executed against + the connection's database or databases are grouped. + +

By default, each SQL statement + is executed within its own transaction, and the transaction ends when + the statement's execution succeeds or fails. Creating a transaction using the + begin() method causes a new, manual transaction to be created. + From that point on, all SQL statements executed against the SQLConnection instance + take place within the transaction, and any actions or modifications performed + by the statements can be committed (made permanent) or rolled back (undone) as + a group.

+ +

To end a transaction, call the commit() or + rollback() method, depending on whether the changes made by the + transactions' statements are to be made permanent or discarded.

+ +

Nested calls to begin() are ignored. You can create savepoints, + which are like bookmarks within a transaction, by calling the + setSavepoint() method. You can then partially commit or roll back + SQL statements by calling the releaseSavepoint() or + rollbackToSavepoint() methods. However, if a transaction is started + by calling begin(), changes are not permanently committed to the + database until the commit() method is called.

+ +

If the database connection closes while a transaction is currently open, + AIR rolls back the transaction automatically. (Note: for AIR 1.1 and previous + versions, an open transaction is automatically committed when a connection + closes.)

+ +

A transaction is not limited to statement executions in a single + database; it can include statements executed on different attached + databases.

+ +
The following example demonstrates executing multiple SQL INSERT + statements within a transaction. First a row is added to the "employees" table. Next the + primary key of the newly inserted row is retrieved, and used to add a row to the related + "phoneNumbers" table. + +package +{ + import flash.data.SQLConnection; + import flash.data.SQLResult; + import flash.data.SQLStatement; + import flash.display.Sprite; + import flash.events.SQLErrorEvent; + import flash.events.SQLEvent; + import flash.filesystem.File; + + public class MultiInsertTransactionExample extends Sprite + { + private var conn:SQLConnection; + private var insertEmployee:SQLStatement; + private var insertPhoneNumber:SQLStatement; + + public function MultiInsertTransactionExample():void + { + // define where to find the database file + var appStorage:File = File.applicationStorageDirectory; + var dbFile:File = appStorage.resolvePath("ExampleDatabase.db"); + + // open the database connection + conn = new SQLConnection(); + conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); + conn.addEventListener(SQLEvent.OPEN, openHandler); + conn.openAsync(dbFile); + } + + // Called when the database is connected + private function openHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.OPEN, openHandler); + + // start a transaction + conn.addEventListener(SQLEvent.BEGIN, beginHandler); + conn.begin(); + } + + // Called when the transaction begins + private function beginHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.BEGIN, beginHandler); + + // create and execute the first SQL statement: + // insert an employee record + insertEmployee = new SQLStatement(); + insertEmployee.sqlConnection = conn; + insertEmployee.text = + "INSERT INTO employees (lastName, firstName, email) " + + "VALUES (:lastName, :firstName, :email, :birthday)"; + insertEmployee.parameters[":lastName"] = "Smith"; + insertEmployee.parameters[":firstName"] = "Bob"; + insertEmployee.parameters[":email"] = "bsmith@example.com"; + insertEmployee.parameters[":birthday"] = new Date(1971, 8, 12); + + insertEmployee.addEventListener(SQLEvent.RESULT, insertEmployeeHandler); + insertEmployee.addEventListener(SQLErrorEvent.ERROR, errorHandler); + + insertEmployee.execute(); + } + + // Called after the employee record is inserted + private function insertEmployeeHandler(event:SQLEvent):void + { + insertEmployee.removeEventListener(SQLEvent.RESULT, insertEmployeeHandler); + insertEmployee.removeEventListener(SQLErrorEvent.ERROR, errorHandler); + + // Get the employee id of the newly created employee row + var result:SQLResult = insertEmployee.getResult(); + var employeeId:Number = result.lastInsertRowID; + + // Add a phone number to the related phoneNumbers table + insertPhoneNumber = new SQLStatement(); + insertPhoneNumber.sqlConnection = conn; + insertPhoneNumber.text = + "INSERT INTO phoneNumbers (employeeId, type, number) " + + "VALUES (:employeeId, :type, :number)"; + insertPhoneNumber.parameters[":employeeId"] = employeeId; + insertPhoneNumber.parameters[":type"] = "Home"; + insertPhoneNumber.parameters[":number"] = "(555) 555-1234"; + + insertPhoneNumber.addEventListener(SQLEvent.RESULT, insertPhoneNumberHandler); + insertPhoneNumber.addEventListener(SQLErrorEvent.ERROR, errorHandler); + + insertPhoneNumber.execute(); + } + + // Called after the phone number record is inserted + private function insertPhoneNumberHandler(event:SQLEvent):void + { + insertPhoneNumber.removeEventListener(SQLEvent.RESULT, insertPhoneNumberHandler); + insertPhoneNumber.removeEventListener(SQLErrorEvent.ERROR, errorHandler); + + // No errors so far, so commit the transaction + conn.addEventListener(SQLEvent.COMMIT, commitHandler); + conn.commit(); + } + + // Called after the transaction is committed + private function commitHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.COMMIT, commitHandler); + + trace("Transaction complete"); + } + + // Called whenever an error occurs + private function errorHandler(event:SQLErrorEvent):void + { + // If a transaction is happening, roll it back + if (conn.inTransaction) + { + conn.addEventListener(SQLEvent.ROLLBACK, rollbackHandler); + conn.rollback(); + } + + trace(event.error.message); + trace(event.error.details); + } + + // Called when the transaction is rolled back + private function rollbackHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.ROLLBACK, rollbackHandler); + + // add additional error handling, close the database, etc. + } + } +} + The following example demonstrates executing multiple SQL DELETE + statements within a transaction. The transaction is used to delete an employee record. + First the related rows in the "phoneNumbers" table are deleted. Next the employee + record row is deleted from the "employees" table. + +package +{ + import flash.data.SQLConnection; + import flash.data.SQLResult; + import flash.data.SQLStatement; + import flash.display.Sprite; + import flash.events.SQLErrorEvent; + import flash.events.SQLEvent; + import flash.filesystem.File; + + public class MultiDeleteTransactionExample extends Sprite + { + private var conn:SQLConnection; + private var deleteEmployee:SQLStatement; + private var deletePhoneNumbers:SQLStatement; + + private var employeeIdToDelete:Number = 25; + + public function MultiDeleteTransactionExample():void + { + // define where to find the database file + var appStorage:File = File.applicationStorageDirectory; + var dbFile:File = appStorage.resolvePath("ExampleDatabase.db"); + + // open the database connection + conn = new SQLConnection(); + conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); + conn.addEventListener(SQLEvent.OPEN, openHandler); + conn.openAsync(dbFile); + } + + // Called when the database is connected + private function openHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.OPEN, openHandler); + + // start a transaction + conn.addEventListener(SQLEvent.BEGIN, beginHandler); + conn.begin(); + } + + // Called when the transaction begins + private function beginHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.BEGIN, beginHandler); + + // Create and execute the first SQL statement: + // Delete an employee's phone number records + deletePhoneNumbers = new SQLStatement(); + deletePhoneNumbers.sqlConnection = conn; + deletePhoneNumbers.text = + "DELETE FROM phoneNumbers " + + "WHERE employeeId = :employeeId"; + deletePhoneNumbers.parameters[":employeeId"] = employeeIdToDelete; + + deletePhoneNumbers.addEventListener(SQLEvent.RESULT, deletePhoneNumbersHandler); + deletePhoneNumbers.addEventListener(SQLErrorEvent.ERROR, errorHandler); + + deletePhoneNumbers.execute(); + } + + // Called after the phone number records are deleted + private function deletePhoneNumbersHandler(event:SQLEvent):void + { + deletePhoneNumbers.removeEventListener(SQLEvent.RESULT, deletePhoneNumbersHandler); + deletePhoneNumbers.removeEventListener(SQLErrorEvent.ERROR, errorHandler); + + deleteEmployee = new SQLStatement(); + deleteEmployee.sqlConnection = conn; + deleteEmployee.text = + "DELETE FROM employees " + + "WHERE employeeId = :employeeId"; + deleteEmployee.parameters[":employeeId"] = employeeIdToDelete; + + deleteEmployee.addEventListener(SQLEvent.RESULT, deleteEmployeeHandler); + deleteEmployee.addEventListener(SQLErrorEvent.ERROR, errorHandler); + + deleteEmployee.execute(); + } + + // Called after the employee record is deleted + private function deleteEmployeeHandler(event:SQLEvent):void + { + deleteEmployee.removeEventListener(SQLEvent.RESULT, deleteEmployeeHandler); + deleteEmployee.removeEventListener(SQLErrorEvent.ERROR, errorHandler); + + // No errors so far, so commit the transaction + conn.addEventListener(SQLEvent.COMMIT, commitHandler); + conn.commit(); + } + + // Called after the transaction is committed + private function commitHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.COMMIT, commitHandler); + + trace("Transaction complete"); + } + + // Called whenever an error occurs + private function errorHandler(event:SQLErrorEvent):void + { + // If a transaction is happening, roll it back + if (conn.inTransaction) + { + conn.addEventListener(SQLEvent.ROLLBACK, rollbackHandler); + conn.rollback(); + } + + trace(event.error.message); + trace(event.error.details); + } + + // Called when the transaction is rolled back + private function rollbackHandler(event:SQLEvent):void + { + conn.removeEventListener(SQLEvent.ROLLBACK, rollbackHandler); + + // add additional error handling, close the database, etc. + } + } +} +
commit()rollback()setSavepoint()releaseSavepoint()rollbackToSavepoint()flash.data.SQLTransactionLockTypebeginflash.events:SQLEventDispatched when the operation completes. + + Dispatched when the operation completes.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
cancel + Aborts all SQL statements that are currently executing on databases connected to the SQLConnection + instance.When this method is called while the SQLConnection instance + isn't connected to a database (the connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a cancel + or error event is dispatched when execution completes. + + + Aborts all SQL statements that are currently executing on databases connected to the SQLConnection + instance. This method can be used to stop long running or runaway queries. + +

If there are statements executing when the cancel() method is called, this method + aborts the statements' operations and any incomplete updates or transactions are rolled back. + If there are no statements currently executing, calling this method rolls back an open transaction + but otherwise does nothing.

+ +
flash.data.SQLStatementcancelflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
close + Closes the current database connection.If the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a close + or error event is dispatched when execution completes. + + + Closes the current database connection. Any attached databases are + detached as well. + +

If there is an open + transaction when close() is called, the transaction is rolled back. + When a SQLConnection instance is + garbage-collected, the runtime calls close() automatically, including + if an AIR application is closed while a SQLConnection is still connected to a database.

+ +
closeflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
commit + Commits an existing transaction, causing any actions performed by the transaction's + statements to be permanently applied to the database.When the method is called while the SQLConnection + instance isn't connected to a database (the connected property is + false); or if no transaction is currently open (the + inTransaction property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a commit + or error event is dispatched when execution completes. + + + Commits an existing transaction, causing any actions performed by the transaction's + statements to be permanently applied to the database. + +

Intermediate savepoints, which are like bookmarks in a transaction, can be created + by calling the setSavepoint() method. Using savepoints you can commit + portions of a transaction by calling the releaseSavepoint() + method, or roll back portions of a transaction by calling the + rollbackToSavepoint() method. However, + if a transaction is opened using the begin() method, changes are not + permanently saved to the database until the entire transaction is + committed by calling the commit() method.

+ +

For a transaction that uses savepoints, any statements that were rolled back + using the rollbackToSavepoint() method are not committed when the + entire transaction is committed. Statements that were committed using + releaseSavepoint() or whose savepoints weren't released or rolled back + are committed to the database.

+ +
begin()rollback()setSavepoint()releaseSavepoint()rollbackToSavepoint()commitflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation completes with a failure. + + Dispatched when the operation completes with a failure.
compact + Reclaims all unused space in the database.If the method is called while the SQLConnection instance + isn't connected to a database (the connected property is false); + or if a transaction is currently in progress (the inTransaction + property is true). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a compact + or error event is dispatched when execution completes. + + + Reclaims all unused space in the database. When an object (table, index, or trigger) is + dropped from the database, it leaves behind empty space. This makes the database file + larger than it needs to be, but can speed up INSERT operations. + Over time, INSERT and DELETE operations can leave the database + file structure fragmented, which slows down disk access to the database contents. This + method compacts the database file, eliminating free pages, aligning table data to be + contiguous, and otherwise cleaning up the database file structure. + +

The compact() operation can't be performed on an attached database file; + it can only be performed on the main (original) database file opened by the SQLConnection + instance. This operation fails if there is an active transaction, and has no effect + on an in-memory database.

+ +
compactflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
deanalyze + Removes all statistical information created by a call to the + analyze() method.When this method is called while the SQLConnection instance + isn't connected to a database (the connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a deanalyze + or error event is dispatched when execution completes. + + + Removes all statistical information created by a call to the + analyze() method. + +

Because the statistics generated by the analyze() method take up space in + a database, calling deanalyze() allows you to reclaim that space, such as + after dropping several indices or tables.

+ +

This operation is not included in an active transaction.

+ +
analyze()deanalyzeflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
detach + Detaches an additional database previously attached to the SQLConnection instance using + the attach() method.If the name argument is null or contains + an empty string (""). + + ArgumentErrorArgumentErrorIf this method is called while the SQLConnection instance + isn't connected to a database (the connected property is false); or + if the SQLConnection instance has an open transaction (the inTransaction + property is true). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornameStringThe given name of the database to detach. + + responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a detach + or error event is dispatched when execution completes. + + + Detaches an additional database previously attached to the SQLConnection instance using + the attach() method. It is possible to have the same database + attached multiple times using different names, and detaching one + connection leaves the others intact. A database cannot be detached + if the connection has an open transaction (if the inTransaction + property is true). + + attach()detachflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.getSchemaResult + Provides access to the result of a call to the loadSchema() method.flash.data:SQLSchemaResult + Provides access to the result of a call to the loadSchema() method. + The getSchemaResult() method behaves as a first-in, first-out queue of + results. Each time the loadSchema() method call completes (each time the + schema event is dispatched in asynchronous execution mode), + a new SQLSchemaResult object is added to the queue. + Each time the getSchemaResult() method + is called, the earliest result (the one that was added to the queue first) is returned and removed + from the queue. When there are no more objects left in the queue, getSchemaResult() + returns null. + +

When the database connection is closed the method returns null.

+ +
loadSchema()schema event
loadSchema + Loads schema information from the connected database or any attached databases.When the method is called while the SQLConnection instance + isn't connected to a database (the connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorWhen the specified type argument value isn't + one of the allowed types. + + ArgumentErrorArgumentErrorWhen using synchronous execution mode, if an invalid value is supplied for the name + or database parameters. + + SQLErrorflash.errors:SQLErrortypeClassnullIndicates the type of schema to load. A null value (the + default) indicates that all the schema information should be loaded. + Specifying a non-null value for this parameter narrows the scope of the + resulting schema, removing potentially unneeded information from the results + and making the operation more efficient. The value must be the class name of + one of the following classes: +
  • SQLIndexSchema
  • SQLTableSchema
  • SQLTriggerSchema
  • SQLViewSchema
+ +
nameStringnullIndicates which resource's schema is loaded. How this value is + used depends on the type argument specified. Typically, this is the name of a database + object such as a table name, an index or view name, and so forth. If a value is specified, + only schema information for the database object with the specified name is included in the + result. + +

If the specified value is not valid an error event is + dispatched (or an error is thrown in synchronous execution mode). The type parameter + value must correspond to the type of the object named in order for the value to be valid, as described + in the method description.

+ +

If the name argument is null then all schemata of the specified + type are included. If the value specified is not valid an error event is dispatched.

+ +
databaseStringmainThe name of the database whose schema is loaded. If the value specified + is not valid an error event is dispatched. + + includeColumnSchemaBooleantrueIndicates whether the result includes schema information for the + columns of tables and views. + + responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a schema + or error event is dispatched when execution completes. + +
+ Loads schema information from the connected database or any attached databases. + The schema indicates the structure of the database's tables, columns, indices, and triggers. + +

To access the loaded schema use the SQLConnection.getSchemaResult() method.

+ +

In asynchronous execution mode, a schema event is dispatched if the operation + is successful, or an error event is dispatched if the operation fails.

+ +

The combination of the type and name parameter values determines the + type of schema data that's generated by the loadSchema() method and, consequently, the + values of the properties of the SQLSchemaResult instance that's generated. The following + table lists the valid type and name pairs and the schema data that's + generated as a result:

+ + type argumentname argumentRetrieves schema data for: nullnullall objects in the database (all tables, views, triggers, and indices)SQLIndexSchemanullall indices in the databaseSQLIndexSchemavalid table nameall indices defined on the specified tableSQLIndexSchemavalid index namethe specified indexSQLTableSchemanullall tables in the databaseSQLTableSchemavalid table namethe specified tableSQLTriggerSchemanullall triggers in the databaseSQLTriggerSchemavalid table nameall triggers associated with the specified tableSQLTriggerSchemavalid view nameall triggers associated with the specified view SQLTriggerSchemavalid trigger namethe specified trigger SQLViewSchemanullall views in the databaseSQLViewSchemavalid view namethe specified view + +

If the combination of type and name arguments does not correspond to + one of the specified combinations, an error event is dispatched in asynchronous + execution mode or an exception is thrown in synchronous execution mode. + For instance, if the type argument is SQLViewSchema and the name + argument is the name of a table (rather than the name of a view), an error is raised indicating that + the database doesn't contain an object of the specified type with the specified name.

+ + +

If the database is empty (it doesn't contain any tables, views, triggers, + or indices), calling the loadSchema() method results in an error.

+ +
getSchemaResult()schema eventflash.data.SQLIndexSchemaflash.data.SQLTableSchemaflash.data.SQLTriggerSchemaflash.data.SQLViewSchemaschemaflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation completes with a failure. + + Dispatched when the operation completes with a failure.
openAsync + Opens an asynchronous connection to the database file at the specified location in the file system, + or creates and opens a new database file at the location, or creates and opens an + in-memory database.When the SQLConnection instance already has an open connection + to a database (the connected property is true). + + IllegalOperationErrorflash.errors:IllegalOperationErrorWhen the value specified for the reference parameter is not a + flash.filesystem.File instance + + ArgumentErrorArgumentErrorWhen the encryptionKey argument is not null and + its length is not 16 bytes + + ArgumentErrorArgumentErrorWhen the reference parameter is null and the + encryptionKey argument is not null + + ArgumentErrorArgumentErrorIf an invalid pageSize parameter is specified. + This includes passing a page size when the mode is SQLMode.READ. + + ArgumentErrorArgumentErrorreferenceObjectnullThe location of the database file that is opened. This value must be + a flash.filesystem.File instance. If the parameter's value is null, an in-memory database + is created and opened. + + openModeStringcreateIndicates how the database is opened. The value can be any of the + constants defined in the SQLMode class. The default value is + SQLMode.CREATE, indicating that if a database file is not found at the specified + location, one is created. If openMode is SQLMode.READ and + the specified file does not exist then an error event is dispatched. This parameter is ignored + when the reference parameter is null. + + responderflash.net:RespondernullAn object that designates methods to be called when the operation succeeds or fails. + If the responder argument is null an open or error + event is dispatched when execution completes. + + autoCompactBooleanfalseIndicates whether unused space in the database is reclaimed automatically. + This parameter is only valid when creating a new database file or opening a database file in which + no tables have been created. By default, the space taken up by removed data is left in the database + file and reused when needed. Setting this parameter to true causes the database to + automatically reclaim unused space. This can negatively affect performance because it requires + additional processing each time data is written to the database and can also cause the + database data to become fragmented over time. + To force the database to reclaim unused space in a database file at any time and to + defragment the database file, use the compact() method. + +

This parameter is ignored when the openMode parameter is SQLMode.READ.

+ +
pageSizeint1024Indicates the page size (in bytes) for the database. This parameter is + only valid when creating a new database file or opening a database file in which + no tables have been created. The value must be a power of two greater than or equal to + 512 and less than or equal to 32768. The default value is 1024 bytes. This value can only be set + before any tables are created. Once the tables are created attempting to change this value + results in an error. + + encryptionKeyflash.utils:ByteArraynullThe encryption key for the database file. + If the openAsync() call creates a database, the database is encrypted and the + specified key is used as the encryption key for the database. If the call opens an + encrypted database, the value must match the database's encryption key or an error occurs. + If the database being opened is not encrypted, the value must be null (the + default) or an error occurs. + +

A valid encryption key is 16 bytes long. An in-memory database cannot be encrypted, so this + parameter must be null when the reference parameter's value is + null.

+ +

When opening an encrypted database, if the encryption key provided doesn't match the + database's encryption key, a SQLErrorEvent is dispatched. The event object's + error property contains a SQLError instance. That SQLError object's + errorID property is 3138 ("File opened is not a database file").

+ +

The encryptionKey parameter is available starting with AIR 1.5.

+ +
+ Opens an asynchronous connection to the database file at the specified location in the file system, + or creates and opens a new database file at the location, or creates and opens an + in-memory database. The operations of creating and opening the database, as well as all other operations + that are performed using this SQLConnection instance (including statement execution and other operations + performed by a SQLStatement instance associated with this SQLConnection instance) are performed + asynchronously when the database is opened using this method. To perform operations + synchronously, open the database connection using the open() method instead. + +

Once a database is connected, use a SQLStatement instance to execute SQL commands. + Database-level operations such as beginning or ending transactions, loading schema information, + and other operations are performed using the SQLConnection instance.

+ +

A database that is connected using the openAsync() method is automatically + assigned the database name "main"; that name can be used to explicitly qualify + table names in SQL statements using the format [database-name].[table-name].

+ +
open()close()flash.data.SQLModeopenflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails. The connection is never left open after a + failed operation. + + Dispatched when the operation fails.
open + Opens a synchronous connection to the database file at the specified location in the file system, + or creates and opens a new database file at the location, or creates and opens an + in-memory database.When the SQLConnection instance already has an open connection + to a database (the connected property is true). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails. The connection is never left open after a failed + operation. + + SQLErrorflash.errors:SQLErrorWhen the value specified for the reference parameter is not a + flash.filesystem.File instance + + ArgumentErrorArgumentErrorWhen the encryptionKey argument is not null and + its length is not 16 bytes + + ArgumentErrorArgumentErrorWhen the reference parameter is null and the + encryptionKey argument is not null + + ArgumentErrorArgumentErrorIf an invalid pageSize parameter is specified. + This includes passing a page size when the mode is SQLMode.READ. + + ArgumentErrorArgumentErrorreferenceObjectnullThe location of the database file that is opened. This value must be + a flash.filesystem.File instance. If the parameter's value is null, an in-memory database + is created and opened. + + openModeStringcreateIndicates how the database is opened. The value can be any of the + constants defined in the SQLMode class. The default value is + SQLMode.CREATE, indicating that if a database file is not found at the specified + location, one is created. If openMode is SQLMode.READ and + the specified file does not exist then an error occurs. This parameter is ignored + when the reference parameter is null. + + autoCompactBooleanfalseIndicates whether unused space in the database is reclaimed automatically. + This parameter is only valid when creating a new database file or opening a database file in which + no tables have been created. By default, the space taken up by removed data is left in the database + file and reused when needed. Setting this parameter to true causes the database to + automatically reclaim unused space. This can negatively affect performance because it requires + additional processing each time data is written to the database and can also cause the + database data to become fragmented over time. + At any time you can force the database to reclaim unused space in a database file and + defragment the database file using the compact() method. + +

This parameter is ignored when the openMode parameter is SQLMode.READ.

+ +
pageSizeint1024Indicates the page size (in bytes) for the database. This parameter is + only valid when creating a new database file or opening a database file in which + no tables have been created. The value must be a power of two greater than or equal to + 512 and less than or equal to 32768. The default value is 1024 bytes. This value can only be set + before any tables are created. Once the tables are created attempting to change this value + results in an error. + + encryptionKeyflash.utils:ByteArraynullThe encryption key for the database file. + If the open() call creates a database, the database is encrypted and the + specified key is used as the encryption key for the database. If the call opens an + encrypted database, the value must match the database's encryption key or an error occurs. + If the database being opened is not encrypted, or to create an unencrypted database, + the value must be null (the default) or an error occurs. + +

A valid encryption key is 16 bytes long. An in-memory database cannot be encrypted, so this + parameter must be null when the reference parameter's value is + null.

+ +

When opening an encrypted database, if the encryption key provided doesn't match the + database's encryption key, a SQLError exception is thrown. In that case the SQLError object's + errorID property is 3138 ("File opened is not a database file").

+ +

The encryptionKey parameter is available starting with AIR 1.5.

+ +
+ Opens a synchronous connection to the database file at the specified location in the file system, + or creates and opens a new database file at the location, or creates and opens an + in-memory database. The operations of creating and opening the database, as well as all other operations + that are performed using this SQLConnection instance (including statement execution and other operations + performed by a SQLStatement instance associated with this SQLConnection instance) are performed + synchronously when the database is opened using this method. To perform operations + asynchronously, open the database connection using the openAsync() method instead. + +

Once a database is connected, use a SQLStatement instance to execute SQL commands. + Database-level operations such as beginning or ending transactions, loading schema information, + and other operations are performed using the SQLConnection instance.

+ +

A database that is connected using the open() method is automatically + assigned the database name "main". That name can be used to explicitly qualify + table names in SQL statements using the format [database-name].[table-name].

+ +
openAsync()close()flash.data.SQLModeopenflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.
reencrypt + Changes the encryption key of an encrypted database.When the newEncryptionKey value is null or its + length is not 16 bytes. + + ArgumentErrorArgumentErrorWhen the connection is not open, or if there is an open transaction. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornewEncryptionKeyflash.utils:ByteArrayA ByteArray containing the new encryption key for the database. A valid + encryption key is 16 bytes long. + + responderflash.net:RespondernullAn object that designates methods to be called when the operation succeeds or fails. + If the responder argument is null a reencrypt or + error event is dispatched when execution completes. + + + Changes the encryption key of an encrypted database. This method only affects the encryption + key of the main database (the database that was connected using the open() or + openAsync() method). You can only call reencrypt() on a database + that was encrypted when it was created. Once a database has been created as an encrypted database, + it cannot be unencrypted. Likewise, a database that is created without encryption cannot be + encrypted later. + +

The reencryption operation runs in its own transaction. If the reencryption process + is interrupted, the database rolls back the transaction and the encryption key is not changed.

+ +
open()openAsync()attach()reencryptflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails. + + Dispatched when the operation fails.
releaseSavepoint + This method commits the SQL operations made since the most recent savepoint + or the named savepoint if a name is specified.when the name parameter value is an empty + string (""). + + ArgumentErrorArgumentErrorWhen the method is called while the SQLConnection + instance isn't connected to a database (the connected property is + false); or if no transaction is currently open (the + inTransaction property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornameStringnullString The name of the savepoint from which all SQL operations + should be committed. If no value is provided or if this parameter is + null (the default) then the most recent unnamed savepoint (created + by a call to setSavepoint() with no name value) is + used. The name value cannot be an empty string (""). + + responderflash.net:RespondernullResponder An object that designates methods to be called + when the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a releaseSavepoint + or error event is dispatched when execution completes. + + + This method commits the SQL operations made since the most recent savepoint + or the named savepoint if a name is specified. + +

Note that until the entire transaction is committed, any changes are not + permanently saved to the database. If the transaction is started using the + begin() method, you must call the commit() method + to commit the entire transaction. If the transaction is started by calling + setSavepoint() while inTransaction is + false, you can finish the entire transaction either by calling + the commit() method or by calling releaseSavepoint() + or rollbackToSavepoint() for the first savepoint of the + transaction.

+ +

If the code calls the rollback() method, it permanently discards + all changes in the transaction, regardless of whether releaseSavepoint() + is called before the transaction is rolled back.

+ +

If this method is called with no parameters (or with null for + the name parameter), it commits all database changes since the most + recent unnamed savepoint (the most recent savepoint created by calling + setSavepoint() with no name parameter). For example, + if the setSavepoint() method has been called three times, three + savepoints are set. Calling releaseSavepoint() at that point + commits the SQL operations performed since the third (newest) + savepoint.

+ +

If a value is provided for the name parameter this method commits + all the SQL operations performed since the savepoint with the specified name. + If other savepoints have been created more recently than the specified savepoint, + operations performed after those savepoints are committed also.

+ +

Once a savepoint is released or rolled back, that savepoint and any more + recent savepoints are removed. If code executes additional SQL operations after + a releaseSavepoint() or rollbackToSavepoint() call + removes a savepoint, those operations belong to the most recent remaining + savepoint. (In other words, they belong to the savepoint created most recently + before the removed savepoint.) If no savepoint remains, the operations belong + to the main transaction.

+ +
setSavepoint()rollbackToSavepoint()releaseSavepointflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous + execution mode. + + Dispatched when the operation fails in asynchronous + execution mode.
removeEventListener + + Removes a listener from the EventDispatcher object.typeStringThe type of event. + + listenerFunctionThe listener object to remove. + + useCaptureBooleanfalse + + Specifies whether the listener was registered for the capture phase or the + target and bubbling phases. If the listener was registered for both the capture phase and the + target and bubbling phases, two calls to removeEventListener() are required + to remove both, one call with useCapture() set to true, and another + call with useCapture() set to false. + + + + Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect. + + rollbackToSavepoint + Rolls back any SQL operations since the most recent savepoint or the named + savepoint if a name is specified.when the name parameter value is an empty + string (""). + + ArgumentErrorArgumentErrorWhen the method is called while the SQLConnection + instance isn't connected to a database (the connected property is + false); or if no transaction is currently open (the + inTransaction property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornameStringnullString The name of the savepoint to which the database state should + be rolled back. If no value is provided or if this parameter is null + (the default) then most recent unnamed savepoint (created by a call to + setSavepoint() with no name value) is used. The + name value cannot be an empty string (""). + + responderflash.net:RespondernullResponder An object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the responder + argument is null a rollbackToSavepoint or + error event is dispatched when execution completes. + + + Rolls back any SQL operations since the most recent savepoint or the named + savepoint if a name is specified. + +

Note that if the entire transaction is committed by calling the + commit() method, any changes in the transaction that are not + already rolled back using the rollbackToSavepoint() method are + permanently saved to the database. In addition, calling the rollback() + method permanently discards all changes, regardless of whether individual + savepoints have been released (committed) or rolled back before the transaction + is rolled back.

+ +

If this method is called with no parameters (or with null + for the name parameter), it rolls back all database changes since + the most recent unnamed savepoint (the most recent call to setSavepoint() + with no name parameter value).

+ +

If a value is provided for the name parameter this method + rolls back all the SQL operations performed since the savepoint with the + specified name. If other savepoints have been created more recently than the + specified savepoint, operations performed since those savepoints are rolled + back also.

+ +

Once a savepoint is released or rolled back, that savepoint and any more + recent savepoints are removed. If code executes additional SQL operations after + a releaseSavepoint() or rollbackToSavepoint() call + removes a savepoint, those operations belong to the most recent remaining + savepoint. (In other words, they belong to the savepoint created most recently + before the removed savepoint.) If no savepoint remains, the + operations belong to the main transaction.

+ + +
setSavepoint()releaseSavepoint()rollbackToSavepointflash.events:SQLEventDispatched when the operation completes + successfully. + + Dispatched when the operation completes + successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous + execution mode. + + Dispatched when the operation fails in asynchronous + execution mode.
rollback + Rolls back an existing transaction created using the begin() method, + meaning all changes made by any SQL statements in the transaction are discarded.When the method is called while the SQLConnection + instance isn't connected to a database (the connected property is + false); or if no transaction is currently open (the + inTransaction property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorresponderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null a rollback + or error event is dispatched when execution completes. + + + Rolls back an existing transaction created using the begin() method, + meaning all changes made by any SQL statements in the transaction are discarded. + +

Intermediate savepoints can be marked within a transaction by calling the + setSavepoint() method. Using savepoints you can commit portions + of a transaction by calling the releaseSavepoint() method, or + roll back portions of a transaction by calling rollbackToSavepoint(). + However, calling the rollback() method permanently discards all + changes made in a transaction, regardless of whether individual savepoints have + been released (committed) before the transaction is rolled back.

+ +
begin()commit()setSavepoint()releaseSavepoint()rollbackToSavepoint()rollbackflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous + execution mode. + + Dispatched when the operation fails in asynchronous + execution mode.
setSavepoint + Creates a savepoint, which is like a bookmark within a database transaction.when the name parameter value is an empty + string (""). + + ArgumentErrorArgumentErrorWhen the method is called while the SQLConnection + instance isn't connected to a database (the connected property is + false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrornameStringnullString The name for the savepoint. If no value is provided or + if this parameter is null (the default) then the next call + to releaseSavepoint() or rollbackToSavepoint() with + no name parameter specified commits or rolls back the SQL operations + performed since the unnamed savepoint. +

If the name provided is a duplicate of a previous named savepoint, the next call + to either SQLConnection.releaseSavepoint() or + SQLConnection.rollbackToSavepoint() commits or rolls back changes + made since the most recent savepoint with that name.

+

The name value cannot be an empty string ("").

+ +
responderflash.net:RespondernullResponder An object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the responder + argument is null a setSavepoint or error + event is dispatched when execution completes. + +
+ Creates a savepoint, which is like a bookmark within a database transaction. + A savepoint represents a point within a transaction. The set of SQL operations + performed between savepoints can be committed or rolled back separately from + other operations using the releaseSavepoint() and + rollbackToSavepoint() methods. In this way, using a savepoint + allows you to treat a set of SQL operations as a nested transaction. + +

When the setSavepoint() method is called, if a transaction has + not already been opened (by calling the begin() method), calling + this method begins the transaction and creates a savepoint at the start of the + transaction. If a transaction is already open, calling setSavepoint() + creates a savepoint within the transaction.

+ +

Note that until the entire transaction is committed, any changes are not + permanently saved to the database. If the transaction is started using the + begin() method, you must call the commit() method + to commit the entire transaction. If the transaction is started by calling + setSavepoint() while inTransaction is + false, you can finish the entire transaction either by calling + the commit() method. The transaction also finishes automatically + when you call releaseSavepoint() or rollbackToSavepoint() + for the savepoint that started the transaction.

+ +

You can specify a name for a savepoint by providing a value for the + name parameter. This allows you to to rollback or commit all + changes made since that specific savepoint. If no name is specified + (the default) then an unnamed savepoint is created.

+ +

Once a savepoint is released or rolled back, that savepoint and any more + recent savepoints are removed. If code executes additional SQL operations + after a releaseSavepoint() or rollbackToSavepoint() + call removes a savepoint, those operations belong to the most recent remaining + savepoint. (In other words, they belong to the savepoint created most recently + before the removed savepoint.) If no savepoint remains, the operations belong + to the main transaction.

+ +
begin()releaseSavepoint()rollbackToSavepoint()commit()rollback()setSavepointflash.events:SQLEventDispatched when the operation completes successfully. + + Dispatched when the operation completes successfully.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous + execution mode. + + Dispatched when the operation fails in asynchronous + execution mode.
autoCompact + Indicates whether autocompacting was enabled when the current database + was originally created (the value that was specified for the autoCompact + parameter in the open() or openAsync() call that created the + database).Boolean + Indicates whether autocompacting was enabled when the current database + was originally created (the value that was specified for the autoCompact + parameter in the open() or openAsync() call that created the + database). If this property is true, unused space is removed from the database file + automatically after each write operation, keeping the database file smaller. If the property + is false, the space previously occupied by removed data is left in the database + file and reused when needed. Even when autoCompact is false, you can force the + database to reclaim unused space by calling the compact() method. + +

If the connected property is false, this property + is set to false.

+ +
open()openAsync()
cacheSize + Provides access to the cache size for this connection, which represents the maximum number + of database disk pages that are held in memory at one time.uintWhen an attempt is made to set this + property while the SQLConnection instance isn't connected to a database (the + connected property is false); or if a transaction is currently open (the + inTransaction property is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Provides access to the cache size for this connection, which represents the maximum number + of database disk pages that are held in memory at one time. Each page + uses about 1.5 KB of memory (depending on the value specified for the pageSize + parameter of the open() or openAsync() method call that created the + database). The default cache size is 2000. If an application is executing + UPDATE or DELETE operations that change many rows of a database, + increasing the cache size can improve speed at the cost of increased memory consumption. + + open()openAsync()columnNameStyle + Indicates how column names are reported in the + result of a SELECT statement.StringWhen an attempt is made to set this + property while the SQLConnection instance isn't connected to a database (the + connected property is false). + + IllegalOperationErrorflash.errors:IllegalOperationError + Indicates how column names are reported in the + result of a SELECT statement. + +

The constants defined in the SQLColumnNameStyle class + represent the possible values for this property:

+ +
  • SQLColumnNameStyle.LONG indicates that + column names are returned in the format [table-name]_[column-name].
  • SQLColumnNameStyle.SHORT specifies that column names are given + the format [column-name]. If there are multiple columns with the same name, + only one property with that name is added to the result object.
  • SQLColumnNameStyle.DEFAULT is the default value. When + this value is used, result column names are formatted according to the number of + tables in the SELECT statement that have similar column names. If the + SELECT statement includes only one table, the short name format + [column-name] is used, and if the SELECT + statement includes multiple tables joined together, whenever there is a naming collision + because two column names are identical, the long name format + [table-name]_[column-name] is used for the identically named columns.
+ +
flash.data.SQLColumnNameStyle
connected + Indicates whether the SQLConnection instance has an open connection + to a database file.Boolean + Indicates whether the SQLConnection instance has an open connection + to a database file. + + open()openAsync()close()inTransaction + Indicates whether this connection is currently involved in a transaction.Boolean + Indicates whether this connection is currently involved in a transaction. + + begin()commit()rollback()lastInsertRowID + The last generated row identifier created by a SQL INSERT + statement.Number + The last generated row identifier created by a SQL INSERT + statement. A row identifier is used to uniquely identify a row in a table within + the database. The value is frequently generated by the database. + +

The value is zero if no database is connected or no + INSERT statement has been executed.

+ +

The row identifier for a single SQL INSERT statement execution + can be obtained through the lastInsertRowID property of the SQLResult object + returned by the SQLStatement object's getResult() method (when called after the + SQLStatement dispatches its result event).

+ +

For more information on primary keys and generated row identifiers, + see the "CREATE TABLE" and + "Expressions" sections in the appendix + "SQL support in local databases."

+ +
flash.data.SQLResult.lastInsertRowIDflash.events.SQLUpdateEvent.rowID
pageSize + Indicates the database page size (in bytes) that was specified when the current database + was originally created (the value that was specified for the pageSize + parameter in the open() or openAsync() call that created the + database).uint + Indicates the database page size (in bytes) that was specified when the current database + was originally created (the value that was specified for the pageSize + parameter in the open() or openAsync() call that created the + database). + +

If the connected property is false, this property's + value is 0.

+ +

The page size for a database can be changed (using the open() or openAsync() + methods) until the first table is created in the database.

+ +
open()openAsync()
totalChanges + Contains the total number of data changes that have been made since the + connection to the database was opened.Number + Contains the total number of data changes that have been made since the + connection to the database was opened. In addition to tracking changes + made by INSERT, DELETE, and UPDATE + statements, this value includes changes caused by triggers. + +

When the database connection is closed, the value is + reset to 0. When the SQLConnection instance isn't connected + to a database, the value is 0.

+ +
flash.data.SQLResult.rowsAffected
SQLTriggerSchema + A SQLTriggerSchema instance provides information describing a specific trigger + in a database.flash.data:SQLSchema + A SQLTriggerSchema instance provides information describing a specific trigger + in a database. + + It contains the name of the trigger (the name property), + the name of the associated table (the table property), and the + SQL statement used to create the trigger (the sql property). + +

To obtain trigger schema information for a database, use the + SQLConnection.loadSchema() method to load the schema information, making certain to + use null or SQLTriggerSchema for the type argument's value. + In the resulting SQLSchemaResult instance, the triggers property contains an array + of SQLTriggerSchema instances representing the triggers in the database.

+ +

Generally, developer code does not construct SQLTriggerSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()SQLTriggerSchema + Creates a SQLTriggerSchema instance.databaseStringThe name of the associated database. + + nameStringThe name of the trigger. + + sqlStringThe SQL used to create the trigger. + + tableStringThe name of the trigger's associated table. + + + Creates a SQLTriggerSchema instance. Generally, developer code does not call the SQLTriggerSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + + table + The name of the table on which this trigger is defined, or the name of the view if + the trigger is defined on a view.String + The name of the table on which this trigger is defined, or the name of the view if + the trigger is defined on a view. + +
SQLStatement + A SQLStatement instance is used to execute a SQL statement against a local SQL database + that is open through a SQLConnection instance.flash.events:EventDispatcher + A SQLStatement instance is used to execute a SQL statement against a local SQL database + that is open through a SQLConnection instance. + +

A SQLStatement instance is linked to a SQLConnection instance by setting the SQLConnection instance as the + value of the SQLStatement instance's sqlConnection property. The text property + is populated with the actual text of the SQL statement to execute. If necessary, SQL statement parameter + values are specified using the parameters property, and the statement is + carried out by calling the execute() method.

+ +

For a complete description of the SQL dialect supported in local SQL databases, see the appendix + SQL support in local databases.

+ +

In asynchronous execution mode, the execute() and next() methods are executed + in the background, and the runtime dispatches events to registered event listeners or to a specified Responder + instance when the operations complete or fail. + In synchronous mode, the methods are executed on the main application thread, meaning that no other code executes + until the database operations are completed. In addition, in synchronous mode if the methods fail the runtime + throws an exception rather than dispatching an error event.

+ +
flash.data.SQLConnectionerror + Dispatched when an error occurs during an operation.flash.events.SQLErrorEvent.ERRORflash.events.SQLErrorEvent + Dispatched when an error occurs during an operation. + + execute()next()result + Dispatched when an execute() or + next() method call's operation completes successfully.flash.events.SQLEvent.RESULTflash.events.SQLEvent + Dispatched when an execute() or + next() method call's operation completes successfully. Once the + result event is dispatched the getResult() + method can be called to retrieve statement results. + + + execute()next()getResult()SQLStatement + Creates a SQLStatement instance.If the constructor is called from any sandbox outside + of the main application sandbox. + + SecurityErrorSecurityError + Creates a SQLStatement instance. + + cancel + Cancels execution of this statement. + Cancels execution of this statement. Like SQLConnection.cancel() + this method is used to stop a long running query or to cancel a query that is not + yet complete. However, unlike SQLConnection.cancel() this method only cancels the + single statement. If the statement is not currently executing, calling this method does + nothing. + +

No events are dispatched in direct response to the completion of the cancel() + operation. However, once the cancel() operation completes and statement execution + is cancelled, the SQLStatement instance dispatches an error event indicating that + the statement execution (the execute() or next() call) did not complete. + Alternatively, if a value was specified for the responder parameter of the + execute() or next() call, the specified fault handler method is called. + In either case, the SQLError instance that's passed to the listeners has an errorID + property with a value of 3118 (Operation aborted).

+ +
clearParameters + Clears all current parameter settings. + Clears all current parameter settings. + + parametersexecute + Executes the SQL in the text property against the database that + is connected to the SQLConnection object in the sqlConnection + property.If the text property is null + or contains an empty string (""); if the sqlConnection property is + not set; if the SQLConnection instance assigned to the sqlConnection property is not + connected; or if the statement is currently executing. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorprefetchint-1When the statement's text property is a + SELECT statement, this value indicates how many rows are + returned at one time by the statement. + The default value is -1, indicating that all the result rows are returned + at one time. This parameter is used in conjunction with the next() + method to divide large result sets into smaller sets of data. This can improve + a user's perception of application performance by returning initial results more + quickly and dividing result-processing operations. + +

When the SQL statement is a SELECT query and a prefetch + argument greater than zero is specified, the statement is considered to be executing + until the entire result set is returned or either the SQLStatement.cancel() + or SQLConnection.cancel() method is called. Note that because the number of + rows in a result set is unknown at execution time, the database cursor must move beyond + the last row in the result set before the statement is considered complete. When a + prefetch argument is specified in an execute() call, at least + one row more than the total number of rows in the result set must be requested + (either through a prefetch value that's larger than the number of rows in the + result set, or through subsequent calls to the next() method) before + the resulting SQLResult instance's complete property is true.

+ +
responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. In asynchronous execution mode, if the + responder argument is null + a result or error event is dispatched when execution completes. + +
+ Executes the SQL in the text property against the database that + is connected to the SQLConnection object in the sqlConnection + property. + +

If the responder argument is not null the specified + Responder object designates methods that are called to handle the results + of the operation. If the responder argument is null, + in asynchronous execution mode a + result event is dispatched if the operation is successful, or an + error event is dispatched if the operation fails.

+ +

To access the results of a statement, such as the result rows of a SELECT + statement or the database generated primary key of an INSERT statement, call + the getResult() method. The results are available immediately after the + statement executes in synchronous mode, and when the result event + is dispatched in asynchronous mode.

+ +

Every statement must be prepared (compiled) before it can be executed. The first time + a SQLStatement instance's execute() method is called, the statement is + prepared by the runtime. Once a statement is prepared it does not need to be prepared + again unless the text property changes. Setting one or more parameter values + does not require the statement to be prepared again.

+ +
The following example demonstrates executing a SQLStatement, + using event listeners to determine when the statement execution completes + or fails. + +var conn:SQLConnection; +var dbStatement:SQLStatement; + +function init():void +{ + conn = new SQLConnection(); + conn.addEventListener(SQLEvent.OPEN, connOpenHandler); + + dbStatement = new SQLStatement(); + dbStatement.sqlConnection = conn; + dbStatement.text = "SELECT id, name, ssn FROM employees"; + + var dbFile:File = new File(File.separator + "employee.db"); + conn.open(dbFile); +} + +function connOpenHandler(event:SQLEvent):void +{ + dbStatement.addEventListener(SQLEvent.RESULT, resultHandler); + dbStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler); + dbStatement.execute(); +} + +function resultHandler(event:SQLEvent):void +{ + var result:SQLResult = dbStatement.getResult(); + if (result != null) + { + var numRows:int = result.data.length; + for (var i:int = 0; i < numRows; i++) + { + var row:Object = result.data[i]; + trace("id:", row.id, ", name:", row.name, ", ssn:", row.ssn); + } + } +} + +function errorHandler(event:SQLErrorEvent):void +{ + trace("An error occured while executing the statement."); +} + The following example demonstrates executing a SQLStatement, + using a Responder object to indicate which functions are called when the statement + execution completes or fails. + +var conn:SQLConnection; +var dbStatement:SQLStatement; +var employeeResponder:Responder; + +function init():void +{ + conn = new SQLConnection(); + conn.addEventListener(SQLEvent.OPEN, connOpenHandler); + + dbStatement = new SQLStatement(); + dbStatement.sqlConnection = conn; + dbStatement.text = "SELECT id, name, ssn FROM employees"; + + var dbFile:File = new File(File.separator + "employee.db"); + conn.open(dbFile); +} + +function connOpenHandler(event:SQLEvent):void +{ + employeeResponder = new Responder(resultHandler, errorHandler); + dbStatement.execute(-1, employeeResponder); +} + +function resultHandler(result:SQLResult):void +{ + if (result != null) + { + var numRows:int = result.data.length; + for (var i:int = 0; i < numRows; i++) + { + var row:Object = result.data[i]; + trace("id:", row.id, ", name:", row.name, ", ssn:", row.ssn); + } + } +} + +function errorHandler(error:SQLError):void +{ + trace("An error occured while executing the statement."); +} +
next()getResult()resultflash.events:SQLEventDispatched when the statement execution completes + successfully, or when a prefetch argument value is specified and a SELECT + statement returns one or more rows of data. + + Dispatched when the statement execution completes + successfully, or when a prefetch argument value is specified and a SELECT + statement returns one or more rows of data.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
getResult + Provides access to a SQLResult object containing the results of the statement + execution, including any result rows from a SELECT statement, and other + information about the statement execution for all executed statements.A SQLResult object containing the result of a call to the execute() + or next() method. + + flash.data:SQLResult + Provides access to a SQLResult object containing the results of the statement + execution, including any result rows from a SELECT statement, and other + information about the statement execution for all executed statements. + In asynchronous execution mode, the result information is not available until the + result event is dispatched. + +

When a SELECT statement is executed, if the execute() + method is called with the default prefetch argument of -1, the returned + SQLResult object contains the entire result set of the query.

+ +

When a prefetch argument is specified for an execute() or next() + method call, the getResult() method behaves as a first-in, first-out queue + of results. Each time the result event is dispatched, a new SQLResult object + is added to the queue. Each time the getResult() method is called, the earliest + SQLResult object (the one that was added to the queue first) is returned and removed + from the queue. When there are no more SQLResult objects left in the queue, getResult() + returns null.

+ +

Note that unless they are removed by calling getResult(), + SQLResult objects remain in the queue. For example, if the execute() + method is called multiple times without calling getResult(), the + SQLResult objects associated with each execute() call remains in + the queue.

+ +
execute()next()result event
next + Retrieves the next portion of a SELECT statement's result set.When the method is called while the statement is not + currently executing (the executing property is false). + + IllegalOperationErrorflash.errors:IllegalOperationErrorif the operation fails in synchronous execution mode. + + SQLErrorflash.errors:SQLErrorprefetchint-1When the statement's text property is a SELECT + statement, this value indicates how many rows are returned at one time by + the statement. + The default value is -1, indicating that all the result rows are returned + at one time. This can improve + a user's perception of application performance by returning initial results more + quickly and dividing result-processing operations. + + responderflash.net:RespondernullAn object that designates methods to be called when + the operation succeeds or fails. If the responder argument is null + a result or error event is dispatched when execution completes. + + + Retrieves the next portion of a SELECT statement's result set. + If there are no more rows in the result set, a result event is dispatched but + no additional SQLResult object is added to the getResult() queue. + +

In asynchronous execution mode, if the responder argument is not + null the specified + Responder object indicates the methods that are called to handle the results + of the operation. + If the responder argument is null, a + result event is dispatched if the operation is successful, or an + error event is dispatched if the operation fails.

+ +

This method can only be called when the statement is still executing. + When the statement is a SELECT query and a prefetch + argument greater than zero is specified, the statement is considered to be executing + until the entire result set is returned or either the + SQLStatement.cancel() or SQLConnection.cancel() + method is called.

+ +
The following example demonstrates executing a SQLStatement, + explicitly indicating that only the first 10 rows of the result set are + to be returned the first time the result returns. The code checks the + complete property of the SQLResult and, if not all the rows + have been retrieved, calls the next() method. + +var conn:SQLConnection; +var dbStatement:SQLStatement; + +function init():void +{ + conn = new SQLConnection(); + conn.addEventListener(SQLEvent.OPEN, connOpenHandler); + + dbStatement = new SQLStatement(); + dbStatement.sqlConnection = conn; + dbStatement.text = "SELECT id, name, ssn FROM employees"; + + var dbFile:File = new File(File.separator + "employee.db"); + conn.open(dbFile); +} + +function connOpenHandler(event:SQLEvent):void +{ + dbStatement.addEventListener(SQLEvent.RESULT, resultHandler); + dbStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler); + dbStatement.execute(10); +} + +function resultHandler(event:SQLEvent):void +{ + var result:SQLResult = dbStatement.getResult(); + if (result != null) + { + var numRows:int = result.data.length; + for (var i:int = 0; i < numRows; i++) + { + var row:Object = result.data[i]; + trace("id:", row.id, ", name:", row.name, ", ssn:", row.ssn); + } + if (!result.complete) + { + dbStatement.next(10); + } + } +} + +function errorHandler(event:SQLErrorEvent):void +{ + trace("An error occured while executing the statement."); +} +
execute()resultflash.events:SQLEventDispatched when the statement execution completes + successfully, or when a prefetch argument value is specified and the + next() call returns one or more rows of data. + + Dispatched when the statement execution completes + successfully, or when a prefetch argument value is specified and the + next() call returns one or more rows of data.errorflash.events:SQLErrorEventDispatched when the operation fails in asynchronous execution mode. + + Dispatched when the operation fails in asynchronous execution mode.
executing + Indicates whether the statement is currently executing.Boolean + Indicates whether the statement is currently executing. + +

This property is true if execute() has been called and + not all of the results have been returned from the database.

+ +
execute()
itemClass + Indicates a class (data type) that is used for each + row returned as a result of the statement's execution.Class + Indicates a class (data type) that is used for each + row returned as a result of the statement's execution. + + + +

By default, each row returned by a SELECT statement is + created as an Object instance, with the result set's column names as the + names of the properties of the object, and the value of each column as the + value of its associated property.

+ +

By specifying a class for the itemClass property, + each row returned by a SELECT statement executed by this SQLStatement instance + is created as an instance of the designated class. Each property of the itemClass instance is + assigned the value from the column with the same name as the property.

+ +

Any class assigned to this property must have a constructor + that does not require any parameters. In addition, the class must + have a single property for each column returned by the SELECT statement. + It is considered an error if a column in the SELECT list + does not have a matching property name in the itemClass class.

+ +
The following code demonstrates using the itemClass property + to have the runtime create instances of a custom class from SQL SELECT statement + results. + +// Employee class definition +package +{ + public class Employee + { + public var name:String; + public var ssn:String; + public var id:uint; + public override function toString():String + { + return "id: "+ id.toString() + " name: " + name + " ssn: " + ssn; + } + } +} + + +// using the Employee class as SQLStatement.itemClass +var conn:SQLConnection; +var dbStatement:SQLStatement; + +function init():void +{ + conn = new SQLConnection(); + conn.addEventListener(SQLEvent.OPEN, connOpenHandler); + + dbStatement = new SQLStatement(); + dbStatement.sqlConnection = conn; + dbStatement.text = "SELECT id, name, ssn FROM employees"; + dbStatement.itemClass = Employee; + + var dbFile:File = new File(File.separator + "employee.db"); + conn.open(dbFile); +} + +function connOpenHandler(event:SQLEvent):void +{ + dbStatement.addEventListener(SQLEvent.RESULT, resultHandler); + dbStatement.execute(); +} + +function resultHandler(event:SQLEvent):void +{ + var result:SQLResult = dbStatement.getResult(); + if (result != null) + { + var emp:Employee; + var numRows:int = result.data.length; + for (var i:int = 0; i < numRows; i++) + { + emp = result.data[i]; + trace(emp.toString()); + } + } +} +
flash.data.SQLResult.data
parameters + Serves as an associative array to which you add values for the + parameters specified in the SQL statement's + text property.Object + Serves as an associative array to which you add values for the + parameters specified in the SQL statement's + text property. The array keys are + the names of the parameters. If an unnamed parameter is specified + in the statement text, its key is the index of the parameter. + +

Within the text of a SQL statement, a parameter is indicated with + one of the following characters: "?", ":", or "@".

+ +

The ":" and "@" tokens indicate a named parameter; the characters following + the token designate the name of the parameter.

+ +

For example, in the following SQL statement, a parameter named firstName + is specified using the ":" character:

+ +
SELECT FROM employees WHERE firstName = :firstName
+ +

The "?" token indicates an indexed (numbered) parameter; each parameter + is automatically given an index according to the sequence of parameters + in the statement text. Parameter index values are zero based. In other words, the first parameter's index is 0.

+ +

Parameters are used to allow for typed substitution of + values that are unknown at the time the SQL statement is constructed. + The use of parameters is the only way to guarantee the storage class for + a value passed in to the database. When parameters are not used, all values are + converted from their text representation to a storage class based on the + associated column's type affinity. For more information on storage classes and + column affinity, see the + "Data type support" section + in the appendix + "SQL support in local databases".

+ +

Parameters are also used as a security measure to prevent a malicious technique known + as a SQL injection attack. In a SQL injection attack, a user enters SQL code in a + user-accessible location (for example, a data entry field). If application code constructs + a SQL statement by directly concatenating user input into the SQL text, the user-entered + SQL code is executed against the database. The following listing shows an + example of concatenating user input into SQL text. Do not use this + technique:

+ + + // assume the variables "username" and "password" + // contain user-entered data + var sql:String = + "SELECT userId " + + "FROM users " + + "WHERE username = '" + username + "' " + + " AND password = '" + password + "'"; + var statement:SQLStatement = new SQLStatement(); + statement.text = sql; + + + + +

Using statement parameters instead of concatenating user-entered values into + a statement's text prevents a SQL injection attack, because the parameter values are + treated explicitly as substituted values, rather than becoming part of the literal statement + text. The following is the recommended alternative to the previous listing:

+ + + // assume the variables "username" and "password" + // contain user-entered data + var sql:String = + "SELECT userId " + + "FROM users " + + "WHERE username = :username " + + " AND password = :password"; + var statement:SQLStatement = new SQLStatement(); + statement.text = sql; + // set parameter values + statement.parameters[":username"] = username; + statement.parameters[":password"] = password; + + + + +

All parameter values must be set before + the statement is executed. Parameter values specified in the parameters + array are bound (that is, + combined with the statement text) when the execute() method is called. Once + execute() has been called, any + subsequent changes to the values are not applied to the executing + statement. However, on a subsequent execute() call the changed + values are used. If the statement text includes a parameter that doesn't have a value specified + in the parameters property, an error occurs.

+ +

To clear all the parameter values from the parameters property, + use the clearParameters() method.

+ +
The following example shows the use of a named parameter, + :firstName, in a SQL statement. + +// employees is a SQLStatement instance +employees.text = "SELECT FROM employees WHERE first = :firstName"; +employees.parameters[":firstName"] = "Sam"; +employees.execute(); + The following example shows the use of an unnamed parameter + in a SQL statement. + +// employees is a SQLStatement instance +employees.text = "SELECT FROM employees WHERE first = ?"; +employees.parameters[0] = "Sam"; +employees.execute(); +
textclearParameters()
sqlConnection + The SQLConnection object that manages the connection to the database or databases on which + the statement is executed.flash.data:SQLConnectionWhen an attempt is made to change the value + of this property while the statement is executing. + + IllegalOperationErrorflash.errors:IllegalOperationError + The SQLConnection object that manages the connection to the database or databases on which + the statement is executed. + + text + The actual SQL text of the statement.StringWhen an attempt is made to change the text + property while the statement is executing. + + IllegalOperationErrorflash.errors:IllegalOperationError + The actual SQL text of the statement. + +

The text can be any supported SQL. For a complete description of the + SQL dialect supported in local SQL databases, see the appendix + "SQL support in local databases".

+ +
SQLMode + This class contains the constants that represent the possible values for the + openMode parameter of the SQLConnection.open() and + SQLConnection.openAsync() methods.Object + This class contains the constants that represent the possible values for the + openMode parameter of the SQLConnection.open() and + SQLConnection.openAsync() methods. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()CREATE + Indicates that the connection is opened for updates, and a database + file is created if the specified file doesn't exist.createString + Indicates that the connection is opened for updates, and a database + file is created if the specified file doesn't exist. In this + mode reading and writing are allowed to the database. If the database + does not exist one is created before the operation completes. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()READ + Indicates that the connection is opened in read-only mode.readString + Indicates that the connection is opened in read-only mode. In this + mode writes are not allowed to the database. If the database does not + exist the open operation fails. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()UPDATE + Indicates that the connection is opened for updates but a + new database file is not created if the specified file doesn't exist.updateString + Indicates that the connection is opened for updates but a + new database file is not created if the specified file doesn't exist. In this + mode reading and writing are allowed to the database. If the database + does not exist the open operation fails. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()EncryptedLocalStore + The EncryptedLocalStore class provides a persistent, encrypted data storage mechanism.Object + The EncryptedLocalStore class provides a persistent, encrypted data storage mechanism. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the EncryptedLocalStore.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

AIR provides an encrypted local store (ELS) for each AIR application installed on + a user's computer. This lets you save and retrieve data that is + stored on the user’s local hard drive in an encrypted format that + cannot easily be deciphered by other users. A separate encrypted + local store is used for each AIR application, and each AIR application + uses a separate encrypted local store for each user account on the computer.

+ +

Use the encrypted local store to cache information + that must be secured, such as login credentials for web services. + The ELS is appropriate for storing information that must be kept + private from other users. It does not, however, protect the data + from other processes run under the same user account. It is thus + not appropriate for protecting secret application data, such as DRM + or encryption keys.

+ +

AIR uses + DPAPI on Windows, KeyChain on Mac OS, and KeyRing or KWallet on Linux + to associate the encrypted local store to each application and user. + The encrypted local store uses AES-CBC 128-bit encryption.

+ +

Information in the encrypted local store is only available to + AIR application content in the application security sandbox.

+ +

If you update an AIR application, the updated version retains + access to any existing data in the encrypted local store unless:

+ +
  • The items were added with the stronglyBound parameter + set to true
  • The existing and update versions are both published prior + to AIR 1.5.3 and the update is signed with a migration signature
+ +

Limitations of the encrypted local store

+

The + data in the encrypted local store is protected by the user’s operating + system account credentials. Other entities cannot access the data + in the store unless they can login as that user. However, the data + is not secure against access by other applications run by an authenticated + user. Thus, data that your application + may want to keep secret from users, such as keys used for licensing + or digital rights management, is not secure. The ELS is not + an appropriate location for storing such information. It is only + an appropriate place for storing a user’s private data, such as + passwords.

+ +

Data in the ELS can be lost for a variety of reasons. + For example, the user could uninstall the application and delete + the encrypted file. Or, the publisher ID could be changed as a result + of an update. Thus the ELS should be treated as a private cache, + not permanent data storage.

+ +

The stronglyBound parameter + is deprecated and should not be set to true. Setting + the parameter to true does not provide any additional + protection for data. At the same time, access to the data is lost + whenever the application is updated — even if the publisher ID stays + the same.

+ +

The encrypted local store may perform more slowly + if the stored data exceeds 10MB.

+ +

When you uninstall an AIR + application, the uninstaller does not delete data stored in the + encrypted local store.

+ +

The best practices for using the ELS + include:

+ +
  • Use the ELS to store sensitive user data + such as passwords (setting stronglyBound to false)
  • Do not use the ELS to store applications secrets such as + DRM keys or licensing tokens
  • Provide a way for your application to recreate the data stored + in the ELS if the ELS data is lost. For example, by prompting the + user to re-enter their account credentials when necessary.
  • Do not use the stronglyBound parameter.
  • If you do set stronglyBound to true, + do not migrate stored items during an update. Recreate the data + after the update instead.
  • Only store relatively small amounts of data. For large amounts + of data, use an AIR SQL database with encryption.
+ +

Items in the encrypted local store are identified with a string. All items are + stored as byte array data.

+ +

Encrypted local store data is put in a subdirectory of the user's application data directory; + the subdirectory path is Adobe/AIR/ELS/ followed by the application ID.

+ +
The following code stores a string in the encrypted local store, retrieves it, and then deletes it: + +var str:String = "Bob"; +var bytes:ByteArray = new ByteArray(); +bytes.writeUTFBytes(str); +EncryptedLocalStore.setItem("firstName", bytes); + +var storedValue:ByteArray = EncryptedLocalStore.getItem("firstName"); +trace(storedValue.readUTFBytes(storedValue.length)); // "Bob" + +EncryptedLocalStore.removeItem("firstName"); +
getItem + The data corresponding to the specified name.The name value is null or an empty string. + + ArgumentErrorArgumentErrorThe ByteArray data. If there is no data for the provided name, + the method returns null. + + flash.utils:ByteArraynameStringThe name of the item in the encrypted local store. + + + The data corresponding to the specified name. + +

If an item does not exist by the specified name, this method returns null.

+ +
removeItem + Removes the item with the given name from the encrypted local store.The name value is null or an empty string. + + ArgumentErrorArgumentErrornameStringThe name of the item in the encrypted local store. + + + Removes the item with the given name from the encrypted local store. + + reset + Clears the entire encrypted local store, deleting all data. + Clears the entire encrypted local store, deleting all data. + + setItem + Stores a ByteArray object under the specified name.The name value is null or an empty string. + + + ArgumentErrorArgumentErrornameStringThe name of the item in the encrypted local store. + + dataflash.utils:ByteArrayThe data. + + stronglyBoundBooleanfalse(deprecated) The stronglyBound parameter should + be set to false (the default value). If set to true, the stored item + cannot be retrieved if any application files are altered. For example,if a user installs an + update of your application, the updated application cannot read any strongly bound data that + was previously written to the encrypted local store. + + + Stores a ByteArray object under the specified name. + + isSupported + The isSupported property is set to true if the + EncryptedLocalStore class is supported on the current platform, otherwise it is + set to false.BooleanReports whether the encrypted local store is available on the client system. + + + The isSupported property is set to true if the + EncryptedLocalStore class is supported on the current platform, otherwise it is + set to false. + +
SQLIndexSchema + A SQLIndexSchema instance provides information describing a specific index + in a database.flash.data:SQLSchema + A SQLIndexSchema instance provides information describing a specific index + in a database. + + The available information includes the name of the associated table + (the table property), the + SQL statement used to create the index (the sql property), + and the name of the index (the name property). + +

To obtain index schema information for a database, use the + SQLConnection.loadSchema() method to load the schema information, making certain to + use null or SQLIndexSchema for the type argument's value. + In the resulting SQLSchemaResult instance, the indices property contains an array + of SQLIndexSchema instances representing the indices in the database.

+ +

Generally, developer code does not construct SQLIndexSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()SQLIndexSchema + Creates a SQLIndexSchema instance.databaseStringThe name of the associated database. + + nameStringThe name of the index. + + sqlStringThe SQL statement used to create this index. + + tableStringThe name of the table to which this index is attached. + + + Creates a SQLIndexSchema instance. Generally, developer code does not call the SQLIndexSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + + flash.data.SQLConnection.getSchemaResult()flash.data.SQLSchemaResult.indicestable + The name of the table to which this index is attached.String + The name of the table to which this index is attached. + +
SQLTableSchema + A SQLTableSchema instance provides information describing a specific table + in a database.flash.data:SQLSchema + A SQLTableSchema instance provides information describing a specific table + in a database. + + It contains the name of the table (the name property), the + SQL statement used to create the table (the sql property), and + information about the table's columns (the columns property). + +

To obtain table schema information for a database, use the + SQLConnection.loadSchema() method to load the schema information, making certain to + use null or SQLTableSchema for the type argument's value. + In the resulting SQLSchemaResult instance, the tables property contains an array + of SQLTableSchema instances representing the tables in the database.

+ +

Generally, developer code does not construct SQLTableSchema instances directly.

+ +
flash.data.SQLConnection.loadSchema()flash.data.SQLColumnSchemaSQLTableSchema + Creates a SQLTableSchema instance.databaseStringThe name of the associated database. + + nameStringThe name of the table. + + sqlStringThe SQL statement used to create the table. + + columnsArrayArray of SQLColumnSchema instances describing this table's columns. + + + Creates a SQLTableSchema instance. Generally, developer code does not call the SQLTableSchema + constructor directly. To obtain schema information for a database, call the + SQLConnection.loadSchema() method. + + flash.data.SQLConnection.getSchemaResult()flash.data.SQLSchemaResult.tablescolumns + An array of SQLColumnSchema instances containing schema information for this table's columns.Array + An array of SQLColumnSchema instances containing schema information for this table's columns. + If the SQlConnection.loadSchema() call indicates that column information + is excluded from the result, the columns property is an empty array + (an array whose length property is 0). + + flash.data.SQLColumnSchemaflash.data.SQLConnection.loadSchema()
SQLResult + The SQLResult class provides access to data returned in response to the execution of a + SQL statement (a SQLStatement instance).Object + The SQLResult class provides access to data returned in response to the execution of a + SQL statement (a SQLStatement instance). + +

The SQLResult instance for a SQL statement is accessed by calling the + SQLStatement.getResult() method or + as an argument passed to the result handler of a Responder instance specified in a call to + SQLStatement.execute() or SQLStatement.next(). Generally, developer + code does not construct SQLResult instances directly.

+ +

You use a SQLResult object to access the rows of data returned from a + SELECT statement (using the data property), to get + row identifier information for an INSERT statement (using the + lastInsertRowID property), to determine the number of rows affected + by an INSERT, UPDATE, or DELETE statement + (using the rowsAffected property), or to determine whether there are + additional SELECT result rows that haven't been retrieved (using the + complete property).

+ +
flash.data.SQLStatement.getResult()flash.data.SQLStatement.execute()flash.data.SQLStatement.next()SQLResult + Creates a SQLResult instance.dataArraynullThe array of rows returned from the execution of a statement. If + the statement doesn't return any rows this value should be null. + + rowsAffectedNumber0Indicates how many rows the executed statement affected. + + completeBooleantrueIndicates whether there are additional rows that can + be fetched or whether all data has been returned. + + rowIDNumber0If the statement was a SQL INSERT operation this is the new + unique identifier for the row. + + + Creates a SQLResult instance. Generally, developer code does not call the SQLResult + constructor directly. To retrieve a SQLResult instance associated with a particular SQLStatement + instance, call the instance's getResult() method. A SQLResult + instance is also passed as an argument to the result handler function when + a Responder instance is specified for an execute() or next() + method call. + + complete + Indicates whether all the resulting data from a statement execution has been returned.Boolean + Indicates whether all the resulting data from a statement execution has been returned. + +

When a statement returns one or more rows this property indicates + whether all of the rows have been returned. When a SQLStatement object's execute() + method is called with a prefetch argument value, only the specified number of + rows of the resulting + data are returned in the SQLResult object's data property. Subsequent calls + to SQLStatement.next() cause additional data to become available. This property + is used to determine when the final results have been returned.

+ +

Note that because the number of rows is unknown at execution time, the database cursor must move beyond + the last row before a statement's execution is considered complete. When the + SQLStatement.execute() method is called with a prefetch argument, at least one + row more than the total number of rows in the result set must be requested before + the resulting SQLResult instance's complete property is true.

+ +
flash.data.SQLStatement.execute()flash.data.SQLStatement.next()
data + The data returned as a result of the statement execution, specifically when + a SQL SELECT statement is executed.Array + The data returned as a result of the statement execution, specifically when + a SQL SELECT statement is executed. + +

When a statement returns one or more rows this property is an array containing objects + that represent the rows of result data. Each object in the array has + property names that correspond to the result data set's column names.

+ +

For example, suppose you execute the following SQL SELECT statement:

+ + + SELECT lastName, firstName + FROM employees + + +

Assuming the employees table contains 10 rows, the + SQLResult.data property is an Array with 10 elements. Each element + is an object with two properties, lastName and firstName.

+ +

The situation is more complex when you are using a SELECT statement + with a complex result column, such as an aggregate function. For example, + suppose you execute the following SQL:

+ + + SELECT departmentId, SUM(salary) + FROM employees + GROUP BY departmentId + + +

In the results from this statement, each object in the data Array has + two properties named departmentId and SUM(salary). However, + "SUM(salary)" is not a valid identifier. If you are using a computed column such as an + aggregate or other function, specify an alias for the computed column in your SQL + statement. The alias is used as the property name in the result data objects. For + example, consider this alternative to the previous statement:

+ + + SELECT departmentId, SUM(salary) AS salarySubtotal + FROM employees + GROUP BY departmentId + + +

In this statement's data array, the result objects have two + properties named departmentId and salarySubtotal.

+ +

The data property is always an Array regardless of how many rows + and columns are in the result set. For example, the following SELECT statement + results in one row and one column, which is essentially a single value:

+ + + SELECT COUNT(~~) AS numEmployees + FROM employees + + +

After executing the query the data property contains an Array object + with one element. That element is an object with a single property, + numEmployees.

+ +

If there are duplicate column names in the result data, for example if the + SELECT statement includes an two different id columns + from two different tables, the duplicate names are given property names according + to the value of the SQLConnection.columnNameStyle property. By default, + each column's name is used as the property name, but if there is are multiple columns + in the result set with the same name, the long name format + [table-name]_[column-name] is used for the identically named columns. + This behavior can be changed by setting the SQLConnection.columnNameStyle + property.

+ +

By default the objects in the data Array are Object instances. + However, by setting the value of the SQLStatement.itemClass property + to a class, the data Array elements are created as instances of + that class instead. For every column in the result data set, the + itemClass class must have a property whose name exactly matches the + column name.

+ +

If a statement does not return any data this property is null. + This is the case if the statement is not a SELECT statement, or if + it is a SELECT statement that returns 0 rows.

+ +
The following code demonstrates using the itemClass property + to have the runtime create instances of a custom class from SQL SELECT statement + results. + +// Employee class definition +package +{ + public class Employee + { + public var name:String; + public var ssn:String; + public var id:uint; + public override function toString():String + { + return "id: "+ id.toString() + " name: " + name + " ssn: " + ssn; + } + } +} + + +// using the Employee class as SQLStatement.itemClass +var conn:SQLConnection; +var dbStatement:SQLStatement; + +function init():void +{ + conn = new SQLConnection(); + conn.addEventListener(SQLEvent.OPEN, connOpenHandler); + + dbStatement = new SQLStatement(); + dbStatement.sqlConnection = conn; + dbStatement.text = "SELECT id, name, ssn FROM employees"; + dbStatement.itemClass = Employee; + + var dbFile:File = new File(File.separator + "employee.db"); + conn.open(dbFile); +} + +function connOpenHandler(event:SQLEvent):void +{ + dbStatement.addEventListener(SQLEvent.RESULT, resultHandler); + dbStatement.execute(); +} + +function resultHandler(event:SQLEvent):void +{ + var result:SQLResult = dbStatement.getResult(); + if (result != null) + { + var emp:Employee; + var numRows:int = result.data.length; + for (var i:int = 0; i < numRows; i++) + { + emp = result.data[i]; + trace(emp.toString()); + } + } +} +
SQLConnection.columnNameStyleSQLStatement.itemClass
lastInsertRowID + The last generated row identifier generated by a SQL INSERT + statement.Number + The last generated row identifier generated by a SQL INSERT + statement. + +

The value is 0 if the executed statement was not an + INSERT statement.

+ +

A row identifier is used to uniquely identify a row in a table within + the database. The value is frequently generated by the database.

+ +

For more information about primary keys and generated row identifiers, + see the "CREATE TABLE" and + "Expressions" sections in the appendix + "SQL support in local databases."

+ +
flash.data.SQLConnection.lastInsertRowIDflash.events.SQLUpdateEvent.rowID
rowsAffected + Indicates how many rows were affected by the operation.Number + Indicates how many rows were affected by the operation. + Only changes that are directly specified by an INSERT, + UPDATE, or DELETE statement are counted. + +

Auxiliary changes caused by triggers are not counted. + Use the SQLConnection.totalChanges property to find the total + number of changes including changes caused by triggers.

+ +

Note that when the related SQL operation is a DELETE statement + with no WHERE clause (that is, the statement deletes all the rows in the table), + the rowsAffected property is always 0, regardless of the number of rows + that were deleted. If you need to know the number of rows that are deleted, you can + include the WHERE clause WHERE 1 = 1, in which case all + the rows are deleted, and the rowsAffected property accurately + reflects the number of rows that were deleted. However, depending on the number of + rows being deleted, doing so may have a negative impact on the statement's performance.

+ +
flash.data.SQLConnection.totalChanges
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.desktop.xml b/language-server/playerglobal_docs/flash.desktop.xml new file mode 100644 index 0000000..f5bbd61 --- /dev/null +++ b/language-server/playerglobal_docs/flash.desktop.xml @@ -0,0 +1,2433 @@ +flash.desktopNativeProcess + + The NativeProcess class provides command line integration and general launching capabilities.flash.events:EventDispatcher + The NativeProcess class provides command line integration and general launching capabilities. The NativeProcess + class lets an AIR application execute native processes on the host operating system. The AIR applcation + can monitor the standard input (stdin) and standard output (stdout) stream of the process as well as the + process's standard error (stderr) stream. + +

The NativeProcess class and its capabilities are only available to AIR applications installed with a + native installer (extended desktop profile applications). When debugging, you can pass the + -profile extendedDesktop argument to ADL to enable the NativeProcess functionality. + At runtime, you can check the NativeProcess.isSupported property to to determine whether + native process communication is supported.

+ +

AIR profile support: This feature is supported + on applications that are deployed to desktop operating systems via native installers. + The feature is not supported on mobile devices or on AIR for TV devices. You can test + for support at run time using the NativeProcess.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

AIR applications installed with a native installer (extended desktop profile applications) can also use the + File.openWithDefaultApplication to open an application. However, the NativeProcess class + provides direct access to the standard input, standard output, and standard error pipes.

+ +

Note: AIR for TV applications using the extendedTV profile can use ActionScript native extensions + to execute native processes.

+ +
The following example checks to see if native process communication is supported on + the machine. If it is, the application sets up event listeners for the native process and launches + the test.py file in the main application directory). : + +package +{ + import flash.display.Sprite; + import flash.desktop.NativeProcess; + import flash.desktop.NativeProcessStartupInfo; + import flash.events.Event; + import flash.events.ProgressEvent; + import flash.events.IOErrorEvent; + import flash.events.NativeProcessExitEvent; + import flash.filesystem.File; + + public class NativeProcessExample extends Sprite + { + public var process:NativeProcess; + + public function NativeProcessExample() + { + if(NativeProcess.isSupported) + { + setupAndLaunch(); + } + else + { + trace("NativeProcess not supported."); + } + } + + public function setupAndLaunch():void + { + var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo(); + var file:File = File.applicationDirectory.resolvePath("test.py"); + nativeProcessStartupInfo.executable = file; + + var processArgs:Vector.<String> = new Vector.<String>(); + processArgs[0] = "foo"; + nativeProcessStartupInfo.arguments = processArgs; + + process = new NativeProcess(); + process.start(nativeProcessStartupInfo); + process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData); + process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData); + process.addEventListener(NativeProcessExitEvent.EXIT, onExit); + process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError); + process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError); + } + + public function onOutputData(event:ProgressEvent):void + { + trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable)); + } + + public function onErrorData(event:ProgressEvent):void + { + trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable)); + } + + public function onExit(event:NativeProcessExitEvent):void + { + trace("Process exited with ", event.exitCode); + } + + public function onIOError(event:IOErrorEvent):void + { + trace(event.toString()); + } + } +} + Add the following Python script to a file named test.py in your + application directory (and the ensure that Python is installed): + +
 #!/usr/bin/python
+ # ------------------------------------------------------------------------------
+ # Sample Python script
+ # ------------------------------------------------------------------------------
+ 
+ import sys
+ 
+ for word in sys.argv: #echo the command line arguments
+     print word
+ 
+ print "HI FROM PYTHON"
+ print "Enter user name" 
+ line = sys.stdin.readline()
+ 
+ sys.stdout.write("hello," + line)
+
flash.external.ExtensionContextexit + Signals the native process has exited.flash.events.NativeProcessExitEventflash.events.NativeProcessExitEvent + Signals the native process has exited. The exitCode property + contains the value the process returns to the host operating system on exit. + If the AIR application terminates the process by calling the exit() + method of the NativeProcess object, the exitCode property is set + to NaN. + + standardInputIoError + Signals that writing to the standard input (stdin) stream has failed.flash.events.IOErrorEventflash.events.IOErrorEvent + Signals that writing to the standard input (stdin) stream has failed. The NativeProcess + object dispatches this event when the closeInput() method fails or when the runtime + cannot write data to the native process's standard input pipe. + + standardOutputIoError + Signals that reading from the stdout stream has failed.flash.events.IOErrorEventflash.events.IOErrorEvent + Signals that reading from the stdout stream has failed. The NativeProcess object can dispatch + this event when the runtime + cannot read data from the native process's standard output pipe. + + standardErrorIoError + Signals that reading from the standard error (stderror) stream has failed.flash.events.IOErrorEventflash.events.IOErrorEvent + Signals that reading from the standard error (stderror) stream has failed. The NativeProcess object can dispatch + this event when the runtime + cannot read data from the native process's standard error pipe. + + standardInputClose + Signals that the NativeProcess object has closed its input stream by calling the closeInput() + method.flash.events.Eventflash.events.Event + Signals that the NativeProcess object has closed its input stream by calling the closeInput() + method. The NativeProcess object does not dispatch this event when the actual native process itself + closes the input stream. + + standardInputProgress + Signals that the NativeProcess has written data to the input stream for the child process.flash.events.ProgressEventflash.events.ProgressEvent + Signals that the NativeProcess has written data to the input stream for the child process. + The NativeProcess object dispatches this event when data is written to the stream. This event + does not indicate whether or not the child process has read any of the data. + + standardErrorClose + Signals that the NativeProcess has closed its error stream.flash.events.Eventflash.events.Event + Signals that the NativeProcess has closed its error stream. + + standardErrorData + Signals that the native process has data available to read on the standard error (stderror) stream.flash.events.ProgressEventflash.events.ProgressEvent + Signals that the native process has data available to read on the standard error (stderror) stream. The NativeProcess + object dispatches this event when the child process flushes its standard error stream or when the internal + buffer used to communicate between the processes is full. Do not write code that depend on + the size of this internal buffer; it varies between versions and operating systems. + + standardOutputClose + Signals that the NativeProcess has closed its output stream.flash.events.Eventflash.events.Event + Signals that the NativeProcess has closed its output stream. + + standardOutputData + Signals that the native process has data available to read on the output stream.flash.events.ProgressEventflash.events.ProgressEvent + Signals that the native process has data available to read on the output stream. The NativeProcess + object dispatches this event when the child process flushes its stdout stream or when the internal + buffer used to communicate between the processes is full. Do not write code that depend on + the size of this internal buffer; it varies between versions and operating systems. + + NativeProcess + Constructs an uninitialized NativeProcess object. + Constructs an uninitialized NativeProcess object. Call the start() method + to start the process. + + start()closeInput + Closes the input stream on this process. + Closes the input stream on this process. Some command line applications + wait until the input stream is closed to start some operations. Once + the stream is closed it cannot be re-opened until the process exits and + is started again. + + ioErrorStandardInputflash.events:IOErrorEventThere is a problem closing the input stream to the process + + There is a problem closing the input stream to the process + + standardInputCloseflash.events:EventThe input stream has been closed. + + The input stream has been closed.exit + Attempts to exit the native process.forceBooleanfalseWhether the application should attempt to forcibly exit the native process, if necessary. + +

If the force parameter is set to false, this method attempts to gracefully exit the native process. + This method "asks" the native process to exit. This request may be ignored by the native process, and as a result this method + is not guaranteed to actually cause the native process to exit. The NativeProcess object only dispatches a + NativeProcessExitEvent event if the native process exits.

+ +

If the force parameter is set to true, this method attempts to forcibly exit the native process. + Calling this method with the force parameter is set to true should be a last resort. + Calling this method with the force parameter is set to true may have adverse affects on the state of system + resources associated with the native process. For example, opened files may be left in an inconsistent state. The runtime will + make its best effort to try to force the native process to exit. However, it is not guaranteed that the native process + will exit. The NativeProcess object only dispatches a NativeProcessExitEvent event if the native process exits.

+ +

If the NativeProcess does successfully exit, it dispatches a NativeProcessExitEvent event.

+ +
+ Attempts to exit the native process. + +
start + Starts the native process identified by the start up info specified.if the NativeProcess is currently running. + IllegalOperationErrorflash.errors:IllegalOperationErrorif the nativePath property of the NativeProcessStartupInfo does not exist. + ArgumentErrorArgumentErrorif the NativeProcess did not start successfully. + + ErrorErrorinfoflash.desktop:NativeProcessStartupInfoNativeProcessStartupInfo Defines information about how to start the native process. + + + Starts the native process identified by the start up info specified. Once the process starts, + all of the input and output streams will be opened. This method returns immediately after the request + to start the specified process has been made to the operating system. The NativeProcess object throws an + IllegalOperationError exception if the process is currently running. The process is running + if the running property of the NativeProcess object returns true. + If the operating system is unable to start the process, an Error is thrown. + +

+ A NativeProcess instance corresponds to a single process on the underlying operating system. If you want to execute more than + one instance of the same operating system process concurrently, you can create one NativeProcess instance per child + process.

+ +

+ You can call this method whenever the running property of the NativeProcess object returns false. + This means that the NativeProcess object can be reused. In other words you can construct a NativeProcess instance, + call the start() method, wait for the exit event, and then call the start() + method again. You may use a different NativeProcessStartupInfo object as the info parameter value in + the subsequent call to the start() method.

+ +

The NativeProcess class and its capabilities are only available to AIR applications installed with a + native installer. When debugging, you can pass the -profile extendedDesktop argument to ADL + to enable the NativeProcess functionality. Check the NativeProcess.isSupported property to + to determine whether native process communication is supported.

+ +

Important security considerations:

+ +

The native process API can run any executable on the user's system. Take extreme care when constructing + and executing commands. If any part of a command to be executed originates from an external source, + carefully validate that the command is safe to execute. Likewise, your AIR application should + validate data passed to a running process.

+ +

However, validating input can be difficult. To avoid such difficulties, it is best + to write a native application (such as an EXE file on Windows) that has specific APIs. These APIs should + process only those commands specifically required by the AIR application. For example, the native + application may accept only a limited set of instructions via the standard input stream.

+ +

AIR on Windows does not allow you to run .bat files directly. Windows .bat files are executed by + the command interpreter application (cmd.exe). When you invoke a .bat file, this command application + can interpret arguments passed to the command as additional applications to launch. A malicious injection + of extra characters in the argument string could cause cmd.exe to execute a harmful or insecure application. + For example, without proper data validation, your AIR application may call + myBat.bat myArguments c:/evil.exe. The command application would launch the evil.exe + application in addition to running your batch file.

+ +

If you call the start() method with a .bat file, the NativeProcess object + throws an exception. The message property of the Error object contains the string + "Error #3219: The NativeProcess could not be started."

+ +
NativeProcessStartupInfo
isSupported + Indicates if running native processes is supported in the current profile.Boolean + Indicates if running native processes is supported in the current profile. This property returns + true only when running in the extendedDesktop profile. In addition, + NativeProcess.isSupported is always false for applications installed + as an AIR file. You must package an AIR application using the ADT -target native flag + in order to use the NativeProcess class. + + running + Indicates if this native process is currently running.Boolean + Indicates if this native process is currently running. The process is running if you have called + the start() method and the NativeProcess object has not yet dispatched an exit + event. A NativeProcess instance corresponds to a single process on the underlying operating system. + This property remains true as long as the underlying operating system process is executing + (while the native process is starting and until the process returns an exit code to the operating system.) + + standardError + Provides access to the standard error output from this native process.flash.utils:IDataInputif no data is present and a read operation is attempted. + + EOFErrorflash.errors:EOFError + Provides access to the standard error output from this native process. As data + becomes available on this pipe, the NativeProcess object dispatches a ProgressEvent + object. If you attempt to read data from this stream when no data is + available, the NativeProcess object throw an EOFError exception. + +

The type is IDataInput because data is input from the perspective of the + current process, even though it is an output stream of the child process.

+ +
flash.events.ProgressEventflash.utils.IDataInput
standardInput + Provides access to the standard input of this native process.flash.utils:IDataOutputwhen writing to this value when running returns false or + when attempting to write data to a closed input stream. + + IllegalOperationErrorflash.errors:IllegalOperationError + Provides access to the standard input of this native process. Use this pipe to + send data to this process. Each time data is written to the input property + that data is written to the native process's input pipe as soon as possible. + +

The type is IDataOutput because data is output from the perspective of the current process, + even though it is an input stream of the child process.

+ +
closeInput()IDataOutput
standardOutput + Provides access to the standard output pipe of this native process.flash.utils:IDataInputif no data is present and a read operation is attempted. + + EOFErrorflash.errors:EOFError + Provides access to the standard output pipe of this native process. Use this pipe to + read data from the native process's standard output. When data is present on this pipe, + the NativeProcess object dispatches a ProgressEvent. If you attempt to read data from this stream + when no data is available, the NativeProcess object throws an EOFError. + +

The type is IDataInput because data is input from the perspective of the + current process even though it is an output stream of the child process.

+ +
flash.utils.IDataInputflash.events.ProgressEvent
InteractiveIcon + The InteractiveIcon class is the base class for the operating + system icons associated with applications.flash.desktop:Icon + The InteractiveIcon class is the base class for the operating + system icons associated with applications. + +

Use the icon property of the NativeApplication object to get an instance of the application + icon. The icon type will be one of the subclasses of InteractiveIcon, + either DockIcon on Mac OS X® or SystemTrayIcon on Windows® and Linux.

+ +

You cannot instantiate the InteractiveIcon class directly. Calls to + the new InteractiveIcon() constructor will throw an + ArgumentError exception.

+ +
flash.desktop.NativeApplication.iconflash.desktop.NativeApplication.supportsDockIconflash.desktop.NativeApplication.supportsSystemTrayIconbitmaps + + The icon image as an array of BitmapData objects of different sizes.Array + + The icon image as an array of BitmapData objects of different sizes. + +

When an icon is displayed in a given operating system context, the bitmap + in the array closest to the displayed size is used (and + scaled if necessary). Common sizes include 16x16, 32x32, 48x48, and + 128x128. (512x512 pixel icons may be used for some operating system + icons in the near future.)

+ +

In some contexts, the operating system may use a default system icon + if nothing has been assigned to the bitmaps property. + In other contexts, no icon appears.

+ +

To set or change the icon appearance, assign an array of + BitmapData objects to the bitmaps property:

+ + + icon.bitmaps = new Array(icon16x16.bitmapData, icon128x128.bitmapData); + + +

Modifying the bitmaps array directly has no effect.

+ +

To clear the icon image, assign an empty array to the + bitmaps property.

+ +

+ Note: When loading image files for an icon, the PNG file format + generally provides the best alpha blending. The GIF format supports only + on or off transparency (no blending). The JPG format does not support + transparency at all. +

+ +
height + The current display height of the icon in pixels.int + The current display height of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The height property indicates the height of the icon chosen from the bitmaps array + for the current context. The actual display height may be different if the operating system + has scaled the icon.

+ +
width + The current display width of the icon in pixels.int + The current display width of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The width property indicates the width of the icon chosen from the bitmaps array + for the current context. The actual display width may be different if the operating system + has scaled the icon.

+ +
InvokeEventReason + The InvokeEventReason class enumerates values returned by the + reason property of an InvokeEvent object.Defines constants representing the ways in which an application can be invoked via + the operating system. + + Object + The InvokeEventReason class enumerates values returned by the + reason property of an InvokeEvent object. + + flash.events.InvokeEvent.reasonLOGIN + Indicates that the InvokeEvent event occurred due to the user logging in.loginString + Indicates that the InvokeEvent event occurred due to the user logging in. + + STANDARD + Indicates that the InvokeEvent occured for any reason other than login.standardString + Indicates that the InvokeEvent occured for any reason other than login. + + NativeDragActions +The NativeDragActions class defines string constants for the names of the drag-and-drop actions.Object +The NativeDragActions class defines string constants for the names of the drag-and-drop actions. + +

The NativeDragActions constants are used as values for the + dropAction property of the NativeDragManager and NativeDragEvent classes.

+ +
flash.desktop.NativeDragManagerflash.events.NativeDragEventCOPY + Defines the string to use for the copy action.copyString + Defines the string to use for the copy action. + + LINK + Defines the string to use for the link action.linkString + Defines the string to use for the link action. + + MOVE + Defines the string to use for the move action.moveString + Defines the string to use for the move action. + + NONE + Defines the string to use when no action is specified.noneString + Defines the string to use when no action is specified. + +

In a nativeDragComplete event, an action of none + indicates that the drag-and-drop operation was abandoned by the user.

+ +
ClipboardFormats +The ClipboardFormats class defines constants for the names of the standard data formats used with the Clipboard class.Object +The ClipboardFormats class defines constants for the names of the standard data formats used with the Clipboard class. +Flash Player 10 only supports TEXT_FORMAT, RICH_TEXT_FORMAT, and HTML_FORMAT. + +flash.desktop.ClipboardBITMAP_FORMAT + Image data (AIR only).air:bitmapString + Image data (AIR only). + + FILE_LIST_FORMAT + An array of files (AIR only).air:file listString + An array of files (AIR only). + + FILE_PROMISE_LIST_FORMAT + File promise list (AIR only).air:file promise listString + File promise list (AIR only). + + HTML_FORMAT + HTML data.air:htmlString + HTML data. + + RICH_TEXT_FORMAT + Rich Text Format data.air:rtfString + Rich Text Format data. + + TEXT_FORMAT + String data.air:textString + String data. + + URL_FORMAT + A URL string (AIR only).air:urlString + A URL string (AIR only). + + NativeApplication + The NativeApplication class represents this AIR application.flash.events:EventDispatcher + The NativeApplication class represents this AIR application. + +

+ The NativeApplication class provides application information, + application-wide functions, and dispatches application-level events. +

+

+ The NativeApplication object is a singleton object, created automatically at startup. + Get the NativeApplication instance of an application with the static property + NativeApplication.nativeApplication. +

+ +
keyUp + Dispatched when the user releases a key.flash.events.KeyboardEvent.KEY_UPflash.events.KeyboardEvent + Dispatched when the user releases a key. The NativeApplication instance provides this event to + support keyboard accelerators. This keyboard event is dispatched first to the NativeApplication. + Canceling this event has no effects on other objects (such as NativeWindow menu accelerators). + This event occurs after a keyDown event. + flash.display.InteractiveObject.keyUpkeyDown + Dispatched when the user presses a key.flash.events.KeyboardEvent.KEY_DOWNflash.events.KeyboardEvent + Dispatched when the user presses a key. The NativeApplication instance provides this event to + support keyboard accelerators. This keyboard event is dispatched first to the NativeApplication. + Canceling this event also cancels NativeWindow menu accelerators. + This event occurs before the keyUp event. + flash.display.InteractiveObject.keyDownuserPresent + Dispatched when the operating system detects mouse or keyboard activity after an idle period.flash.events.Event.USER_PRESENTflash.events.Event + Dispatched when the operating system detects mouse or keyboard activity after an idle period. + +

Note: This event is not dispatched on mobile devices or AIR for TV devices.

+ +

The period of time that is considered idle is configurable with the idleThreshold + property. The amount of time that the user has been idle can be determined from + the timeSinceLastUserInput property.

+ +
idleThresholdtimeSinceLastUserInput
userIdle + Dispatched when the user has been idle.flash.events.Event.USER_IDLEflash.events.Event + Dispatched when the user has been idle. + +

Specify the period of time for which a user must be idle before this event is dispatched using the + idleThreshold property. The amount of time that the user has been idle can be + determined from the timeSinceLastUserInput property.

+ +

Note: This event is not dispatched on mobile devices or AIR for TV devices.

+ + +
idleThresholdtimeSinceLastUserInput
networkChange + Dispatched when either a new network connection becomes available or + an existing network connection is lost.flash.events.Event.NETWORK_CHANGEflash.events.Event + Dispatched when either a new network connection becomes available or + an existing network connection is lost. + +

A networkChange event does not necessarily mean that the host computer has + gone online or offline; it may just be transitioning from one type of + connection to another. Applications can use this event to help optimize the + task of monitoring remote resource availability. The dispatch of a + networkChange event is often a good time to verify the availability of any remote resources. +

+

Notes:

+
  • There may be a short delay between + a network change and the delivery of this event.
  • On Android, the NativeApplication object may dispatch more than one networkChange + event for each change in a network connection.
+ +
exiting + Dispatched when the application exit sequence is started.flash.events.Event.EXITINGflash.events.Event + Dispatched when the application exit sequence is started. + +

The exiting event is dispatched when application exit is initiated by + the operating system; for example, when a user issues the Cmd-Q + key sequence on Mac OS X, or when the autoExit property of + the NativeApplication object is true and the last + application window is closed. + Canceling this event prevents the application from exiting.

+ +

AIR for TV devices never dispatch the exiting event. +

+ +

Note: Calling the NativeApplication exit() method does not cause an + exiting event to be dispatched. To warn components of an impending exit, + dispatch the exiting event before calling exit().

+ + +
deactivate + Dispatched when the desktop focus is switched to a different application.flash.events.Event.DEACTIVATEflash.events.Event + Dispatched when the desktop focus is switched to a different application. + + activate + Dispatched when this application becomes the active desktop application.flash.events.Event.ACTIVATEflash.events.Event + Dispatched when this application becomes the active desktop application. + + browserInvoke + Dispatched when an application is invoked by a SWF file running in the user's browser.flash.events.BrowserInvokeEvent.Browser_INVOKEflash.events.BrowserInvokeEvent + Dispatched when an application is invoked by a SWF file running in the user's browser. + +

Browser invocation is permitted only if an application specifies the following in + the application descriptor file:

+ + <allowBrowserInvocation>true</allowBrowserInvocation> + +
invoke + Dispatched when an application is invoked.flash.events.InvokeEvent.INVOKEflash.events.InvokeEvent + Dispatched when an application is invoked. + +

When an application is invoked a second time, + another instance of the application is not started. Instead, the first instance + receives an additional invoke event. It is the responsibility of the + application to handle subsequent invoke events appropriately.

+ +

Note: All invoke events are queued. When a listener for this + event is registered, it receives all events in the queue as well as any new events. + Queued events may be delivered before or after any new invoke events.

+ +
activate + Activates this application.windowflash.display:NativeWindownullThe NativeWindow object of the window to activate along with the application. + + Activates this application. + +

This method is not supported on platforms that do not support the NativeWindow class.

+ +

Under some circumstances determined by the operating system, this method does not + activate an application. Most operating systems restrict the ability of an application + to activate itself to prevent it from accidentally or maliciously making it impossible + for a user to use other applications.

+ +

If the operating system allows activation, then the specified window is activated and + brought to the desktop foreground; that is, in front of the windows of other applications. + (If the window parameter is null, then any + visible window of this application is activated.)

+ +

The activate() method has no effect if the application has no visible windows.

+ +

The activate operation is synchronous.

+ +
activateflash.events:EventDispatched if the activation state changes. + + Dispatched if the activation state changes.
addEventListener + + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.typeStringThe type of event. + + listenerFunctionThe listener function that processes the event. This function must accept + an Event object as its only parameter and must return nothing, as this example shows: + + + function(evt:Event):void + +

The function can have any name.

+ +
useCaptureBooleanfalse + + Determines whether the listener works in the capture phase or the + target and bubbling phases. If useCapture is set to true, + the listener processes the event only during the capture phase and not in the + target or bubbling phase. If useCapture is false, the + listener processes the event only during the target or bubbling phase. To listen for + the event in all three phases, call addEventListener twice, once with + useCapture set to true, then again with + useCapture set to false. + + priorityint0The priority level of the event listener. The priority is designated by + a signed 32-bit integer. The higher the number, the higher the priority. All listeners + with priority n are processed before listeners of priority n-1. If two + or more listeners share the same priority, they are processed in the order in which they + were added. The default priority is 0. + + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or + weak. A strong reference (the default) prevents your listener from being garbage-collected. + A weak reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbage-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. + + + +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's + priority, you must first call removeListener(). Then you can register the + listener again with the new priority level.

+ +

Keep in mind that after the listener is registered, subsequent calls to + addEventListener() with a different type or + useCapture value result in the creation of a separate listener registration. + For example, if you first register a listener with useCapture set to + true, it listens only during the capture phase. If you call + addEventListener() again using the same listener object, but with + useCapture set to false, you have two separate listeners: one + that listens during the capture phase and another that listens during the target and + bubbling phases. +

+ +

You cannot register an event listener for only the target phase or the bubbling + phase. Those phases are coupled during registration because bubbling + applies only to the ancestors of the target node.

+ +

If you no longer need an event listener, remove it by calling + removeEventListener(), or memory problems could result. Event listeners are not automatically + removed from memory because the garbage + collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference + parameter is set to true).

+ +

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event listeners + attached to it move along with it.

+ + +

If the event listener is being registered on a node while an event is being processed + on this node, the event listener is not triggered during the current phase but can be + triggered during a later phase in the event flow, such as the bubbling phase.

+ +

If an event listener is removed from a node while an event is being processed on the node, + it is still triggered by the current actions. After it is removed, the event listener is + never invoked again (unless registered again for future processing).

+ +
clear + Invokes an internal delete command on the focused display object.true. + + Boolean + Invokes an internal delete command on the focused display object. + +

This function call is ignored if the + focused object does not implement the + command. Only display objects descending from the TextField or HTMLLoader + classes currently implement this command.

+ +

Note: The clear() command deletes + selected text. If nothing is selected, it does not clear all text.

+ +
copy + Invokes an internal copy command on the focused display object.Boolean + Invokes an internal copy command on the focused display object. + +

This function call is ignored if the component does not implement the + command. Only display objects descending from the TextField or HTMLLoader + classes currently implement this command.

+ +
cut + Invokes an internal cut command on the focused display object.true. + + Boolean + Invokes an internal cut command on the focused display object. + +

This function call is ignored if the component does not implement the + command. Only display objects descending from the TextField or HTMLLoader + classes currently implement this commands.

+ +
dispatchEvent + + Dispatches an event into the event flow.A value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called + on the event. + + Booleaneventflash.events:EventThe Event object that is dispatched into the event flow. + If the event is being redispatched, a clone of the event is created automatically. + After an event is dispatched, its target property cannot be changed, so you + must create a new copy of the event for redispatching to work. + + + + Dispatches an event into the event flow. The event target is the EventDispatcher + object upon which the dispatchEvent() method is called. + + exit + Terminates this application.errorCodeint0The exit code reported to the operating system when this application exits. + + + Terminates this application. + + +

The call to the exit() method will return; + the shutdown sequence does not begin until the currently executing code + (such as a current event handler) has completed. Pending asynchronous + operations are canceled and may or may not complete.

+ +

Note that an exiting event is not dispatched. If an exiting event is required + by application logic, call NativeApplication.nativeApplication.dispatchEvent(), passing + in an Event object of type exiting. For any open windows, NativeWindow objects do dispatch + closing and close events. Calling the preventDefault() method of + closing event object prevents the application from exiting.

+ +

Note: This method is not supported on the iOS operating system.

+ +
getDefaultApplication + Gets the default application for opening files with the specified extension.If the extension parameter does not contain one of the + file extensions declared in the application descriptor. + + ErrorErrorThe path of the default application. + + StringextensionStringA String containing the extension of the file type of interest (without the "."). + + + Gets the default application for opening files with the specified extension. + +

Note: This method can only be used with file types declared in the + fileTypes statement of the application descriptor.

+ +

This method is not applicable for AIR for TV devices. If you call it with a file type + declared in the application descriptor, it returns null.

+ +
applicationDescriptor
isSetAsDefaultApplication + Specifies whether this application is currently the default application + for opening files with the specified extension.If the extension parameter does not contain one of the + file extensions declared in the application descriptor. + + ErrorErrortrue if this application is the default. + + BooleanextensionStringA String containing the extension of the file type of interest (without the "."). + + + Specifies whether this application is currently the default application + for opening files with the specified extension. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the NativeApplication.supportsDefaultApplication property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
applicationDescriptorsupportsDefaultApplication
paste + Invokes an internal paste command on the focused display object.true. + + Boolean + Invokes an internal paste command on the focused display object. + +

This function call is ignored if the component does not implement the + command. Only display objects descending from the TextField or HTMLLoader + classes currently implement this command.

+ +
removeAsDefaultApplication + Removes this application as the default for opening files with the specified extension.If the extension parameter does not contain one of the + file extensions declared in the application descriptor. + + ErrorErrorextensionStringA String containing the extension of the file type of interest + (without the "."). + + + Removes this application as the default for opening files with the specified extension. + +

Note: This method can only be used with file types listed in the + fileTypes statement in the application descriptor.

+ +
applicationDescriptorsupportsDefaultApplication
removeEventListener + + Removes a listener from the EventDispatcher object.typeStringThe type of event. + + listenerFunctionThe listener object to remove. + + useCaptureBooleanfalse + + Specifies whether the listener was registered for the capture phase or the + target and bubbling phases. If the listener was registered for both the capture phase and the + target and bubbling phases, two calls to removeEventListener() are required + to remove both, one call with useCapture() set to true, and another + call with useCapture() set to false. + + + + Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect. + + selectAll + Invokes an internal selectAll command on the focused display object.true. + + Boolean + Invokes an internal selectAll command on the focused display object. + +

This function call is ignored if the component does not implement the + command. Only display objects descending from the TextField or HTMLLoader + classes currently implement this command.

+ +
setAsDefaultApplication + Sets this application as the default application for opening files with the specified extension.If the extension parameter does not contain one of the + file extensions declared in the application descriptor. + + ErrorErrorextensionStringA String containing the extension of the file type of interest (without the "."). + + + Sets this application as the default application for opening files with the specified extension. + +

Note: This method can only be used with file types declared in the + fileTypes statement in the application descriptor.

+ +
applicationDescriptorsupportsDefaultApplication
activeWindow + The active application window.flash.display:NativeWindow + The active application window. + +

If the active desktop window does not belong + to this application, or there is no active window, activeWindow is + null.

+ +

This property is not supported on platforms that do not support the NativeWindow class.

+ +
applicationDescriptor + The contents of the application descriptor file for this AIR application.XML + The contents of the application descriptor file for this AIR application. + + + + The following example reads the copyright and version + elements from the application descriptor file. Note that you must use the default namespace + defined in the application descriptor XML. + +var appDescriptor:XML = NativeApplication.nativeApplication.applicationDescriptor; +var ns:Namespace = appDescriptor.namespace(); +var appCopyright:String = appDescriptor.ns::copyright; +var appVersion:String = appDescriptor.ns::version; +trace("appId:", appCopyright); +trace("version:", appVersion); +applicationID + The application ID of this application.String + The application ID of this application. + +

The value of this ID is set in the + application descriptor file.

+ +
autoExit + Specifies whether the application should automatically terminate when + all windows have been closed.Boolean + Specifies whether the application should automatically terminate when + all windows have been closed. + +

When autoExit is true, which is the default, + the application terminates when all windows are closed. Both + exiting and exit events are dispatched. + When autoExit is false, you must call + NativeApplication.nativeApplication.exit() to terminate the application.

+ +

This property is not supported on platforms that do not support the NativeWindow class.

+ +
icon + The application icon.flash.desktop:InteractiveIcon + The application icon. + +

Use NativeApplication.supportsDockIcon and NativeApplication.supportsSystemTrayIcon + to determine the icon class. The type will be one + of the subclasses of InteractiveIcon. On Mac® OS X, NativeApplication.icon + is an object of type DockIcon. On Windows®, NativeApplication.icon + is an object of type SystemTrayIcon. When an application icon is not supported, + NativeApplication.supportsDockIcon and NativeApplication.supportsSystemTrayIcon are + both false and the icon property is null.

+ +

The icon object is automatically created, but it is not initialized + with image data. On some operating systems, such as Mac OS X, a default image is supplied. + On others, such as Windows, the icon is not displayed unless image data is assigned to it. + To assign an icon image, set the icon.bitmaps property with an array + containing at least one BitmapData object. If more than one BitmapData object is included + in the array, then the operating system chooses the image that is closest in size to the icon's + display dimensions, scaling the image if necessary.

+ +
supportsDockIconflash.desktop.DockIconsupportsSystemTrayIconflash.desktop.SystemTrayIcon
idleThreshold + The number of seconds that must elapse without user input + before a userIdle event is dispatched.intIf you attempt to set the property to an invalid value. + The acceptable range of values is from 5 (5 seconds) through 86,400 (1 day), inclusive. + + ArgumentErrorArgumentError + The number of seconds that must elapse without user input + before a userIdle event is dispatched. + +

By default, the idle threshold is 300 seconds (5 minutes). The acceptable + range of values is from 5 (5 seconds) through 86,400 (1 day), inclusive.

+ +
userIdleuserPresent
menu + The application menu.flash.display:NativeMenu + The application menu. + +

Application menus are supported when NativeApplication.nativeApplication.supportsMenu + is true. Not all operating systems support application + menus. For example, application menus are supported on Mac OS X, but not on Windows or Linux. + Assigning a NativeMenu object to this property when NativeApplication.nativeApplication.supportsMenu + is false is allowed, but does nothing. Be sure to use the + NativeApplication.nativeApplication.supportsMenu property to determine whether the + operating system supports application menus. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +

AIR profile support: This feature is not supported + on mobile devices or AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

Note: On Mac OS X, the menu property references the + operating-system-supplied default application menu. You can modify the + existing menu structure by adding and removing items and submenus, and + by adding event listeners. You can also replace the default menus entirely by + assigning a new NativeMenu object to this menu property.

+ +
flash.display.NativeMenuflash.display.NativeWindow.supportsMenu
nativeApplication + The singleton instance of the NativeApplication object.flash.desktop:NativeApplicationIf accessed by content outside the application + security sandbox. + + ErrorError + The singleton instance of the NativeApplication object. + + openedWindows + An array containing all the open native windows of this application.Array + An array containing all the open native windows of this application. + +

This property is not supported on platforms that do not support the NativeWindow class.

+
publisherID + The publisher ID of this application.String + The publisher ID of this application. + +

The value of this ID is set in the + application's publisherid file, which is generated at installation from the + certificate chain used to sign the application.

+ +
runtimePatchLevel + The patch level of the runtime hosting this application.uint + The patch level of the runtime hosting this application. + + runtimeVersion + The version number of the runtime hosting this application.String + The version number of the runtime hosting this application. + + startAtLogin + Specifies whether this application is automatically launched whenever the + current user logs in.BooleanOn Windows when another application with the same name + (but with a different path to the executable) is already set to + launch when this user logs in. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf this application is not installed, which + may be the case when launched by the AIR Debug Launcher (ADL). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies whether this application is automatically launched whenever the + current user logs in. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the NativeApplication.supportsStartAtLogin property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

+ The startAtLogin property reflects the status of the operating-system-defined mechanism for + designating that an application should start automatically when a user logs in. The + user can change the status manually by using the operating system user interface. This + property reflects the current status, whether the status was last changed + by the AIR application or by the operating system. +

+
supportsStartAtLogin
supportsDefaultApplication + Indicates whether setAsDefaultApplication(), removeAsDefaultApplication(), and + isSetAsDefaultApplication() are supported on the current platform.Boolean + Indicates whether setAsDefaultApplication(), removeAsDefaultApplication(), and + isSetAsDefaultApplication() are supported on the current platform. + +

If true, then the above methods will work as documented. + If false, then setAsDefaultApplication() and removeDefaultApplication() + do nothing and isSetAsDefaultApplication() returns false.

+ +
setAsDefaultApplication()removeAsDefaultApplication()isSetAsDefaultApplication()
supportsDockIcon + Indicates whether AIR supports dock-style application icons on the current operating system.Boolean + Indicates whether AIR supports dock-style application icons on the current operating system. + +

If true, the NativeApplication.icon property is of type + DockIcon.

+ +

The Mac OS X user interface provides an application + "dock" containing icons for applications that are running or are frequently used.

+ +

Be sure to use the NativeApplication.supportsDockIcon property to determine whether the + operating system supports application dock icons. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +
iconflash.desktop.DockIcon
supportsMenu + Specifies whether the current operating system supports a global application menu bar.Boolean + Specifies whether the current operating system supports a global application menu bar. + +

When true, the NativeApplication.menu property can be used to define (or access) a native + application menu.

+ +

Be sure to use the NativeApplication.supportsMenu property to determine whether the + operating system supports the application menu bar. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +
menuflash.display.NativeWindow.supportsMenu
supportsStartAtLogin + Indicates whether startAtLogin is supported on the current platform.Boolean + Indicates whether startAtLogin is supported on the current platform. + +

If true, then startAtLogin works as documented. + If false, then startAtLogin has no effect.

+ +
startAtLogin
supportsSystemTrayIcon + Specifies whether AIR supports system tray icons on the current operating system.Boolean + Specifies whether AIR supports system tray icons on the current operating system. + +

If true, the NativeApplication.icon property is of type + SystemTrayIcon.

+ +

The Windows user interface provides the "system tray" region of the task bar, officially called + the Notification Area, in which application icons can be displayed. No default icon is shown. You + must set the bitmaps array of the icon object to display an icon.

+ +

Be sure to use the NativeApplication.supportsSystemTrayIcon property to determine whether the + operating system supports system tray icons. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +
iconflash.desktop.SystemTrayIcon
systemIdleMode + Provides a way for applications to prevent the user interface from going into "idle" mode.String + Provides a way for applications to prevent the user interface from going into "idle" mode. + +

A value from the SystemIdleMode class to influence the host system's idle mode behavior. + This property is only effective for the application with input focus and can only be accessed from + content running in the application sandbox.

+ +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
flash.desktop.SystemIdleMode
timeSinceLastUserInput + The time, in seconds, since the last user input.int + The time, in seconds, since the last user input. + + userIdleuserPresent
Updater + The Updater class is used to update the currently running application + with a different version.Object + The Updater class is used to update the currently running application + with a different version. To use it, instantiate an Updater object and then call + its update() method. + +

The Updater class is only supported in the desktop profile. It is not supported for + extended desktop applications (applications installed with a native installer), and it is not + supported on the AIR mobile profile or AIR for TV profiles. Check the Updater.isSupported property.

+ +

Extended desktop application (applications installed with a native installer) + can download a new version of the native installer and launch it using the + File.openWithDefaultApplication() method.

+ +
air.update.ApplicationUpdaterair.update.ApplicationUpdaterUIUpdater + The constructor function for the Updater class. + The constructor function for the Updater class. Note that the update() + method is not a static member of the class. You must instantiate an Updater object + and call the update() method on it. + + update + Updates the currently running application with the version of the + application contained in the specified AIR file.The method was called when running in ADL. + + IllegalOperationErrorflash.errors:IllegalOperationErrorairFileflash.filesystem:FileThe File object pointing to the AIR file that contains the + update version of the application. + + versionStringThe required version in the new AIR file. The string in the + version attribute of the main application element of the + application descriptor file for the AIR file must match this value in order for the + update to succeed. + + + Updates the currently running application with the version of the + application contained in the specified AIR file. The application in + the AIR file must have the same application identifier + (appID) as the currently running application. + +

Calling this method causes the current application to exit (as if the + NativeApplication.exit() method had been called). This is necessary + because Adobe AIR cannot fully update an application while + the application is running. Upon successfully installing the new version of + the application, the application launches. If the runtime cannot successfully + install the new version (for example, if its application ID does not match + the existing version), the AIR installer presents an error message to + the user, and then the old version relaunches.

+ +

The update process relaunches the application whether or not the + update is successful. Updates can fail for a variety of reasons, including + some that the application cannot control (such as the user having insufficient + privileges to install the application). Applications should take care to + detect failures and avoid reattempting the same failed update repeatedly. + The resulting infinite loop would effectively disable the application. + One way to check for a successful update is to write the current + version number to a file before starting the update, and then compare + that to the version number when the application is relaunched.

+ +

When testing an application using the AIR Debug Launcher (ADL) application, + calling the update() method results in an IllegalOperationError exception.

+ +

On Mac OS, to install an updated version of an application, the user needs to + have adequate system privileges to install to the application directory. + On Windows or Linux, the user needs to have adminstrative privileges.

+ +

If the updated version of the application requires an updated version of + the runtime, the new runtime version is installed. To update the runtime, + a user needs to have administrative privileges for the computer.

+ +

Note: Specifying the version parameter is required for + security reasons. By requiring the application to verify the version number in + the AIR file, the application will not inadvertantly install an older version, + which might contain a security vulnerability that has been fixed.

+ +
Note that the update() method is not + a static method of the class. You instantiate an Updater object and call the + update() method of that object. + +import flash.fileSystem.File; +import flash.desktop.Updater; + +var updater:Updater = new Updater(); +var airFile:File = File.applicationStorageDirectory.resolvePath("Example Application.air"); +var version:String = "2.01"; +updater.update(airFile, version); +
air.update.ApplicationUpdaterair.update.ApplicationUpdaterUI
isSupported + The isSupported property is set to true if the Updater class is + available on the current platform, otherwise it is set to false.Boolean + The isSupported property is set to true if the Updater class is + available on the current platform, otherwise it is set to false. + + +
SystemTrayIcon + The SystemTrayIcon class represents the Windows taskbar&#xAE; notification + area (system tray)-style icon.A taskbar icon. + + flash.desktop:InteractiveIcon + The SystemTrayIcon class represents the Windows taskbar® notification + area (system tray)-style icon. + +

AIR profile support: This feature is supported on + desktop operating systems, but it is not supported on mobile devices or AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

Not all desktop operating systems have system tray icons. Check NativeApplication.supportsSystemTrayIcon + to determine whether system tray icons are supported on the current system.

+ +

An instance of the SystemTrayIcon class cannot be created. Get the object representing the system tray + icon from the icon property of the "global" NativeApplication object. +

+ +

When system tray icons are supported, the icon will be of type SystemTrayIcon. + Otherwise, the type of icon will be another + subclass of InteractiveIcon, typically DockIcon.

+ + +

Important: Attempting to call a SystemTrayIcon class method on the + NativeApplication.icon object on an operating system for which AIR does not support + system tray icons will generate a run-time exception.

+ +
flash.desktop.NativeApplication.iconflash.desktop.NativeApplication.supportsSystemTrayIconflash.desktop.DockIconrightClick + Dispatched by this SystemTrayIcon object on right mouse click.flash.events.ScreenMouseEvent.RIGHT_CLICKflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on right mouse click. + + rightMouseUp + Dispatched by this SystemTrayIcon object on right mouse up.flash.events.ScreenMouseEvent.RIGHT_MOUSE_UPflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on right mouse up. + + rightMouseDown + Dispatched by this SystemTrayIcon object on right mouse down.flash.events.ScreenMouseEvent.RIGHT_MOUSE_DOWNflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on right mouse down. + + click + Dispatched by this SystemTrayIcon object on mouse click.flash.events.ScreenMouseEvent.CLICKflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on mouse click. + + mouseUp + Dispatched by this SystemTrayIcon object on mouse up.flash.events.ScreenMouseEvent.MOUSE_UPflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on mouse up. + + mouseDown + Dispatched by this SystemTrayIcon object on mouse down.flash.events.ScreenMouseEvent.MOUSE_DOWNflash.events.ScreenMouseEvent + Dispatched by this SystemTrayIcon object on mouse down. + + MAX_TIP_LENGTH + The permitted length of the system tray icon tooltip.63Number + The permitted length of the system tray icon tooltip. + + bitmaps + + + The icon image as an array of BitmapData objects of different sizes.Array + + + The icon image as an array of BitmapData objects of different sizes. + +

When an icon is displayed in a given operating system context, the bitmap + in the array closest to the displayed size is used (and + scaled if necessary). Common sizes include 16x16, 32x32, 48x48, and + 128x128. (512x512 pixel icons may be used for some operating system + icons in the near future.)

+ +

In some contexts, the operating system may use a default system icon + if nothing has been assigned to the bitmaps property. + In other contexts, no icon appears.

+ +

To set or change the icon appearance, assign an array of + BitmapData objects to the bitmaps property:

+ + + icon.bitmaps = new Array(icon16x16.bitmapData, icon128x128.bitmapData); + + +

Modifying the bitmaps array directly has no effect.

+ +

To clear the icon image, assign an empty array to the + bitmaps property.

+ +

+ Note: When loading image files for an icon, the PNG file format + generally provides the best alpha blending. The GIF format supports only + on or off transparency (no blending). The JPG format does not support + transparency at all. +

+ +
height + + The current display height of the icon in pixels.int + + The current display height of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The height property indicates the height of the icon chosen from the bitmaps array + for the current context. The actual display height may be different if the operating system + has scaled the icon.

+ +
menu + The system tray icon menu.flash.display:NativeMenu + The system tray icon menu. + + tooltip + The tooltip that pops up for the system tray icon.String + The tooltip that pops up for the system tray icon. If the string is + longer than SystemTrayIcon.MAX_TIP_LENGTH, the tip will + be truncated. + + width + + The current display width of the icon in pixels.int + + The current display width of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The width property indicates the width of the icon chosen from the bitmaps array + for the current context. The actual display width may be different if the operating system + has scaled the icon.

+ +
Clipboard + The Clipboard class provides a container for transferring data and objects through the clipboard.Object + The Clipboard class provides a container for transferring data and objects through the clipboard. + The operating system clipboard can be accessed through the static generalClipboard property. + +

A Clipboard object can contain the same information in more than one format. + By supplying information in multiple formats, you increase the chances that another + application will be able to use that information. Add data to a Clipboard object + with the setData() or setDataHandler() method.

+ +

The standard formats are:

+
  • BITMAP_FORMAT: a BitmapData object (AIR only)
  • FILE_LIST_FORMAT: an array of File objects (AIR only)
  • HTML_FORMAT: HTML-formatted string data
  • TEXT_FORMAT: string data
  • RICH_TEXT_FORMAT: a ByteArray containing Rich Text Format data
  • URL_FORMAT: a URL string (AIR only)
+

These constants for the names of the standard formats are defined in the ClipboardFormats class.

+ +

When a transfer to or from the operating system occurs, + the standard formats are automatically translated between + ActionScript data types and the native operating system clipboard types.

+ +

You can use application-defined formats to add + ActionScript objects to a + Clipboard object. If an object is serializable, both a reference and a clone + of the object can be made available. Object references are valid only within the + originating application.

+ +

When it is computationally expensive to convert the information to be transferred into a + particular format, you can supply the name of a function that performs the conversion. + The function is called if and only if that format is read by the receiving component or application. + Add a deferred rendering function to a Clipboard object with the setDataHandler() method. + Note that in some cases, + the operating system calls the function before a drop occurs. For example, when you use a handler function to + provide the data for a file dragged from an AIR application to the file system, the operating + system calls the data handler function as soon as the drag gesture leaves the AIR application—typically resulting + in an undesireable pause as the file data is downloaded or created.

+ +

Note for AIR applications: The clipboard object referenced by the event objects dispatched for HTML + drag-and-drop and copy-and-paste events are not the same type as the AIR Clipboard object. + The JavaScript clipboard object is described in the AIR developer's guide.

+ +

Note for Flash Player applications: In Flash Player 10, a paste operation from the clipboard first + requires a user event (such as a keyboard shortcut for the Paste command or a mouse click on the Paste command + in a context menu). Clipboard.getData() + will return the contents of the clipboard only if the InteractiveObject has received + and is acting on a paste event. Calling Clipboard.getData() under any other circumstances + will be unsuccessful. The same restriction applies in AIR for content outside the + application sandbox.

+ +

On Linux, clipboard data does not persist when an AIR application closes.

+ +
The following example, for Adobe AIR, uses the ClipboardExample class to + copy a string from one variable to another via the system clipboard. + This task is accomplished by performing the following steps: + +
  1. Write the data, in this case a string, to Clipboard.generalClipboard.
  2. Read the clipboard contents from Clipboard.generalClipboard.
+

Note: Because of security restrictions on accessing clipboard data, this example + does not work in Flash Player. In Flash Player, you can only call the getData() + method of the Clipboard object in a paste event handler.

+ +package +{ + import flash.display.Sprite; + import flash.desktop.Clipboard; + import flash.desktop.ClipboardFormats; + import flash.desktop.ClipboardTransferMode; + + public class ClipboardExample extends Sprite + { + public function ClipboardExample() + { + var sally:String = "Sally"; + var person:String; + + copy(sally); + person = paste(); + trace(person); //traces: "Sally" + } + + private function copy(text:String):void + { + Clipboard.generalClipboard.clear(); + Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, text); + } + + private function paste():String + { + if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)) + { + return String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT)); + } + else + { + return null; + } + } + + } +} +
flash.desktop.NativeDragManagerflash.desktop.ClipboardFormatsflash.desktop.ClipboardTransferModeClipboard + Creates an empty Clipboard object.new Clipboard() is not supported in Flash Player, since only the operating system clipboard can be used in Flash Player. For copy-and-paste operations involving the operating system clipboard, use the Clipboard.generalClipboard object rather than creating a new Clipboard object. Does not throw an error in an AIR application. + + IllegalOperationErrorflash.errors:IllegalOperationError + Creates an empty Clipboard object. + +

Create Clipboard objects to hold the data of a native drag-and-drop gesture in Adobe AIR. Clipboard + objects can be used for only one drag-and-drop gesture; they cannot be reused.

+ +

Do not create a Clipboard object for copy-and-paste operations. Use the single + Clipboard.generalClipboard object instead.

+ +
The following example creates a new clipboard for use with the NativeDragManager + class. + +

Note: For copy-and-paste operations involving the operating system clipboard, + use the Clipboard.generalClipboard object rather than creating a new clipboard.

+ + import flash.desktop.Clipboard; + + var clipboard:Clipboard = new Clipboard(); +
generalClipboard
clearData + Deletes the data representation for the specified format.Call to generalClipboard.clearData() is not permitted in this context. + In Flash Player, you can only call this method successfully during the processing of a user event + (as in a key press or mouse click). In AIR, this restriction only applies to content outside of the + application security sandbox. + SecurityErrorSecurityErrorformatStringThe data format to remove. + + Deletes the data representation for the specified format. + + The following example clears any data having the format + ClipboardFormats.TEXT_FORMAT from the system clipboard: + + import flash.desktop.ClipboardFormats; + + Clipboard.generalClipboard.clearData(ClipboardFormats.TEXT_FORMAT); +clear + Deletes all data representations from this Clipboard object.Call to generalClipboard.clear() is not permitted in this context. + In Flash Player, you can only call this method successfully during the processing of a user event + (as in a key press or mouse click). In AIR, this restriction only applies to content outside of the + application security sandbox. + SecurityErrorSecurityError + Deletes all data representations from this Clipboard object. + + The following example clears the system clipboard: + + Clipboard.generalClipboard.clear(); +getData + Gets the clipboard data if data in the specified format is present.transferMode is not one of the names defined in the ClipboardTransferMode class. + ErrorErrorThe Clipboard object requested is no longer in scope (AIR only). + IllegalOperationErrorflash.errors:IllegalOperationErrorReading from or writing to the clipboard is not permitted in this context. + In Flash Player, you can only call this method successfully during the processing of a paste event. + In AIR, this restriction only applies to content outside of the application security sandbox. + + SecurityErrorSecurityErrorAn object of the type corresponding to the data format. + + ObjectformatStringThe data format to return. The format string can contain one of the standard + names defined in the ClipboardFormats class, or an application-defined name. + transferModeStringoriginalPreferredSpecifies whether to return a reference or serialized copy + when an application-defined data format is accessed. The value must be one + of the names defined in the ClipboardTransferMode class. This value is + ignored for the standard data formats; a copy is always returned. + + Gets the clipboard data if data in the specified format is present. + +

Flash Player requires that the getData() be called in a paste event handler. + In AIR, this restriction only applies to content outside of the application security sandbox.

+ +

When a standard data format is accessed, the data is returned as a new + object of the corresponding Flash data type.

+ +

When an application-defined format is accessed, the value of the + transferMode parameter determines whether a reference to the original + object or an anonymous object containing a serialized copy of the original + object is returned. When an originalPreferred or clonePreferred mode is specified, + Flash Player or AIR returns the alternate version if the preferred version is not available. + When an originalOnly or cloneOnly mode is specified, Flash Player or AIR returns + null if the requested version is not available.

+ +
The following example reads text from the system clipboard, if available: + + import flash.desktop.ClipboardFormats; + + var pasteData:String = Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT) as String; +
setData()flash.desktop.ClipboardFormatsflash.desktop.ClipboardTransferMode
hasFormat + Checks whether data in the specified format exists in this Clipboard object.The Clipboard object requested is no longer in scope. + IllegalOperationErrorflash.errors:IllegalOperationErrorReading from or writing to the clipboard is not permitted in this context. + + SecurityErrorSecurityErrortrue, if data in the specified format is present. + + BooleanformatStringThe format type to check. + + Checks whether data in the specified format exists in this Clipboard object. + +

Use the constants in the ClipboardFormats class to reference the standard format names.

+ +
The following example tests the system clipboard to determine + whether text-formatted data is available: + +if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)){ + //do something +} +
flash.desktop.ClipboardFormats
setDataHandler + Adds a reference to a handler function that produces the data to be transfered.format or handler is null. + TypeErrorTypeErrorThe Clipboard object requested is no longer in scope (AIR only). + IllegalOperationErrorflash.errors:IllegalOperationErrorReading from or writing to the clipboard is not permitted in this context. + In Flash Player, you can only call this method successfully during the processing of a user event + (such as a key press or mouse click). In AIR, this restriction only applies to content outside of the + application security sandbox. + + SecurityErrorSecurityErrortrue if the handler was succesfully set; + false otherwise. + + BooleanformatStringA function that returns the data to be transferred. + handlerFunctionThe format of the data. + serializableBooleantrueSpecify true if the object returned by handler + can be serialized (and deserialized). + + + Adds a reference to a handler function that produces the data to be transfered. + +

Use a handler function to defer creation or rendering of the data until it is actually accessed.

+ +

The handler function must return the appropriate data type for the specified format:

+ FormatReturn TypeClipboardFormats.TEXT_FORMATStringClipboardFormats.HTML_FORMATStringClipboardFormats.URL_FORMATString (AIR only)ClipboardFormats.RICH_TEXT_FORMATByteArrayClipboardFormats.BITMAP_FORMATBitmapData (AIR only)ClipboardFormats.FILE_LIST_FORMATArray of File (AIR only)ClipboardFormats.FILE_PROMISE_LIST_FORMATArray of File (AIR only)Custom format nameNon-void + +

The handler function is called when and only when the data in the specified format is read. Note that in some cases, + the operating system calls the function before a drop occurs. For example, when you use a handler function to + provide the data for a file dragged from an AIR application to the file system, the operating + system calls the data handler function as soon as the drag gesture leaves the AIR application—typically resulting + in an undesireable pause as the file data is downloaded or created. You can use a URLFilePromise for this purpose instead.

+ +

Note that the underlying data can change between the time the handler is added and the time the data is + read unless your application takes steps to protect the data. + The behavior that occurs when data on the clipboard represented by a handler function is read more than once + is not guaranteed. The clipboard might return the data produced by the first function call or it might call the + function again. Do not rely on either behavior.

+ + +

In the application sandbox of Adobe AIR, setDataHandler() can be called anytime. In other + contexts, setDataHandler() can only be called in response to a user-generated event such as + a key press or mouse click.

+ +

To add data directly to this Clipboard object, use the setData() method instead. + If both the setData() and the setDataHandler() methods are called with the same + format name, then the handler function is never called.

+ +

Note: On Mac OS, when you set the format parameter to ClipboardFormats.URL_FORMAT, + the URL is transferred only if the handler function returns a valid URL. Otherwise, the Clipboard object is emptied + (and calling getData() returns null).

+ +
The following example adds a random number to the system clipboard + through a deferred data function: + + import flash.desktop.ClipboardFormats; + + Clipboard.generalClipboard.setDataHandler(ClipboardFormats.TEXT_FORMAT, randomNumberGenerator); + + public function randomNumberGenerator():String{ + return Math.random().toString(); + } +
setData()flash.desktop.ClipboardFormatsflash.desktop.URLFilePromise
setData + Adds a representation of the information to be transferred in the specified data format.The Clipboard object requested is no longer in scope (which can occur + with clipboards created for drag-and-drop operations). + + IllegalOperationErrorflash.errors:IllegalOperationErrorReading from or writing to the clipboard is not permitted in this context. + In Flash Player, you can only call this method successfully during the processing of a user event + (as in a key press or mouse click). In AIR, this restriction only applies to content outside of the + application security sandbox. + + SecurityErrorSecurityErrorformat or data is null. + + TypeErrorTypeErrortrue if the data was succesfully set; + false otherwise. In Flash Player, returns false when format is an + unsupported member of ClipboardFormats. (Flash Player does not support ClipboardFormats.URL_FORMAT, + ClipboardFormats.FILE_LIST_FORMAT, ClipboardFormats.FILE_PROMISE_LIST_FORMAT, + or ClipboardFormats.BITMAP_FORMAT). + + BooleanformatStringThe format of the data. + dataObjectThe information to add. + serializableBooleantrueSpecify true for objects that can be serialized (and deserialized). + + + Adds a representation of the information to be transferred in the specified data format. + +

In the application sandbox of Adobe AIR, setData() can be called anytime. In other + contexts, setData() can only be called in response to a user-generated event such as + a key press or mouse click.

+ +

Different representations of the same information can be added to the clipboard as + different formats, which increases the ability of other components or applications to + make use of the available data. + For example, an image could be added as bitmap data for use by image editing applications, + as a URL, and as an encoded PNG file for transfer to the native file system.

+ +

The data parameter must be the appropriate data type for the specified format:

+ FormatTypeDescriptionClipboardFormats.TEXT_FORMATStringstring dataClipboardFormats.HTML_FORMATStringHTML string dataClipboardFormats.URL_FORMATStringURL string (AIR only)ClipboardFormats.RICH_TEXT_FORMATByteArrayRich Text Format dataClipboardFormats.BITMAP_FORMATBitmapDatabitmap data (AIR only)ClipboardFormats.FILE_LIST_FORMATarray of Filean array of files (AIR only)Custom format nameanyobject reference and serialized clone + +

Custom format names cannot begin with "air:" or "flash:". To prevent name collisions + when using custom formats, you may want to use your application ID or a package name as a + prefix to the format, such as "com.example.applicationName.dataPacket".

+ +

When transferring within or between applications, the serializable parameter + determines whether both a reference and a copy are available, or whether only a reference to + an object is available. Set serializable to true to make both the reference + and a copy of the data object available. Set serializable to false + to make only the object reference available. Object references are valid only within the current + application so setting serializable to false also means that the data + in that format is not available to other Flash Player or AIR applications. A component can choose to get + the reference or the copy of the object by setting the appropriate clipboard transfer mode + when accessing the data for that format.

+ +

Note: The standard formats are always converted to native formats when data is pasted or + dragged outside a supported application, so the value of the serializable + parameter does not affect the availability of data in the standard formats to non-Flash-based applications.

+ +

To defer rendering of the data for a format, use the setDataHandler() method instead. + If both the setData() and the setDataHandler() methods are used to add a + data representation with the same format name, then the handler function will never be called.

+ +

Note: On Mac OS, when you set the format parameter to ClipboardFormats.URL_FORMAT, + the URL is transferred only if it is a valid URL. Otherwise, the Clipboard object is emptied (and calling + getData() returns null).

+ +
The following example adds content to the system clipboard in both + text and HTML formats: + + import flash.desktop.ClipboardFormats; + + var htmlString:String = "<html><body>Body content</body></html>"; + Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, urlString); + Clipboard.generalClipboard.setData(ClipboardFormats.HTML_FORMAT, urlString); +
setDataHandler()getData()flash.desktop.ClipboardFormatsflash.desktop.ClipboardTransferMode
formats + An array of strings containing the names of the data formats available + in this Clipboard object.Array + An array of strings containing the names of the data formats available + in this Clipboard object. + +

String constants for the names of the standard formats are defined in the + ClipboardFormats class. Other, application-defined, strings may also be used as format + names to transfer data as an object.

+ +
The following example reads the formats array of the system clipboard: + + var availableFormats:Array = Clipboard.generalClipboard.formats; +
flash.desktop.ClipboardFormats
generalClipboard + The operating system clipboard.flash.desktop:Clipboard + The operating system clipboard. + +

Any data pasted to the system clipboard is available to other + applications. This may include insecure remote code running in + a web browser.

+ +

Note: In Flash Player 10 applications, a paste operation from the clipboard first + requires a user event (such as a keyboard shortcut for the Paste command or a mouse click on the Paste command + in a context menu). Clipboard.getData() + will return the contents of the clipboard only if the InteractiveObject has received + and is acting on a paste event. Calling Clipboard.getData() under any other circumstances + will be unsuccessful. The same restriction applies in AIR for content outside the + application sandbox.

+ +

The generalClipboard object is created automatically. + You cannot assign another instance of a Clipboard to this property. + Instead, you use the getData() and setData() + methods to read and write data to the existing object.

+ +

You should always clear the clipboard before writing new data to it + to ensure that old data in all formats is erased.

+ +

The generalClipboard object cannot be passed to the AIR NativeDragManager. + Create a new Clipboard object for native drag-and-drop operations in an AIR application.

+ +
To write to the operating system clipboard: + + import flash.desktop.ClipboardFormats; + + var copy:String = "A string to copy to the system clipboard."; + Clipboard.generalClipboard.clear(); + Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, copy); + To read from the operating system clipboard: + + import flash.desktop.ClipboardFormats; + + var pasteData:String = Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT) as String; +
supportsFilePromise + Indicates whether the file promise clipboard format is supported on the client system.Boolean + Indicates whether the file promise clipboard format is supported on the client system. + +
NotificationType + The NotificationType class defines constants for use in the priority + parameter of the DockIcon bounce() method and the type + parameter of the NativeWindow notifyUser() method.Object + The NotificationType class defines constants for use in the priority + parameter of the DockIcon bounce() method and the type + parameter of the NativeWindow notifyUser() method. + + flash.desktop.DockIcon.bounce()flash.display.NativeWindow.notifyUser()CRITICAL + Specifies that a notification alert is critical in nature and the user should attend to it promptly.criticalString + Specifies that a notification alert is critical in nature and the user should attend to it promptly. + + INFORMATIONAL + Specifies that a notification alert is informational in nature and the user can safely ignore it.informationalString + Specifies that a notification alert is informational in nature and the user can safely ignore it. + + IFilePromise + The IFilePromise interface defines the interface used by the AIR runtime to read data for a file promise. + The IFilePromise interface defines the interface used by the AIR runtime to read data for a file promise. + +

A file promise is a drag-and-drop clipboard format that allows a user to drag a file that does not yet + exist out of an AIR application. AIR uses the methods and properties defined by the IFilePromise interface + to access the data to be written when the file promise is dropped.

+ +

When a file promise is dropped on a suitable target, AIR calls the IFilePromise open() + method. The implementation of this method must return the data provider as an object that implements the IDataInput interface. + The provider object can be one of the built-in classes, such as ByteArray, FileStream, Socket, and URLStream, or + it can be a custom class.

+ +

If the data from the data provider is accessed synchronously, such as with a ByteArray, AIR reads the amount of data indicated by the IDataInput + bytesAvailable property and writes it to the destination file.

+ +

If the data from the data provider is accessed asynchronously, such as with a Socket, AIR uses events dispatched by the provider to regulate + the process of reading the data and writing it to the file. Data is read at each progress event until a complete or a close + event is received. The runtime listens for the following events (but a data provider does not need to dispatch every event):

+
  • Event.OPEN
  • ProgressEvent.PROGRESS
  • ProgressEvent.SOCKET_DATA
  • Event.COMPLETE
  • Event.CLOSE
  • IOErrorEvent.IOERROR
  • SecurityErrorEvent.SECURITY_ERROR
  • HTTPStatusEvent.HTTP_STATUS
  • HTTPStatusEvent.HTTP_RESPONSE_STATUS
+ +

Custom data provider classes should dispatch either a progress event or a socketData + event when data is available. Likewise, either a complete or a close event should be + dispatched when all the requested data has been read. The error events inform the runtime that the data transfer + has failed and should be aborted. The other events should be dispatched as appropriate to + aid in error handling and in debugging application logic.

+ +

The methods defined by IFilePromise are only intended to be called by the AIR runtime after a drag and drop operation has completed. + Developers should not typically call these methods from their own code.

+ +

Note: The URLFilePromise class, available in the air.desktop library implements the IFilePromise interface and uses the URLStream as + a data provider. The air.desktop library is included as separate SWF and SWC files in the AIR SDK.

+ +
flash.desktop.Clipboardflash.desktop.ClipboardFormatsflash.desktop.NativeDragManagerclose + Called by the AIR runtime when it has finished reading all data. + Called by the AIR runtime when it has finished reading all data. + +

No methods will be called on the object reference returned by open() after close() has been called. + The data provider object can be safely destroyed.

+ +
open + Returns the data provider object.IDataInput An object implementing the IDataInput interface. If the data is provided asynchronously, + the returned object must also implement the IEventDispatcher interface. + + flash.utils:IDataInput + Returns the data provider object. + +

The data provider object must implement the IDataInput interface, which defines methods for reading + data. If the IFilePromise isAsync property returns true, then the data + provider object must also implement the IEventDispatcher interface. The following built-in classes can + be used as a data provider:

+
  • ByteArray (synchronous)
  • FileStream (synchronous or asynchronous)
  • Socket (asynchronous)
  • URLStream (asynchronous)
+

You can also provide an object of a custom class that implements the required interfaces (or extends + another class that implements them).

+ +
reportError + Called by the AIR runtime to inform the IFilePromise implementation of errors + that occur when reading data from the data provider object.eflash.events:ErrorEventThe error event containing detailed error information. + + + Called by the AIR runtime to inform the IFilePromise implementation of errors + that occur when reading data from the data provider object. + + isAsync + Indicates whether asynchronous data transfer is supported.Boolean + Indicates whether asynchronous data transfer is supported. + +

If true, then the data provider object returned by the open() method must implement the + IEventDispatcher interface (or extend a class implementing this interface). The data transfer is driven by + progress or socketData events. AIR waits for these data progress events until a + complete or a close event is dispatched.

+ +

If isAsync returns false, then the AIR runtime assumes that all data is available immediately. + In this case, the runtime reads the bytesAvailable property of the data provider object + to determine the amount of data available and synchronously reads that amount of data.

+ +
relativePath + The relative path and file name of the file that will be created by this file promise.Stringif the relative path uses .. shortcuts to traverse one or more parent directories + of the drop target. + + ArgumentErrorArgumentError + The relative path and file name of the file that will be created by this file promise. + +

This property must provide a valid path or an argument error is thrown when the file promise is dropped.

+ +

The path can include subdirectories, which are resolved based on the drop location. The subdirectories are created, + if needed. When including subdirectories, use the File.separator constant to insert the + proper path separator character for the current operating system. Using the .. shortcut to navigate to a parent directory + is not allowed. If attempted, an argument error is thrown. Invalid file system characters are stripped from the path + without throwing an error.

+ +

Note: To allow client code to set the path, you can implement a setter function with the signature: + function set relativePath( value:String ):void.

+ +
NativeProcessStartupInfo + This class provides the basic information used to start a process on the host operating system.Object + This class provides the basic information used to start a process on the host operating system. + It is constructed and passed to the start() method of a NativeProcess object. + +

Native process access is only available to AIR applications installed with native installers + (applications in the extended desktop profile).

+ +
NativeProcess.html#start()NativeProcessStartupInfo + Constructs an empty NativeProcessStartupInfo object. + Constructs an empty NativeProcessStartupInfo object. + + arguments + The command line arguments that will be passed to the process on startup. + The command line arguments that will be passed to the process on startup. + +

Each string in the arguments Vector will be passed as a separate argument + to the executable, regardless of what characters the string contains. In other words, + there is an exact one-to-one correspondence; no re-interpretation occurs. AIR automatically + escapes any characters in the string that need to be escaped (such as space characters).

+ + +
executable + The File object that references an executable on the host operating system.flash.filesystem:Fileif the value specified is null, if it references + a directory, or if it references a file that does not exist. + + ArgumentErrorArgumentError + The File object that references an executable on the host operating system. + This should be the full path to the executable including any extension required. + +

Note: On Mac OS, to launch an executable within an application + bundle, be sure to have the path of the File object include the full path the the + executable (within the bundle), not just the path to the app file.

+ +
workingDirectory + The File object that references the initial working directory for the + new native process.flash.filesystem:Fileif the value doesn't exist or is not a directory + + ArgumentErrorArgumentError + The File object that references the initial working directory for the + new native process. If assigned a value where isDirectory is false, an ArgumentError + is thrown. +
SystemIdleMode + The SystemIdleMode class provides constant values for system idle behaviors.Object + The SystemIdleMode class provides constant values for system idle behaviors. These constants are used in + the systemIdleMode property of the NativeApplication class. + + flash.desktop.NativeApplication.systemIdleModeKEEP_AWAKE + Prevents the system from dropping into an idle mode.keepAwakeString + Prevents the system from dropping into an idle mode. + +

On Android, the application must specify the Android permissions for DISABLE_KEYGUARD and WAKE_LOCK in the application descriptor or the + operating system will not honor this setting.

+ +
NORMAL + The system follows the normal "idle user" behavior.normalString + The system follows the normal "idle user" behavior. + +
ClipboardTransferMode + The ClipboardTransferMode class defines constants for the modes used as values of the transferMode + parameter of the Clipboard.getData() method.Defines constants for the clipboard transfer modes. + + Object + The ClipboardTransferMode class defines constants for the modes used as values of the transferMode + parameter of the Clipboard.getData() method. + +

The transfer mode provides a hint about whether to return a reference or a + copy when accessing an object contained on a clipboard.

+ +
flash.desktop.Clipboard.getData()CLONE_ONLY + The Clipboard object should only return a copy.cloneOnlyString + The Clipboard object should only return a copy. + + CLONE_PREFERRED + The Clipboard object should return a copy if available and a reference if not.clonePreferredString + The Clipboard object should return a copy if available and a reference if not. + + ORIGINAL_ONLY + The Clipboard object should only return a reference.originalOnlyString + The Clipboard object should only return a reference. + + ORIGINAL_PREFERRED + The Clipboard object should return a reference if available and a copy if not.originalPreferredString + The Clipboard object should return a reference if available and a copy if not. + +
NativeDragManager + The NativeDragManager class coordinates drag-and-drop operations.Object + The NativeDragManager class coordinates drag-and-drop operations. With the native drag-and-drop API, + you can allow a user to drag data between an AIR application and the native operating system, + between two applications, or between components within a single application. + +

The following kinds of data can be transferred:

+
  • Bitmaps
  • Files
  • Text
  • URL strings
  • Serialized objects
  • Object references (valid only within the originating application)
+ +

Note: all NativeDragManager members are static. An instance of this class does not need to be created.

+ +

A drag-and-drop operation is a user interface gesture that begins with the user clicking a visible item and + dragging it elsewhere. During the drag gesture, interactive objects on the display list dispatch native drag events + as the gesture moves across the AIR application window. Handlers for these events can call + the methods of the NativeDragManager class to indicate whether a dragged item + can be dropped on an object. In response, the NativeDragManager changes the mouse pointer to provide + feedback to the user.

+ +

AIR profile support: This feature is not supported + on AIR for TV devices. Also, it is not supported on all mobile devices. You can test + for support at run time using the NativeDragManager.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles. +

+ +

Drag actions

+

Drag-and-drop gestures are typically used for three types of operations, called actions. + Since the meaning of these actions depends on the application context, + the runtime does not enforce any particular behavior with respect to actions. + However, properly implementing the actions improves the user experience with your application. +

+ +

The possible actions are:

+
  • Copy — A copy of the data is made, leaving the original untouched. + (When dragging objects within an application, care should be taken to copy the + original object itself rather than the reference to that object.)
  • Move — The data is moved from its original context into the context defined by the drop target, + such as when moving an item from one list to another.
  • Link — A reference or shortcut to the original data is created, + leaving the item in its original context.
+ +

The allowed actions can be set for a drag gesture by supplying an allowedActions parameter + in the NativeDragManager.doDrag() call that starts the drag operation. + If no allowedActions parameter is provided, all + of the actions are allowed. Potential drag targets can check which actions are allowed by using the + allowedActions property of a NativeDragEvent object, and should not accept a drop + that allows only incompatible actions (this is not enforced by the runtime, however).

+ +

If a drop target only implements a single action, the object can set the + dropAction property of the NativeDragManager in the handlers for both + the nativeDragEnter and nativeDragOver events. Setting the + property before the drop, allows the drag manager to update the mouse pointer to + indicate the supported action and also prevents + a user from choosing an incompatible action using modifier keys. If the specified action + is not one of the allowed actions, then a drop is not allowed, even if the target calls the + acceptDrop() method.

+ +

When accepting a drop, a potential drop target should specify the action chosen + by setting the NativeDragManager.dropAction property in response to the + nativeDragDrop event. This action is reported back to the initiating + display object in the nativeDragComplete event. If no action is set by a drop target, + then a default action is chosen from the allowed actions in this order of + precedence: copy, move, link. The initiating object is responsible + for updating its internal state in response to the chosen action.

+ +

String constants for the action names are defined in the NativeDragActions class.

+ +

Sequence of events

+

A drag gesture is begun by calling the NativeDragManager.doDrag() method + within a mouseDown or mouseMove event handler and + proceeds through the following event sequence in response to user actions:

+
  • nativeDragStart event — When NativeDragManager.doDrag() is called, + the interactive object passed as a paramter to the method becomes the initiator + object and dispatches a nativeDragStart event.
  • nativeDragUpdate event — While the drag is in progress, the initiator object continually + dispatches nativeDragUpdate events.
  • nativeDragEnter, nativeDragOver events — When a drag + gesture passes over an interactive object, that object dispatches a nativeDragEnter event. + While the drag gesture remains over the interactive object, + it continually dispatches nativeDragOver events. In response to either of these events, + an object that serves as a potential drop target should check the properties of the event object + to decide whether it can accept the drop. If the data format and allowed + actions are appropriate, then the event handler for these events must call + NativeDragManager.acceptDrop(), passing in a reference to the + display object to serve as the drag target (typically the object that + dispatched the nativeDragEnter or nativeDragOver event). + The user can then drop the dragged item onto the target.
  • nativeDragExit event — When a drag gesture passes out of an + interactive object, the object dispatches a nativeDragExit event. + If the object had been designated as the drag target by an earlier call to the + NativeDragManager.acceptDrop() method, that call is no longer valid + and acceptDrop() must be called again if the gesture re-enters the interactive object.
  • nativeDragDrop event — The target display object dispatches a + nativeDragDrop event when the user releases the mouse button over the object. + The handler for this event can access the data in the transferable + property of the event object and should set the NativeDragManager.dropAction property to + signal which action should be taken by the initiator object.
  • nativeDragComplete — When the user releases the mouse button at the end of a drag gesture, + the initiator object dispatches a nativeDragComplete event (whether or not the drop itself was consumated). + The handler for this event can check the dropAction property of the event object to determine what, + if any, modification should be made to its internal data state, such as removing a dragged-out item from a list. + If dropAction is NativeDragActions.NONE, then the dragged item was not dropped on an eligible target.
+ +

Gestures between applications

+

When a drag gesture enters an AIR application window from a non-AIR application, + there is no initiator object to dispatch the nativeDragStart or nativeDragComplete + event. The events dispatched during the gesture will otherwise follow the same + pattern as that of a gesture starting and ending within the same AIR application.

+ +

When a drag gesture leaves an AIR application window, there is no target object to dispatch + nativeDragEnter, nativeDragOver, or nativeDragDrop events. The initiator object + still dispatches a nativeDragComplete event, which reports the drag action set + by the native operating system (or none, if the drop was not accepted).

+ +

When a drag gesture moves from one AIR application to another, the initiator + and target display objects dispatch events within their separate applications + as usual.

+ +

Transfering information

+

The data transfered during a drag-and-drop gesture is contained in a Clipboard object. + This data object is added to the drag operation with the + NativeDragManager.doDrag() method that starts the drag gesture. + Potential drop targets can access the Clipboard object through the + clipboard property of the native drag event + object. Once a drag operation has started, the Clipboard object can + only be accessed in the event handler of a NativeDragEvent. Any other attempt + to access the object generates a run-time error.

+ +

Security considerations

+

The security sandboxes of the initiator and potential target objects determine how the + the data being dragged can be accessed. If both objects are in the same sandbox, + then the data can be accessed from any NativeDragEvent object. However, + if the initiator and target objects are in different sandboxes, the data can + only be accessed in the target sandbox within the event + handler for the nativeDragDrop event. Other native drag event handlers can still + still access the Clipboard object referenced in the event clipboard + property to determine which data formats are available, but calling the + clipboard.getData() method generates a security error.

+ +
flash.events.NativeDragEventflash.desktop.NativeDragActionsflash.desktop.NativeDragOptionsflash.desktop.ClipboardacceptDragDrop + Informs the NativeDragManager object that the specified target interactive object can accept a drop + corresponding to the current drag event.targetflash.display:InteractiveObject + Informs the NativeDragManager object that the specified target interactive object can accept a drop + corresponding to the current drag event. + +

This method should be called only when there is a nativeDragDrop + handler on the specified target object that can handle at least one of the + data formats in the dragged item and at least one of the allowed actions.

+ +

This function can be called only within a nativeDragEnter or nativeDragOver + event handler.

+ +
doDrag + Starts a drag-and-drop operation.dragInitiatorflash.display:InteractiveObjectTypically the object from which the drag gesture began. Receives the nativeDragStart + and nativeDragComplete events. + + clipboardflash.desktop:ClipboardThe container object for data being dragged. + + dragImageflash.display:BitmapDatanullAn optional proxy image displayed under the mouse pointer + during the drag gesture. If null, no image is displayed. + + offsetflash.geom:PointnullThe offset between the mouse hotspot and the top left + corner of the drag image. Negative coordinates move the image up and + to the left in relation to the hotspot. If null, the top + left corner of the drag image is positioned at the mouse hotspot. + + allowedActionsflash.desktop:NativeDragOptionsnullRestricts the drag-and-drop actions allowed for + this operation. If null, all actions are allowed. + + + Starts a drag-and-drop operation. + +

To start a drag operation:

+
  1. Create a new Clipboard object.
  2. Add the data to be transferred in one or more formats.
  3. Optionally, create a BitmapData object to serve as a proxy image during the drag.
  4. Optionally, create a NativeDragOptions object to restrict the actions allowed in this operation. + (If the allowedActions parameter is left null, all actions are allowed.)
  5. Call NativeDragManager.doDrag().
+ +

The initiator object dispatches a nativeDragStart event after this method is called, + nativeDragStart events while the drag is in progress, and a + nativeDragComplete event when the user releases the mouse button to end the drag gesture. + The handler for the nativeDragComplete event can check the dropAction property of the + event to determine whether the drag-and-drop operation was successfully completed. + If dropAction is NativeDragActions.NONE, then the dragged item was not dropped + on an eligible target.

+ +

This method can be called only from within a mouseDown or + mouseMove event handler. (If called in response to a + mouseMove event, the mouse button must also be down.)

+ +
flash.desktop.NativeDragActions
dragInitiator + The interactive object passed to the NativeDragManager.doDrag() call that initiated the drag operation.flash.display:InteractiveObject + The interactive object passed to the NativeDragManager.doDrag() call that initiated the drag operation. + + dropAction + The drag action specified by the drop target.String + The drag action specified by the drop target. + +

The dropAction property + should be set in the handler for the nativeDragDrop event. + If dropAction is not set before the nativeDragComplete, + the NativeDragManager sets the value with the first + allowed action from the list: copy, move, or link (in that order).

+ +
flash.desktop.NativeDragActions
isDragging + Reports whether a drag operation is currently in progress.Boolean + Reports whether a drag operation is currently in progress. + + isSupported + The isSupported property is set to true if the + NativeDragManager class is supported on the current platform, otherwise it is + set to false.BooleanReports whether native drag-and-drop operations are supported. + + + The isSupported property is set to true if the + NativeDragManager class is supported on the current platform, otherwise it is + set to false. + +
NativeDragOptions + The NativeDragOptions class defines constants for the names of drag-and-drop actions allowed in a drag-and-drop operation.Object + The NativeDragOptions class defines constants for the names of drag-and-drop actions allowed in a drag-and-drop operation. + +

Drag actions are part of a feedback mechanism to allow the initiating and + target objects to cooperate in the drag-and-drop exchange. The actions are only + a hint to the operating system. It is up to the drag initiator and target objects + involved in the transaction to implement the proper behavior.

+ +

An initiating object should only allow the actions that it supports. For example, + an initiating object should allow the move action only if that object's internal + logic removes the source data when a target accepts a drop with a move action.

+ + +

A new NativeDragOptions object has all properties initialized to + true (all actions allowed).

+ +
flash.desktop.NativeDragManagerflash.events.NativeDragEventtoString + Constructs a string containing the current settings of this NativeDragOptions object.String The current settings of this object in a string. + + String + Constructs a string containing the current settings of this NativeDragOptions object. + + allowCopy + A drop target is allowed to copy the dragged data.trueBoolean + A drop target is allowed to copy the dragged data. + + allowLink + A drop target is allowed to create a link to the dragged data.trueBoolean + A drop target is allowed to create a link to the dragged data. + + allowMove + A drop target is allowed to move the dragged data.trueBoolean + A drop target is allowed to move the dragged data. + +
DockIcon + The DockIcon class represents the Mac OS X&#xAE;-style dock icon.The Mac OS X-style dock icon. + + flash.desktop:InteractiveIcon + The DockIcon class represents the Mac OS X®-style dock icon. + +

AIR profile support: This feature is supported on + all desktop operating systems, but it is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the NativeApplication.supportsDockIcon property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

You can use the DockIcon class to change the appearance of the standard + icon; for example, to animate the icon or add informational graphics. + You can also add items to the dock icon menu. The menu items that you add are displayed above + the standard menu items.

+ +

An instance of the DockIcon class cannot be created. Get the object + representing the operating system dock icon from NativeApplication.icon. +

+ +

Not all operating systems have dock icons. Check NativeApplication.supportsDockIcon + to determine whether dock icons are supported on the current system. If dock + icons are supported, the NativeApplication.icon property is of type + DockIcon. Otherwise, the type of NativeApplication.icon is another + subclass of InteractiveIcon, typically SystemTrayIcon.

+ +

Important: Attempting to call a DockIcon class method on the + NativeApplication.icon object on an operating system for which AIR does not support dock icons + generates a run-time exception.

+ +
The following example loads a sequence of images and, + when the timer is started with the dock icon menu, animates the + icon image. (For the example to work, you must supply a set of icon + images and change the URLs in the imageURLs array.) + + + package { + import flash.desktop.DockIcon; + import flash.desktop.NativeApplication; + import flash.display.Loader; + import flash.display.NativeMenu; + import flash.display.NativeMenuItem; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.TimerEvent; + import flash.net.URLRequest; + import flash.utils.Timer; + + public class AnimatedDockIcon extends Sprite + { + private var imageURLs:Array = ['gfx/frame01.png', + 'gfx/frame02.png', + 'gfx/frame03.png', + 'gfx/frame04.png']; + + private var images:Array = new Array(); + private var animTimer:Timer = new Timer(100); + + public function AnimatedDockIcon() + { + NativeApplication.nativeApplication.autoExit = false; + + addEventListener(Event.COMPLETE, loadImages); + loadImages(); + + animTimer.addEventListener(TimerEvent.TIMER,advanceFrame); + addMenu(); + stage.nativeWindow.close(); + } + + private function addMenu():void{ + var menu:NativeMenu = new NativeMenu(); + var start:NativeMenuItem = menu.addItem(new NativeMenuItem("Start animation")); + var stop:NativeMenuItem = menu.addItem(new NativeMenuItem("Stop animation")); + start.addEventListener(Event.SELECT, startTimer); + stop.addEventListener(Event.SELECT, stopTimer); + + var dockIcon:DockIcon = NativeApplication.nativeApplication.icon as DockIcon; + dockIcon.menu = menu; + } + + private function startTimer(event:Event):void{ + animTimer.start(); + } + + private function stopTimer(event:Event):void{ + animTimer.stop(); + } + + private var currentFrame:int = 0; + private function advanceFrame(event:Event):void{ + if(currentFrame < images.length){ + currentFrame++; + } else { + currentFrame = 0; + } + NativeApplication.nativeApplication.icon.bitmaps = [images[currentFrame]]; + } + + + private function loadImages(event:Event = null):void{ + if(event != null){ + images.push(event.target.content.bitmapData); + } + if(imageURLs.length > 0){ + var urlString:String = imageURLs.pop(); + var loader:Loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImages, false, 0, true); + loader.load(new URLRequest(urlString)); + } else { + var complete:Event = new Event(Event.COMPLETE,false,false); + dispatchEvent(complete); + } + } + } +} +
flash.desktop.NativeApplication.iconflash.desktop.NativeApplication.supportsDockIconflash.desktop.SystemTrayIconbounce + Notifies the user that an event has occurred that may require attention.NotificationType.Informational + + priorityStringinformationalThe urgency with which to bounce the dock. + + + Notifies the user that an event has occurred that may require attention. + +

Calling this method bounces the dock icon if, and only if, the + application is in the background. If the priority is + NotificationType.Informational then the icon bounces once. + If the priority is NotificationType.Critical then the + icon bounces until the application is brought to the foreground.

+ +
The following example bounces the dock icon until the user + activates the application: + + import flash.display.DockIcon; + import flash.display.NotificationType; + import flash.desktop.NativeApplication; + + if(NativeApplication.supportsDockIcon){ + var dockIcon:DockIcon = NativeApplication.nativeApplication.icon As DockIcon; + dockIcon.bounce(NotificationType.CRITICAL); + } + +
flash.desktop.NotificationTypeflash.display.NativeWindow.notifyUser()
bitmaps + + + The icon image as an array of BitmapData objects of different sizes.ArrayThe icon image as an array of BitmapData objects of different sizes. + + + + The icon image as an array of BitmapData objects of different sizes. + +

When an icon is displayed in a given operating system context, the bitmap + in the array closest to the displayed size is used (and + scaled if necessary). Common sizes include 16x16, 32x32, 48x48, and + 128x128. (512x512 pixel icons may be used for some operating system + icons in the near future.)

+ +

In some contexts, the operating system may use a default system icon + if nothing has been assigned to the bitmaps property. + In other contexts, no icon appears.

+ +

To set or change the icon appearance, assign an array of + BitmapData objects to the bitmaps property:

+ + + icon.bitmaps = new Array(icon16x16.bitmapData, icon128x128.bitmapData); + + +

Modifying the bitmaps array directly has no effect.

+ +

To clear the icon image, assign an empty array to the + bitmaps property.

+ +

+ Note: When loading image files for an icon, the PNG file format + generally provides the best alpha blending. The GIF format supports only + on or off transparency (no blending). The JPG format does not support + transparency at all. +

+ +
height + + The current display height of the icon in pixels.int + + The current display height of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The height property indicates the height of the icon chosen from the bitmaps array + for the current context. The actual display height may be different if the operating system + has scaled the icon.

+ +
menu + The system-supplied menu of this dock icon.flash.display:NativeMenu + The system-supplied menu of this dock icon. + +

Any items in the menu are displayed above the standard items. + The standard items cannot be modified or removed.

+ +
The following example adds an item to the dock icon menu: + + import flash.desktop.NativeApplication; + import flash.events.Event; + +private function createDockIconMenu():void{ + if(NativeApplication.supportsDockIcon){ + var dockIcon:DockIcon = NativeApplication.nativeApplication.icon as DockIcon; + + var dockMenu:NativeMenu = new NativeMenu(); + var command:NativeMenuItem = dockMenu.addItem(new NativeMenuItem("Command")); + command.addEventListener(Event.SELECT, onCommand); + + dockIcon.menu = dockMenu; + } +} + + private function onCommand(event:Event):void{ + //do command... + } +
width + + The current display width of the icon in pixels.int + + The current display width of the icon in pixels. + +

Some icon contexts support dynamic sizes. + The width property indicates the width of the icon chosen from the bitmaps array + for the current context. The actual display width may be different if the operating system + has scaled the icon.

+ +
Icon + The Icon class represents an operating system icon.flash.events:EventDispatcher + The Icon class represents an operating system icon. + +

An Icon object has one property, bitmaps, which is an array + of BitmapData objects. Only one image is displayed at a time. The operating + system selects the image closest in size to the icon's current display size, + scaling if necessary.

+ +
flash.filesystem.File.iconflash.display.BitmapDatabitmaps + The icon image as an array of BitmapData objects of different sizes.Array + The icon image as an array of BitmapData objects of different sizes. + +

When an icon is displayed in a given operating system context, the bitmap + in the array closest to the displayed size is used (and + scaled if necessary). Common sizes include 16x16, 32x32, 48x48, and + 128x128. (512x512 pixel icons may be used for some operating system + icons in the near future.)

+ +

In some contexts, the operating system may use a default system icon + if nothing has been assigned to the bitmaps property. + In other contexts, no icon appears.

+ +

To set or change the icon appearance, assign an array of + BitmapData objects to the bitmaps property:

+ + + icon.bitmaps = new Array(icon16x16.bitmapData, icon128x128.bitmapData); + + +

Modifying the bitmaps array directly has no effect.

+ +

To clear the icon image, assign an empty array to the + bitmaps property.

+ +

+ Note: When loading image files for an icon, the PNG file format + generally provides the best alpha blending. The GIF format supports only + on or off transparency (no blending). The JPG format does not support + transparency at all. +

+ +
flash.filesystem.File.iconflash.display.BitmapData
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.display.xml b/language-server/playerglobal_docs/flash.display.xml new file mode 100644 index 0000000..fdf153c --- /dev/null +++ b/language-server/playerglobal_docs/flash.display.xml @@ -0,0 +1,16412 @@ +flash.displayFrameLabel + + + The FrameLabel object contains properties that specify a frame number and the + corresponding label name.Object + + The FrameLabel object contains properties that specify a frame number and the + corresponding label name. + The Scene class includes a labels property, which is an array + of FrameLabel objects for the scene. + + Scene.labelsMovieClip.currentLabelMovieClip.currentSceneMovieClip.scenesMovieClip.gotoAndPlay()MovieClip.gotoAndStop()frame + The frame number containing the label.int + The frame number containing the label. + name + The name of the label.String + The name of the label. + InteractiveObject + The InteractiveObject class is the abstract base class for all display objects with which the user can + interact, using the mouse, keyboard, or other user input device.flash.display:DisplayObject + The InteractiveObject class is the abstract base class for all display objects with which the user can + interact, using the mouse, keyboard, or other user input device. + +

You cannot instantiate the InteractiveObject class directly. A call to the new + InteractiveObject() constructor throws an ArgumentError exception.

+ +

The InteractiveObject class itself does not include any APIs for rendering content onscreen. + To create a custom subclass of the InteractiveObject class, + extend one of the subclasses that do have APIs for rendering content onscreen, + such as the Sprite, SimpleButton, TextField, or MovieClip classes.

+ +
The following example uses the InteractiveObjectExample class, which in + turn uses the ChildSprite class to draw a rectangle and then manipulate that rectangle + based on various mouse events. This task is accomplished by performing the following steps: +
  1. In the InteractiveObjectExample constructor, a new ChildSprite object of type Sprite + called child is created, which calls the ChildSprite constructor method to draw the shape + and add mouse events for the shape (as explained in the following steps). The child + object is added to the top of the display list at coordinates x = 0, y = 0.
  2. In the ChildSprite class, declare the size and + overSize properties that are used later in the draw() method and + MouseEvent methods.
  3. Declare properties that set the background color to orange, the mouse-over color to + dark yellow, and the mouse-down color to light blue.
  4. In the ChildSprite constructor, an orange square is drawn by using methods from + the Graphics class and the draw() method.
  5. The constructor adds four MouseEvent event listener methods: + +
    • mouseOverHandler: redraws a larger 60 x 60 pixel square with a dark-yellow color + at the original coordinates.
    • mouseOutHandler: returns the square to its original size and color.
    • mouseDownHandler: redraws a larger 60 x 60 pixel square with a light-blue color + at the original coordinates.
    • mouseUpHandler: same as mouseOverHandler.
    +
+ + +package { + import flash.display.Sprite; + + public class InteractiveObjectExample extends Sprite { + + public function InteractiveObjectExample() { + var child:Sprite = new ChildSprite(); + addChild(child); + } + } +} + +import flash.display.Sprite; +import flash.events.MouseEvent; + +class ChildSprite extends Sprite { + private var size:uint = 50; + private var overSize:uint = 60; + private var backgroundColor:uint = 0xFFCC00; + private var overColor:uint = 0xCCFF00; + private var downColor:uint = 0x00CCFF; + + public function ChildSprite() { + buttonMode = true; + draw(size, size, backgroundColor); + addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); + addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); + addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + } + + private function draw(w:uint, h:uint, bgColor:uint):void { + graphics.clear(); + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, w, h); + graphics.endFill(); + } + + public function mouseOverHandler(event:MouseEvent):void { + trace("mouseOverHandler"); + draw(overSize, overSize, overColor); + } + + public function mouseOutHandler(event:MouseEvent):void { + trace("mouseOutHandler"); + draw(size, size, backgroundColor); + } + + public function mouseDownHandler(event:MouseEvent):void { + trace("mouseDownHandler"); + draw(overSize, overSize, downColor); + } + + public function mouseUpHandler(event:MouseEvent):void { + trace("mouseUpHandler"); + draw(overSize, overSize, overColor); + } +} +
softKeyboardDeactivate + Dispatched immediately after the soft keyboard is lowered.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATEflash.events.SoftKeyboardEventDispatched immediately after the soft keyboard is lowered. + + Dispatched immediately after the soft keyboard is lowered. + flash.events.SoftKeyboardEventsoftKeyboardActivate + Dispatched immediately after the soft keyboard is raised.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATEflash.events.SoftKeyboardEventDispatched immediately after the soft keyboard is raised. + + Dispatched immediately after the soft keyboard is raised. + flash.events.SoftKeyboardEventsoftKeyboardActivating + Dispatched immediately before the soft keyboard is raised.flash.events.SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATINGflash.events.SoftKeyboardEventDispatched immediately before the soft keyboard is raised. + + Dispatched immediately before the soft keyboard is raised. + flash.events.SoftKeyboardEventtextInput + Dispatched when a user enters one or more + characters of text.flash.events.TextEvent.TEXT_INPUTflash.events.TextEvent + Dispatched when a user enters one or more + characters of text. Various + text input methods can generate this event, including standard keyboards, + input method editors (IMEs), voice or speech recognition systems, and even the act + of pasting plain text with no formatting or style information. + imeStartComposition + This event is dispatched to any client app that supports inline input with an IME + + flash.events.IMEEvent + This event is dispatched to any client app that supports inline input with an IME + + contextMenu + Dispatched when a user gesture triggers the context menu associated with this interactive + object in an AIR application.flash.events.MouseEvent.CONTEXT_MENUflash.events.MouseEvent + Dispatched when a user gesture triggers the context menu associated with this interactive + object in an AIR application. + + contextMenunativeDragComplete + Dispatched by the drag initiator InteractiveObject when the user releases the drag gesture.flash.events.NativeDragEvent.NATIVE_DRAG_COMPLETEflash.events.NativeDragEvent + Dispatched by the drag initiator InteractiveObject when the user releases the drag gesture. + +

The event's dropAction property indicates the action set + by the drag target object; a value of "none" (DragActions.NONE) + indicates that the drop was canceled or was not accepted.

+ +

The nativeDragComplete event handler is a convenient place + to update the state of the initiating display object, for example, by removing + an item from a list (on a drag action of "move"), or by changing the visual + properties.

+ +
nativeDragUpdate + Dispatched during a drag operation by the InteractiveObject that is + specified as the drag initiator in the DragManager.doDrag() call.flash.events.NativeDragEvent.NATIVE_DRAG_UPDATEflash.events.NativeDragEvent + Dispatched during a drag operation by the InteractiveObject that is + specified as the drag initiator in the DragManager.doDrag() call. + +

nativeDragUpdate events are not dispatched on Linux.

+ +
nativeDragStart + Dispatched at the beginning of a drag operation by the InteractiveObject that is + specified as the drag initiator in the DragManager.doDrag() call.flash.events.NativeDragEvent.NATIVE_DRAG_STARTflash.events.NativeDragEvent + Dispatched at the beginning of a drag operation by the InteractiveObject that is + specified as the drag initiator in the DragManager.doDrag() call. + + nativeDragExit + Dispatched by an InteractiveObject when a drag gesture leaves its boundary.flash.events.NativeDragEvent.NATIVE_DRAG_EXITflash.events.NativeDragEvent + Dispatched by an InteractiveObject when a drag gesture leaves its boundary. + + nativeDragDrop + Dispatched by the target InteractiveObject when a dragged object is + dropped on it and the drop has been accepted with a call to + DragManager.acceptDragDrop().flash.events.NativeDragEvent.NATIVE_DRAG_DROPflash.events.NativeDragEvent + Dispatched by the target InteractiveObject when a dragged object is + dropped on it and the drop has been accepted with a call to + DragManager.acceptDragDrop(). + +

Access the dropped data using the event object clipboard + property.

+ +

The handler for this event should set the DragManager.dropAction + property to provide feedback to the initiator object about which drag action + was taken. If no value is set, the DragManager will select a default value + from the list of allowed actions.

+ +
nativeDragOver + Dispatched by an InteractiveObject continually while a drag gesture remains within its + boundary.flash.events.NativeDragEvent.NATIVE_DRAG_OVERflash.events.NativeDragEvent + Dispatched by an InteractiveObject continually while a drag gesture remains within its + boundary. + +

nativeDragOver events are dispatched whenever the mouse is moved. On Windows and + Mac, they are also dispatched on a short timer interval even when the mouse has not moved.

+ +

Handle either the nativeDragOver or nativeDragEnter + events to allow the display object to become the drop target.

+ +

To determine whether the dispatching display object can accept the drop, + check the suitability of the data in clipboard property of + the event object, and the allowed drag actions in the allowedActions + property.

+ +
nativeDragEnter + Dispatched by an InteractiveObject when a drag gesture enters its boundary.flash.events.NativeDragEvent.NATIVE_DRAG_ENTERflash.events.NativeDragEvent + Dispatched by an InteractiveObject when a drag gesture enters its boundary. + +

Handle either the nativeDragEnter or nativeDragOver + events to allow the display object to become the drop target.

+ +

To determine whether the dispatching display object can accept the drop, + check the suitability of the data in clipboard property of + the event object, and the allowed drag actions in the allowedActions + property.

+ +
tabIndexChange + Dispatched when the value of the object's tabIndex property changes.flash.events.Event.TAB_INDEX_CHANGEflash.events.Event + Dispatched when the value of the object's tabIndex property changes. + tabEnabledChange + Dispatched when the object's tabEnabled flag changes.flash.events.Event.TAB_ENABLED_CHANGEflash.events.Event + Dispatched when the object's tabEnabled flag changes. + tabChildrenChange + Dispatched when the value of the object's tabChildren flag changes.flash.events.Event.TAB_CHILDREN_CHANGEflash.events.Event + Dispatched when the value of the object's tabChildren flag changes. + keyUp + Dispatched when the user releases a key.flash.events.KeyboardEvent.KEY_UPflash.events.KeyboardEvent + Dispatched when the user releases a key. Mappings between keys and specific characters vary + by device and operating system. This event type is generated after such a mapping occurs + but before the processing of an input method editor (IME). IMEs are used to enter + characters, such as Chinese ideographs, that the standard QWERTY keyboard is + ill-equipped to produce. This event occurs after a keyDown event and has + the following characteristics: + keyDown + Dispatched when the user presses a key.flash.events.KeyboardEvent.KEY_DOWNflash.events.KeyboardEvent + Dispatched when the user presses a key. Mappings between keys and specific characters + vary by device and operating system. This event type is generated after such a mapping + occurs but before the processing of an input method + editor (IME). IMEs are used to enter characters, such as Chinese ideographs, that the standard QWERTY keyboard is ill-equipped + to produce. This event occurs before the keyUp event. + +

In AIR, canceling this event prevents the character from being entered into a text field.

+ +
rightMouseUp + Dispatched when a user releases the pointing device button over an + InteractiveObject instance.flash.events.MouseEvent.RIGHT_MOUSE_UPflash.events.MouseEvent + Dispatched when a user releases the pointing device button over an + InteractiveObject instance. + rightMouseDown + Dispatched when a user presses the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.RIGHT_MOUSE_DOWNflash.events.MouseEvent + Dispatched when a user presses the pointing device button over an InteractiveObject instance. + rightClick + Dispatched when a user presses and releases the right button of the user's + pointing device over the same InteractiveObject.flash.events.MouseEvent.RIGHT_CLICKflash.events.MouseEvent + Dispatched when a user presses and releases the right button of the user's + pointing device over the same InteractiveObject. For a rightClick event to occur, it must always follow this series of + events in the order of occurrence: rightMouseDown event, then rightMouseUp. The target object + must be identical for both of these events; otherwise the rightClick event does not + occur. Any number of other mouse events can occur at any time between the + rightMouseDown or rightMouseUp events; the rightClick event + still occurs. + middleMouseUp + Dispatched when a user releases the pointing device button over an + InteractiveObject instance.flash.events.MouseEvent.MIDDLE_MOUSE_UPflash.events.MouseEvent + Dispatched when a user releases the pointing device button over an + InteractiveObject instance. + middleMouseDown + Dispatched when a user presses the middle pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MIDDLE_MOUSE_DOWNflash.events.MouseEvent + Dispatched when a user presses the middle pointing device button over an InteractiveObject instance. + middleClick + Dispatched when a user presses and releases the middle button of the user's + pointing device over the same InteractiveObject.flash.events.MouseEvent.MIDDLE_CLICKflash.events.MouseEvent + Dispatched when a user presses and releases the middle button of the user's + pointing device over the same InteractiveObject. For a middleClick event to occur, it must always follow this series of + events in the order of occurrence: middleMouseDown event, then middleMouseUp. The target object + must be identical for both of these events; otherwise the middleClick event does not + occur. Any number of other mouse events can occur at any time between the + middleMouseDown or middleMouseUp events; the middleClick event + still occurs. + gestureSwipe + Dispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three + fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_SWIPEflash.events.TransformGestureEvent + Dispatched when the user performs a swipe gesture at a point of contact with an InteractiveObject instance (such as touching three + fingers to a screen and then moving them in parallel over a display object on a mobile phone or tablet with a touch screen). + Moving several fingers in parallel is a common swipe gesture, + but each device and operating system can have its own requirements for a swipe. + Some devices might also interpret this contact as a combination of several mouse events, as well. +

Specifically, if a user moves a finger over an InteractiveObject, and then moves the fingers together, the InteractiveObject instance can + dispatch a rollOver + event and a rollOut event (among others), in addition to the gestureSwipe event, or all if the current environment supports it. + Choose how you want to handle the user interaction. + If you choose to handle the rollOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gestureSwipe event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

When handling the properties of the event object, note that the localX and localY properties are set to the + primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the swipe gesture + is complete.

+

Note: While some devices using the Mac OS operating system can + interpret a four-finger swipe, this API only supports a three-finger swipe.

+
The following example shows event handling for the GESTURE_SWIPE events. + While the user performs a swipe gesture on the touch-enabled device, myTextField populates with the phase all, + which is the only phase for swipe events. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onSwipe(evt:TransformGestureEvent):void { + + if (evt.offsetX == 1 ) { + myTextField.text = "right"; + } + if (evt.offsetY == -1) { + myTextField.text = "up"; + } + myTextField.text = evt.phase; + +} +
rollOver eventtouchOver eventflash.ui.Multitouch
gestureZoom + Dispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two + fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_ZOOMflash.events.TransformGestureEvent + Dispatched when the user performs a zoom gesture at a point of contact with an InteractiveObject instance (such as touching two + fingers to a screen and then quickly spreading the fingers apart over a display object on a mobile phone or tablet with a touch screen). + Moving fingers apart is a common zoom gesture, + but each device and operating system can have its own requirements to indicate zoom. + Some devices might also interpret this contact as a combination of several mouse events, as well. +

Specifically, if a user moves a finger over an InteractiveObject, and then moves the fingers apart, the InteractiveObject instance can + dispatch a mouseOver + event and a click event (among others), in addition to the gestureZoom event, or all if the current environment supports it. + Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gestureZoom event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

When handling the properties of the event object, note that the localX and localY properties are set to the + primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the zoom gesture + is complete.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the GESTURE_ZOOM events. + While the user performs a zoom gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onZoom(evt:TransformGestureEvent):void { + + evt.target.scaleX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
mouseOver eventtouchOver eventflash.ui.Multitouch
gestureRotate + Dispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers + and rotating them over a display object on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_ROTATEflash.events.TransformGestureEvent + Dispatched when the user performs a rotation gesture at a point of contact with an InteractiveObject instance (such as touching two fingers + and rotating them over a display object on a mobile phone or tablet with a touch screen). Two-finger rotation is a common rotation gesture, + but each device and operating system can have its own requirements to indicate rotation. + Some devices might also interpret this contact as a combination of several mouse events, as well. +

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can + dispatch a mouseOver + event and a click event (among others), in addition to the gestureRotate event, or all if the current environment supports it. + Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gestureRotate event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

When handling the properties of the event object, note that the localX and localY properties are set to the + primary point of contact. The offsetX and offsetY properties are the distance to the point of contact where the rotation gesture + is complete.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the GESTURE_ROTATE events. + While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onRotate(evt:TransformGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
mouseOver eventtouchOver eventflash.ui.Multitouch
gesturePressAndTap + Dispatched when the user creates a point of contact with an InteractiveObject instance, then taps + on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item + on a mobile phone or tablet with a touch screen).flash.events.PressAndTapGestureEvent.GESTURE_PRESS_AND_TAPflash.events.PressAndTapGestureEvent + Dispatched when the user creates a point of contact with an InteractiveObject instance, then taps + on a touch-enabled device (such as placing several fingers over a display object to open a menu and then taps one finger to select a menu item + on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a combination of several mouse events, as well. +

Specifically, if a user moves a finger over an InteractiveObject, and then provides a secondary tap, the InteractiveObject instance can + dispatch a mouseOver + event and a click event (among others) as well as the gesturePressAndTap event, or all if the current environment supports it. + Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gesturePressAndTap event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

When handling the properties of the event object, note that the localX and localY properties are set to the + primary point of contact (the "push"). The offsetX and offsetY properties are the distance to the secondary point of + contact (the "tap").

+
mouseOver eventtouchOver eventflash.ui.Multitouch
gesturePan + Dispatched when the user moves a point of contact over the InteractiveObject instance + on a touch-enabled device (such as moving a finger from left to right over a display object + on a mobile phone or tablet with a touch screen).flash.events.TransformGestureEvent.GESTURE_PANflash.events.TransformGestureEvent + Dispatched when the user moves a point of contact over the InteractiveObject instance + on a touch-enabled device (such as moving a finger from left to right over a display object + on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseOver event and as a touchOver event. +

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a mouseOver + event or a touchOver event or a gesturePan event, or all if the current environment supports it. + Choose how you want to handle the user interaction. Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gesturePan event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the GESTURE_PAN events. + While the user performs a pan gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onPan(evt:TransformGestureEvent):void { + + evt.target.localX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
mouseOver eventtouchOver eventflash.ui.Multitouch
gestureTwoFingerTap + Dispatched when the user presses two points of contact over the same InteractiveObject instance + on a touch-enabled device (such as presses and releases two fingers over a display object + on a mobile phone or tablet with a touch screen).flash.events.GestureEvent.GESTURE_TWO_FINGER_TAPflash.events.GestureEvent + Dispatched when the user presses two points of contact over the same InteractiveObject instance + on a touch-enabled device (such as presses and releases two fingers over a display object + on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a doubleClick event. +

Specifically, if a user taps two fingers over an InteractiveObject, the InteractiveObject instance can dispatch a doubleClick + event or a gestureTwoFingerTap event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the doubleClick event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the gestureTwoFingerTap event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
doubleClick eventflash.ui.Multitouch
touchTap + Dispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated + on a touch-enabled device (such as presses and releases a finger from a single point over a display object + on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_TAPflash.events.TouchEvent + Dispatched when the user lifts the point of contact over the same InteractiveObject instance on which the contact was initiated + on a touch-enabled device (such as presses and releases a finger from a single point over a display object + on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a click event. +

Specifically, if a user taps a finger over an InteractiveObject, the InteractiveObject instance can dispatch a click + event or a touchTap event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the click event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchTap event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example displays a message when the + square drawn on mySprite is tapped on a touch-enabled screen: + +Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +var myTextField:TextField = new TextField(); + +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); + +function taphandler(e:TouchEvent): void { + myTextField.text = "I've been tapped"; + myTextField.y = 50; + addChild(myTextField); +} +
click eventflash.ui.Multitouch
touchRollOver + Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device + (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ROLL_OVERflash.events.TouchEvent + Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device + (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a rollOver event. +

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a rollOver + event or a touchRollOver event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the rollOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchRollOver event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
rollOver eventflash.ui.Multitouch
touchRollOut + Dispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device + (such as drags a finger from over a display object to a point outside the display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ROLL_OUTflash.events.TouchEvent + Dispatched when the user moves the point of contact away from an InteractiveObject instance on a touch-enabled device + (such as drags a finger from over a display object to a point outside the display object on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a rollOut event. +

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a rollOut + event or a touchRollOut event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the rollOut event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchRollOut event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
rollOut eventflash.ui.Multitouch
touchOver + Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device + (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_OVERflash.events.TouchEvent + Dispatched when the user moves the point of contact over an InteractiveObject instance on a touch-enabled device + (such as drags a finger from a point outside a display object to a point over a display object on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseOver event. +

Specifically, if a user moves a finger over an InteractiveObject, the InteractiveObject instance can dispatch a mouseOver + event or a touchOver event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOver event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchOver event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
mouseOver eventflash.ui.Multitouch
touchOut + Dispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device + (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_OUTflash.events.TouchEvent + Dispatched when the user moves the point of contact away from InteractiveObject instance on a touch-enabled device + (such as drags a finger from one display object to another on a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseOut event. +

Specifically, if a user moves a finger across a touch screen, the InteractiveObject instance can dispatch a mouseOut + event or a touchOut event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseOut event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchOut event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
mouseOut eventflash.ui.Multitouch
touchMove + Dispatched when the user moves the point of contact with a touch-enabled device (such as drags a finger across a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_MOVEflash.events.TouchEvent + Dispatched when the user moves the point of contact with a touch-enabled device (such as drags a finger across a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseMove event. +

Specifically, if a user moves a finger across a touch screen, the InteractiveObject instance can dispatch a mouseMove + event or a touchMove event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseMove event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchMove event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. + While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. + For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. + The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(eBegin:TouchEvent) { + eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } + +function onTouchMove(eMove:TouchEvent) { + trace(eMove.stageX); +} + +function onTouchEnd(eEnd:TouchEvent) { + eEnd.target.stopTouchDrag(eEnd.touchPointID); + trace("touch end"); +} +
mouseMove eventflash.ui.Multitouch
touchEnd + Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_ENDflash.events.TouchEvent + Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseUp event. +

Specifically, if a user lifts a finger from a touch screen, the InteractiveObject instance can dispatch a mouseUp + event or a touchEnd event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseUp event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchEnd event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. + While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. + For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. + The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(eBegin:TouchEvent) { + eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } + +function onTouchMove(eMove:TouchEvent) { + trace(eMove.stageX); +} + +function onTouchEnd(eEnd:TouchEvent) { + eEnd.target.stopTouchDrag(eEnd.touchPointID); + trace("touch end"); +} +
mouseUp eventflash.ui.Multitouch
touchBegin + Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen).flash.events.TouchEvent.TOUCH_BEGINflash.events.TouchEvent + Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen). + Some devices might also interpret this contact as a mouseDown event. +

Specifically, if a user touches a finger to a touch screen, the InteractiveObject instance can dispatch a mouseDown + event or a touchBegin event, or both if the current environment supports it. Choose how you want to handle the user interaction. + Use the flash.ui.Multitouch class to manage touch event handling (enable touch gesture event handling, + simple touch point event handling, or disable touch events so only mouse events are dispatched). + If you choose to handle the mouseDown event, then the same event handler will run on a touch-enabled device and + a mouse enabled device. However, if you choose to handle the touchBegin event, you can design your event handler + to respond to the specific needs of a touch-enabled environment and provide users with a richer touch-enabled + experience. You can also handle both events, separately, to provide a different response for a touch event than a mouse event.

+

Note: See the Multitouch class for environment compatibility information.

+
The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. + While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. + For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. + The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(eBegin:TouchEvent) { + eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } + +function onTouchMove(eMove:TouchEvent) { + trace(eMove.stageX); +} + +function onTouchEnd(eEnd:TouchEvent) { + eEnd.target.stopTouchDrag(eEnd.touchPointID); + trace("touch end"); +} +
mouseDown eventflash.ui.Multitouch
rollOver + Dispatched when the user moves a pointing device over an InteractiveObject instance.flash.events.MouseEvent.ROLL_OVERflash.events.MouseEvent + Dispatched when the user moves a pointing device over an InteractiveObject instance. + The event target is the object under the pointing device or a parent of that object. + The relatedObject is the object that was previously under the pointing + device. The rollOver events are dispatched consecutively down the parent + chain of the object, starting with the highest parent that is neither the root + nor an ancestor of the relatedObject and ending with the object. +

The purpose of the rollOver event is to simplify the coding of rollout behaviors for + display object containers with children. When the mouse enters the area of a display + object or the area of any of its children from an object that is not one of its + children, the display object dispatches the rollOver event. This is different behavior + than that of the mouseOver event, which is dispatched each time the mouse + enters the area of any child object of the display object container, even if the mouse + was already over another child object of the display object container.

+
rollOut + Dispatched when the user moves a pointing device away from an InteractiveObject + instance.flash.events.MouseEvent.ROLL_OUTflash.events.MouseEvent + Dispatched when the user moves a pointing device away from an InteractiveObject + instance. The event target is the object previously under the pointing device or a parent of + that object. The relatedObject is the object that the pointing device has moved to. + The rollOut events are dispatched consecutively up the parent chain of the object, + starting with the object and ending with the highest parent that is neither the root nor an + ancestor of the relatedObject. +

The purpose of the rollOut event is to simplify the + coding of rollover behaviors for display object containers with children. When the mouse leaves + the area of a display object or the area of any of its children to go to an object that is not + one of its children, the display object dispatches the rollOut event. This is different behavior + than that of the mouseOut event, which is dispatched each time the mouse leaves the + area of any child object of the display object container, even if the mouse remains over another + child object of the display object container.

+
mouseWheel + Dispatched when a mouse wheel is spun over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_WHEELflash.events.MouseEvent + Dispatched when a mouse wheel is spun over an InteractiveObject instance. + If the target is a text field, the text scrolls as the default behavior. + Only available on Microsoft Windows operating systems. + mouseUp + Dispatched when a user releases the pointing device button over an + InteractiveObject instance.flash.events.MouseEvent.MOUSE_UPflash.events.MouseEvent + Dispatched when a user releases the pointing device button over an + InteractiveObject instance. + If the target is a SimpleButton instance, the object displays the upState + display object. + If the target is a selectable text field, the text field ends selection as the default + behavior. + mouseOver + Dispatched when the user moves a pointing device over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_OVERflash.events.MouseEvent + Dispatched when the user moves a pointing device over an InteractiveObject instance. + The relatedObject is the object that was previously under + the pointing device. + If the target is a SimpleButton instance, the object displays the overState + or upState display object, depending on whether the mouse button is down, as the default behavior. +

The mouseOver event is dispatched each time the mouse enters the area of any child object of the display object container, + even if the mouse was already over another child object of the display object container. + This is different behavior than the purpose of the rollOver event, which is to simplify the coding of rollout behaviors for + display object containers with children. When the mouse enters the area of a display object or the area of any of its children from an object + that is not one of its children, the display object dispatches the rollOver event. + The rollOver events are dispatched consecutively down the parent chain of the object, + starting with the highest parent that is neither the root nor an ancestor of the relatedObject and ending with the object.

+
mouseOut + Dispatched when the user moves a pointing device away from an InteractiveObject instance.flash.events.MouseEvent.MOUSE_OUTflash.events.MouseEvent + Dispatched when the user moves a pointing device away from an InteractiveObject instance. + The event target is the object previously under the pointing device. The relatedObject + is the object the pointing device has moved to. + If the target is a SimpleButton instance, the button displays the upState + display object as the default behavior. +

The mouseOut event is dispatched each time the mouse leaves the + area of any child object of the display object container, even if the mouse remains over another + child object of the display object container. This is different behavior than the purpose of the rollOut event, which is to simplify the + coding of rollover behaviors for display object containers with children. When the mouse leaves + the area of a display object or the area of any of its children to go to an object that is not + one of its children, the display object dispatches the rollOut event.The rollOut events are dispatched consecutively + up the parent chain of the object, starting with the object and ending with the highest parent that is neither the root nor an + ancestor of the relatedObject.

+
mouseMove + Dispatched when a user moves the pointing device while it is over an InteractiveObject.flash.events.MouseEvent.MOUSE_MOVEflash.events.MouseEvent + Dispatched when a user moves the pointing device while it is over an InteractiveObject. + If the target is a text field that the user is selecting, the selection is updated as the default behavior. + mouseDown + Dispatched when a user presses the pointing device button over an InteractiveObject instance.flash.events.MouseEvent.MOUSE_DOWNflash.events.MouseEvent + Dispatched when a user presses the pointing device button over an InteractiveObject instance. + If the target is a SimpleButton instance, the SimpleButton instance displays the + downState display object as the default behavior. If the target is a + selectable text field, the text field begins selection as the default behavior. + doubleClick + Dispatched when a user presses and releases the main button of a pointing device twice in + rapid succession over the same InteractiveObject when that object's + doubleClickEnabled flag is set to true.flash.events.MouseEvent.DOUBLE_CLICKflash.events.MouseEvent + Dispatched when a user presses and releases the main button of a pointing device twice in + rapid succession over the same InteractiveObject when that object's + doubleClickEnabled flag is set to true. + For a doubleClick event to occur, it must immediately follow the following + series of events: mouseDown, mouseUp, click, + mouseDown, mouseUp. All of these events must share the same + target as the doubleClick event. The second click, represented by + the second mouseDown and mouseUp events, must occur within + a specific period of time after the click event. The allowable length of + this period varies by operating system and can often be configured by the user. + If the target is a selectable text field, the word under the pointer is selected as the + default behavior. If the target InteractiveObject does not have its + doubleClickEnabled flag set to true it receives two + click events. + +

The doubleClickEnabled property defaults + to false.

+ +

The double-click text selection behavior of a TextField object + is not related to the doubleClick event. Use + TextField.doubleClickEnabled to control TextField selections.

+
doubleClickEnabled
click + Dispatched when a user presses and releases the main button of the user's + pointing device over the same InteractiveObject.flash.events.MouseEvent.CLICKflash.events.MouseEvent + Dispatched when a user presses and releases the main button of the user's + pointing device over the same InteractiveObject. For a click event to occur, it must always follow this series of + events in the order of occurrence: mouseDown event, then mouseUp. The target object + must be identical for both of these events; otherwise the click event does not + occur. Any number of other mouse events can occur at any time between the + mouseDown or mouseUp events; the click event + still occurs. + mouseFocusChange + Dispatched when the user attempts to change focus by using a pointer device.flash.events.FocusEvent.MOUSE_FOCUS_CHANGEflash.events.FocusEvent + Dispatched when the user attempts to change focus by using a pointer device. + The default behavior of this event is to change the focus and dispatch the corresponding + focusIn and focusOut events. + +

This event is dispatched to the object that currently has focus. The related object for this event is the + InteractiveObject instance that receives focus if you do not prevent the default behavior. You can prevent the change in + focus by calling preventDefault() in an event listener that is properly registered with the target object. + The shiftKey property is not used. Focus changes and + focusIn and focusOut events are dispatched by default.

+
keyFocusChange + Dispatched when the user attempts to change focus by using keyboard navigation.flash.events.FocusEvent.KEY_FOCUS_CHANGEflash.events.FocusEvent + Dispatched when the user attempts to change focus by using keyboard navigation. + The default behavior of this event is to change the focus and dispatch the + corresponding focusIn and focusOut events. + +

This event is dispatched to the object that currently has focus. + The related object for this event is the InteractiveObject instance that receives focus + if you do not prevent the default behavior. + You can prevent the change in focus by calling the preventDefault() method + in an event listener that is properly registered with the target object. + Focus changes and focusIn and focusOut + events are dispatched by default.

+
focusOut + Dispatched after a display object loses focus.flash.events.FocusEvent.FOCUS_OUTflash.events.FocusEvent + Dispatched after a display object loses focus. + This happens when a user highlights a different object with a pointing device or keyboard navigation. + The object that loses focus is called the target object of this event, while the corresponding InteractiveObject + instance that receives focus is called the related object. A reference to the related object is stored in the target object's + relatedObject property. The shiftKey property is not used. This event precedes the dispatch + of the focusIn event by the related object. + focusIn + Dispatched after a display object gains focus.flash.events.FocusEvent.FOCUS_INflash.events.FocusEvent + Dispatched after a display object gains focus. + This situation happens when a user highlights the object with a pointing device or keyboard navigation. + The recipient of such focus is called the target object of this event, + while the corresponding InteractiveObject instance that lost focus because of this change is called the related object. + A reference to the related object is stored in the receiving object's relatedObject property. + The shiftKey property is not used. + This event follows the dispatch of the previous object's focusOut event. + selectAll + Dispatched when the user activates the platform-specific accelerator key combination for a select all operation + or selects 'Select All' from the text context menu.flash.events.Event.SELECT_ALLflash.events.Event + Dispatched when the user activates the platform-specific accelerator key combination for a select all operation + or selects 'Select All' from the text context menu. + This event is dispatched to the object that currently has focus. + If the object that currently has focus is a TextField, the default behavior of this event is to cause + all the contents of the text field to be selected. + paste + Dispatched when the user activates the platform-specific accelerator key combination for a paste operation + or selects 'Paste' from the text context menu.flash.events.Event.PASTEflash.events.Event + Dispatched when the user activates the platform-specific accelerator key combination for a paste operation + or selects 'Paste' from the text context menu. + This event is dispatched to the object that currently has focus. + If the object that currently has focus is a TextField, the default behavior of this event is to cause + the contents of the clipboard to be pasted into the text field at the current insertion point + replacing any currently selected text in the text field. + cut + Dispatched when the user activates the platform-specific accelerator key combination for a cut operation + or selects 'Cut' from the text context menu.flash.events.Event.CUTflash.events.Event + Dispatched when the user activates the platform-specific accelerator key combination for a cut operation + or selects 'Cut' from the text context menu. + This event is dispatched to the object that currently has focus. + If the object that currently has focus is a TextField, the default behavior of this event is to cause + any currently selected text in the text field to be cut to the clipboard. + copy + Dispatched when the user activates the platform-specific accelerator key combination for a copy operation + or selects 'Copy' from the text context menu.flash.events.Event.COPYflash.events.Event + Dispatched when the user activates the platform-specific accelerator key combination for a copy operation + or selects 'Copy' from the text context menu. + This event is dispatched to the object that currently has focus. + If the object that currently has focus is a TextField, the default behavior of this event is to cause + any currently selected text in the text field to be copied to the clipboard. + clear + Dispatched when the user selects 'Clear' (or 'Delete') from the text context menu.flash.events.Event.CLEARflash.events.Event + Dispatched when the user selects 'Clear' (or 'Delete') from the text context menu. + This event is dispatched to the object that currently has focus. + If the object that currently has focus is a TextField, the default behavior of this event is to cause + any currently selected text in the text field to be deleted. + InteractiveObject + Calling the new InteractiveObject() constructor + throws an ArgumentError exception. + Calling the new InteractiveObject() constructor + throws an ArgumentError exception. + You can, however, call constructors for the following subclasses of InteractiveObject: + +
  • new SimpleButton()
  • new TextField()
  • new Loader()
  • new Sprite()
  • new MovieClip()
+ + +
requestSoftKeyboard + Raises a virtual keyboard.A value of true means that the soft keyboard request was granted; false means that the soft keyboard was not raised. + BooleanIf the current context supports it, show the keyboard. + + Raises a virtual keyboard. + +

Calling this method focuses the InteractiveObject instance and raises the soft keyboard, if necessary. + The needsSoftKeyboard must also be true. A keyboard is not raised + if a hardware keyboard is available, or if the client system does not support virtual keyboards.

+ +

Note: This method is not supported in AIR applications on iOS.

+ +
needsSoftKeyboard
accessibilityImplementation + The current accessibility implementation (AccessibilityImplementation) + for this InteractiveObject instance.flash.accessibility:AccessibilityImplementation + The current accessibility implementation (AccessibilityImplementation) + for this InteractiveObject instance. + flash.accessibility.AccessibilityImplementationcontextMenu + Specifies the context menu associated with this object.flash.display:NativeMenuThe context menu associated with this object + + Specifies the context menu associated with this object. + +

For content running in Flash Player, this property is a ContextMenu object. In the AIR runtime, + the ContextMenu class extends the NativeMenu class, however Flash Player only supports the + ContextMenu class, not the NativeMenu class. +

+ +

Note: TextField objects always include a clipboard menu in the context menu. The clipboard menu contains + Cut, Copy, Paste, Clear, and Select All commands. You cannot remove these commands from the context menu for TextField objects. + For TextField objects, selecting these commands (or their keyboard equivalents) does not generate clear, + copy, cut, paste, or selectAll events.

+ +
The following example shows how you can add a custom context menu item to a Sprite object by setting the Sprite's contextMenu property to a ContextMenu object. + Example provided by + ActionScriptExamples.com. + +var red_cmi:ContextMenuItem = new ContextMenuItem("red"); +red_cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmi_menuItemSelect); + +var cm:ContextMenu = new ContextMenu(); +cm.customItems.push(red_cmi); +cm.hideBuiltInItems(); + +var spr:Sprite = new Sprite(); +spr.contextMenu = cm; +spr.graphics.beginFill(0x000000); +spr.graphics.drawRect(0, 0, 120, 90); +spr.graphics.endFill(); +spr.x = 10; +spr.y = 10; +addChild(spr); + +function cmi_menuItemSelect(evt:ContextMenuEvent):void { + spr.graphics.clear(); + spr.graphics.beginFill(0xFF0000); + spr.graphics.drawRect(0, 0, 120, 90); + spr.graphics.endFill(); +} +
doubleClickEnabled + Specifies whether the object receives doubleClick events.BooleanWhether this object receives double click messages. + + + + Specifies whether the object receives doubleClick events. The default value + is false, which means that by default an InteractiveObject instance does not receive + doubleClick events. If the doubleClickEnabled property is set to + true, the instance receives doubleClick events within its bounds. + The mouseEnabled property of the InteractiveObject instance must also be + set to true for the object to receive doubleClick events. + +

No event is dispatched by setting this property. You must use the + addEventListener() method to add an event listener + for the doubleClick event.

+ +
doubleClickmouseEnabledflash.display.DisplayObjectContainer.mouseChildren
focusRect + Specifies whether this object displays a focus rectangle.Object + Specifies whether this object displays a focus rectangle. It can take one of three + values: true, false, or null. Values of true + and false work as expected, specifying whether or not the focus rectangle + appears. A value of null indicates that this object obeys the + stageFocusRect property of the Stage. + + mouseEnabled + Specifies whether this object receives mouse, or other user input, messages.Boolean + Specifies whether this object receives mouse, or other user input, messages. The default value is true, + which means that by default any InteractiveObject instance that is on the display list + receives mouse events or other user input events. + If mouseEnabled is set to false, the instance does not receive any + mouse events (or other user input events like keyboard events). Any children of this instance on the display list are not affected. To change + the mouseEnabled behavior for all children of an object on the display list, use + flash.display.DisplayObjectContainer.mouseChildren. +

No event is dispatched by setting this property. You must use the + addEventListener() method to create interactive functionality.

+ +
flash.display.DisplayObjectContainer.mouseChildren
needsSoftKeyboard + Specifies whether a virtual keyboard (an on-screen, software keyboard) should display + when this InteractiveObject instance receives focus.Boolean + Specifies whether a virtual keyboard (an on-screen, software keyboard) should display + when this InteractiveObject instance receives focus. + +

By default, the value is false and focusing an InteractiveObject instance does + not raise a soft keyboard. If the needsSoftKeyboard property is set to true, + the runtime raises a soft keyboard when the InteractiveObject instance is ready to accept user input. + An InteractiveObject instance is ready to accept user input after a programmatic call to set the Stage + focus property or a user interaction, such as a "tap." If the client system has a + hardware keyboard available or does not support virtual keyboards, then the soft keyboard is not raised.

+ +

The InteractiveObject instance dispatches softKeyboardActivating, + softKeyboardActivate, and softKeyboardDeactivate events + when the soft keyboard raises and lowers.

+ +

Note: This property is not supported in AIR applications on iOS.

+ +
softKeyboardActivatingsoftKeyboardActivatesoftKeyboardDeactivate
softKeyboardInputAreaOfInterest + Defines the area that should remain on-screen when a soft keyboard is displayed.flash.geom:RectangleSets the area to be displayed on-screen when the soft keyboard opens. + + Defines the area that should remain on-screen when a soft keyboard is displayed. + +

If the needsSoftKeyboard property of this InteractiveObject is + true, then the runtime adjusts the display as needed to keep the + object in view while the user types. Ordinarily, the runtime uses the object + bounds obtained from the DisplayObject.getBounds() method. You can + specify a different area using this softKeyboardInputAreaOfInterest + property.

+ +

Specify the softKeyboardInputAreaOfInterest in stage coordinates.

+ +

Note: On Android, the softKeyboardInputAreaOfInterest is not + respected in landscape orientations.

+ +
flash.display.DisplayObject.getBounds()
tabEnabled + Specifies whether this object is in the tab order.BooleanWhether this object is in the tab order. + + + Specifies whether this object is in the tab order. If this object is in the tab order, + the value is true; otherwise, the value is false. By default, + the value is false, except for the following: +
  • For a SimpleButton object, the value is true.
  • For a TextField object with type = "input", the value is true.
  • For a Sprite object or MovieClip object with buttonMode = true, the value is true.
+ +
tabIndex + Specifies the tab ordering of objects in a SWF file.intThe tab index for this object. + + + + Specifies the tab ordering of objects in a SWF file. The tabIndex + property is -1 by default, meaning no tab index is set for the object. + +

If any currently displayed object in the SWF file contains a tabIndex property, automatic + tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of + objects in the SWF file. The custom tab ordering includes only objects that have tabIndex + properties.

+ +

The tabIndex property can be a non-negative integer. The objects are ordered according to + their tabIndex properties, in ascending order. An object with a tabIndex + value of 1 precedes an object with a tabIndex value of 2. Do not use the same tabIndex + + value for multiple objects.

+ +

The custom tab ordering that the tabIndex property defines is flat. + This means that no attention is paid to the hierarchical relationships of objects in the SWF file. + All objects in the SWF file with tabIndex properties are placed in the tab order, and the + tab order is determined by the order of the tabIndex values.

+

Note: To set the tab order for TLFTextField instances, cast the display object child + of the TLFTextField as an InteractiveObject, then set the tabIndex property. For example: +

+	 InteractiveObject(tlfInstance.getChildAt(1)).tabIndex = 3;
+	 
+ To reverse the tab order from the default setting for three instances of a TLFTextField object + (tlfInstance1, tlfInstance2 and tlfInstance3), use: +
+	 InteractiveObject(tlfInstance1.getChildAt(1)).tabIndex = 3;
+	 InteractiveObject(tlfInstance2.getChildAt(1)).tabIndex = 2;
+	 InteractiveObject(tlfInstance3.getChildAt(1)).tabIndex = 1;
+	 
+

+ +
GraphicsTrianglePath + Defines an ordered set of triangles that can be rendered using + either (u,v) fill coordinates or a normal fill.flash.display:IGraphicsPathflash.display:IGraphicsDataObject + Defines an ordered set of triangles that can be rendered using + either (u,v) fill coordinates or a normal fill. + + Each triangle in the path is represented by three sets of (x, y) + coordinates, each of which is one point of the triangle. + +

+ The triangle vertices do not contain z coordinates and do not necessarily + represent 3D faces. However a triangle path can be used to support the rendering + of 3D geometry in a 2D space. +

+ +
flash.display.Graphics.drawTriangles()GraphicsTrianglePath + Creates a new GraphicsTrianglePath object.verticesnullA Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). Required. + + indicesnullA Vector of integers or indexes, where every three indexes define a triangle. + + uvtDatanullA Vector of normalized coordinates used to apply texture mapping. + + cullingStringnoneSpecifies whether to render triangles that face in a given direction. Used to + prevent the rendering of triangles that cannot be seen in the current view. + Can be set to any value defined by the TriangleCulling class. + + + Creates a new GraphicsTrianglePath object. + + cullingflash.display.TriangleCullingindices + A Vector of integers or indexes, where every three indexes define a triangle. + A Vector of integers or indexes, where every three indexes define a triangle. If the indexes parameter + is null then every three vertices (six x,y pairs in the vertices Vector) defines a triangle. + Otherwise each index refers to a vertex, which is a pair of numbers in the vertices Vector. + For example indexes[1] refers to (vertices[2], vertices[3]). + uvtData + A Vector of normalized coordinates used to apply texture mapping. + A Vector of normalized coordinates used to apply texture mapping. + Each coordinate refers to a point on the bitmap used for the fill. + There must be one UV or one UVT coordinate per vertex. + +

+ In UV coordinates, (0,0) is the upper left of the bitmap, and (1,1) is the lower right of the bitmap. +

+ +

+ If the length of this vector is twice the length of the vertices vector then normalized + coordinates are used without perspective correction. +

+ +

+ If the length of this vector is three times the length of the vertices vector then the + third coordinate is interpreted as 't', the distance from the eye to the texture in eye space. + This helps the rendering engine correctly apply perspective when mapping textures in 3D. +

+
vertices + A Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). + A Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). + culling + Specifies whether to render triangles that face in a given direction.String + Specifies whether to render triangles that face in a given direction. Used to + prevent the rendering of triangles that cannot be seen in the current view. +

+ Can be set to any value defined by the TriangleCulling class. +

+ +
flash.display.TriangleCulling
DisplayObject + The DisplayObject class is the base class for all objects that can be placed on + the display list.flash.display:IBitmapDrawableflash.events:EventDispatcher + The DisplayObject class is the base class for all objects that can be placed on + the display list. The display list manages all objects displayed in the Flash runtimes. + Use the DisplayObjectContainer class to arrange the display objects in the display list. + DisplayObjectContainer objects can have child display objects, while other display objects, such as + Shape and TextField objects, are "leaf" nodes that have only parents and siblings, no children. + +

The DisplayObject class supports basic functionality like the x and y position of + an object, as well as more advanced properties of the object such as its transformation matrix. +

+ +

DisplayObject is an abstract base class; therefore, you cannot call DisplayObject directly. Invoking + new DisplayObject() throws an ArgumentError exception.

+ +

All display objects inherit from the DisplayObject class.

+ +

The DisplayObject class itself does not include any APIs for rendering content onscreen. + For that reason, if you want create a custom subclass of the DisplayObject class, you will want + to extend one of its subclasses that do have APIs for rendering content onscreen, + such as the Shape, Sprite, Bitmap, SimpleButton, TextField, or MovieClip class.

+ +

The DisplayObject class contains several broadcast events. Normally, the target + of any particular event is a specific DisplayObject instance. For example, + the target of an added event is the specific DisplayObject instance + that was added to the display list. Having a single target restricts the placement of + event listeners to that target and in some cases the target's ancestors on the display list. + With broadcast events, however, the target is not a specific DisplayObject instance, + but rather all DisplayObject instances, including those that are not on the display list. + This means that you can add a listener to any DisplayObject instance to listen for broadcast events. + In addition to the broadcast events listed in the DisplayObject class's Events table, + the DisplayObject class also inherits two broadcast events from the EventDispatcher + class: activate and deactivate.

+ +

Some properties previously used in the ActionScript 1.0 and 2.0 MovieClip, TextField, and Button + classes (such as _alpha, _height, _name, _width, + _x, _y, and others) have equivalents in the ActionScript 3.0 + DisplayObject class that are renamed so that they no longer begin with the underscore (_) character.

+ +

For more information, see the "Display Programming" chapter of the ActionScript 3.0 Developer's Guide.

+ +
The following example uses the DisplayObjectExample class to + draw an orange square in the corner of the Stage and then respond to events by displaying text + information for each event. This task is accomplished by performing the following steps: +
  1. Class properties are declared for the color and size of the square.
  2. The constructor calls the draw() method, which draws an orange square on + the Stage at the default coordinates of x = 0, y = 0.
  3. The following event listener methods are attached to the square: +
    • addedHandler() listens for added events, dispatched when the + square is added to the display list.
    • enterFrameHandler() listens for enterFrame events, which have no + real meaning in this example.
    • removedHandler() listens for removed events, dispatched when + the square is removed from the display list, which happens when the square is clicked.
    • clickHandler() listens for click events, dispatched when the + orange square is clicked.
    • renderHandler() listens for render events after the display + list is updated.
+ + +package { + import flash.display.Sprite; + + public class DisplayObjectExample extends Sprite { + public function DisplayObjectExample() { + var child:CustomDisplayObject = new CustomDisplayObject(); + addChild(child); + } + } +} + +import flash.display.DisplayObject; +import flash.display.Sprite; +import flash.display.Stage; +import flash.display.StageAlign; +import flash.display.StageScaleMode; +import flash.events.*; + +class CustomDisplayObject extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + + public function CustomDisplayObject() { + draw(); + addEventListener(Event.ADDED, addedHandler); + addEventListener(Event.ENTER_FRAME, enterFrameHandler); + addEventListener(Event.REMOVED, removedHandler); + addEventListener(MouseEvent.CLICK, clickHandler); + addEventListener(Event.RENDER, renderHandler); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, size, size); + graphics.endFill(); + } + + private function clickHandler(event:MouseEvent):void { + trace("clickHandler: " + event); + parent.removeChild(this); + } + + private function addedHandler(event:Event):void { + trace("addedHandler: " + event); + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + stage.addEventListener("resize", resizeHandler); + } + + private function enterFrameHandler(event:Event):void { + trace("enterFrameHandler: " + event); + removeEventListener("enterFrame", enterFrameHandler); + } + + private function removedHandler(event:Event):void { + trace("removedHandler: " + event); + stage.removeEventListener("resize", resizeHandler); + } + + private function renderHandler(event:Event):void { + trace("renderHandler: " + event); + } + + private function resizeHandler(event:Event):void { + trace("resizeHandler: " + event); + } +} +
flash.display.DisplayObjectContainerrender + [broadcast event] Dispatched when the display list is about to be updated and rendered.flash.events.Event.RENDERflash.events.Event + [broadcast event] Dispatched when the display list is about to be updated and rendered. This event provides the last opportunity + for objects listening for this event to make changes before the display list is rendered. + You must call the invalidate() method + of the Stage object + each time you want a render event to be dispatched. Render events + are dispatched to an object only if there is mutual trust between it and the object that called + Stage.invalidate(). + This event is a broadcast event, which means that it is dispatched + by all display objects with a listener registered for this event. + +

Note: This event is not dispatched if the display is + not rendering. This is the case when the content is either minimized or obscured.

+
removedFromStage + Dispatched when a display object is about to be removed from the display list, + either directly or through the removal of a sub tree in which the display object is contained.flash.events.Event.REMOVED_FROM_STAGEflash.events.Event + Dispatched when a display object is about to be removed from the display list, + either directly or through the removal of a sub tree in which the display object is contained. + Two methods of the DisplayObjectContainer class generate this event: + removeChild() and removeChildAt(). + +

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed + to make room for the new object: addChild(), addChildAt(), and + setChildIndex().

+
removed + Dispatched when a display object is about to be removed from the display list.flash.events.Event.REMOVEDflash.events.Event + Dispatched when a display object is about to be removed from the display list. + Two methods of the DisplayObjectContainer class generate this event: + removeChild() and removeChildAt(). + +

The following methods of a DisplayObjectContainer object also generate this event if an object must be removed + to make room for the new object: addChild(), addChildAt(), and + setChildIndex().

+
exitFrame + [broadcast event] Dispatched when the playhead is exiting the current frame.flash.events.Event.EXIT_FRAMEflash.events.Event + [broadcast event] Dispatched when the playhead is exiting the current frame. + All frame scripts have been run. If the playhead is not moving, or if there is only one frame, this event + is dispatched continuously in conjunction with the frame rate. + This event is a broadcast event, which means that it is dispatched + by all display objects with a listener registered for this event. + frameConstructed + [broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run.flash.events.Event.FRAME_CONSTRUCTEDflash.events.Event + [broadcast event] Dispatched after the constructors of frame display objects have run but before frame scripts have run. + If the playhead is not moving, or if there is only one frame, this event + is dispatched continuously in conjunction with the frame rate. + This event is a broadcast event, which means that it is dispatched + by all display objects with a listener registered for this event. + enterFrame + [broadcast event] Dispatched when the playhead is entering a new + frame.flash.events.Event.ENTER_FRAMEflash.events.Event + [broadcast event] Dispatched when the playhead is entering a new + frame. If the playhead is not moving, or if there is only one frame, this event + is dispatched continuously in conjunction with the frame rate. + This event is a broadcast event, which means that it is dispatched + by all display objects with a listener registered for this event. + addedToStage + Dispatched when a display object is added to the on stage display list, + either directly or through the addition of a sub tree in which the display object is contained.flash.events.Event.ADDED_TO_STAGEflash.events.Event + Dispatched when a display object is added to the on stage display list, + either directly or through the addition of a sub tree in which the display object is contained. The + following methods trigger this event: DisplayObjectContainer.addChild(), + DisplayObjectContainer.addChildAt(). + flash.display.DisplayObjectContainer.addChild()flash.display.DisplayObjectContainer.addChildAt()added + Dispatched when a display object is added to the display list.flash.events.Event.ADDEDflash.events.Event + Dispatched when a display object is added to the display list. The + following methods trigger this event: DisplayObjectContainer.addChild(), + DisplayObjectContainer.addChildAt(). + flash.display.DisplayObjectContainer.addChild()flash.display.DisplayObjectContainer.addChildAt()getBounds + Returns a rectangle that defines the area of the display object relative to the coordinate system + of the targetCoordinateSpace object.The rectangle that defines the area of the display object relative to + the targetCoordinateSpace object's coordinate system. + + flash.geom:RectangletargetCoordinateSpaceflash.display:DisplayObjectThe display object that defines the coordinate system to use. + + + Returns a rectangle that defines the area of the display object relative to the coordinate system + of the targetCoordinateSpace object. + Consider the following code, which shows how the rectangle returned can vary depending on the + targetCoordinateSpace parameter that you pass to the method: + + + var container:Sprite = new Sprite(); + container.x = 100; + container.y = 100; + this.addChild(container); + var contents:Shape = new Shape(); + contents.graphics.drawCircle(0,0,100); + container.addChild(contents); + trace(contents.getBounds(container)); + // (x=-100, y=-100, w=200, h=200) + trace(contents.getBounds(this)); + // (x=0, y=0, w=200, h=200) + + + +

Note: Use the localToGlobal() and + globalToLocal() methods to convert the display object's local coordinates + to display coordinates, or display coordinates to local coordinates, respectively.

+ +

The getBounds() method is similar to the getRect() method; + however, the Rectangle returned by the getBounds() method includes any strokes + on shapes, whereas the Rectangle returned by the getRect() method does not. + For an example, see the description of the getRect() method.

+ +
getRect()globalToLocal()localToGlobal()
getRect + Returns a rectangle that defines the boundary of the display object, + based on the coordinate system defined by the targetCoordinateSpace + parameter, excluding any strokes on shapes.The rectangle that defines the area of the display object relative to + the targetCoordinateSpace object's coordinate system. + + flash.geom:RectangletargetCoordinateSpaceflash.display:DisplayObjectThe display object that defines the coordinate system to use. + + + Returns a rectangle that defines the boundary of the display object, + based on the coordinate system defined by the targetCoordinateSpace + parameter, excluding any strokes on shapes. The values that the getRect() method + returns are the same or smaller than those returned by the getBounds() method. + +

Note: Use localToGlobal() and globalToLocal() methods + to convert the display object's local coordinates to Stage coordinates, or Stage coordinates to + local coordinates, respectively.

+ +
The following example shows how the getBounds() method can return a larger + rectangle than the getRect() method does, because of the additional area taken up by + strokes. In this case, the triangle sprite includes extra strokes because of the + width and jointStyle parameters of the lineStyle() + method. The trace() output (in the last two lines) shows the differences between + the getRect() and getBounds() rectangles: + + +import flash.display.CapsStyle; +import flash.display.JointStyle; +import flash.display.LineScaleMode; +import flash.display.Sprite; +import flash.geom.Rectangle; + +var triangle:Sprite = new Sprite(); +var color:uint = 0xFF0044; +var width:Number = 20; +var alpha:Number = 1.0; +var pixelHinting:Boolean = true; +var scaleMode:String = LineScaleMode.NORMAL; +var caps:String = CapsStyle.SQUARE; +var joints:String = JointStyle.MITER; +triangle.graphics.lineStyle(width, color, alpha, pixelHinting, scaleMode, caps, joints); + +var triangleSide:Number = 100; +triangle.graphics.moveTo(0, 0); +triangle.graphics.lineTo(0, triangleSide); +triangle.graphics.lineTo(triangleSide, triangleSide); +triangle.graphics.lineTo(0, 0); + +addChild(triangle); + +trace(triangle.getBounds(this)); // (x=-10, y=-24.1, w=134.10000000000002, h=134.1) +trace(triangle.getRect(this)); // (x=0, y=0, w=100, h=100) +
getBounds()
globalToLocal3D + Converts a two-dimensional point from the Stage (global) coordinates to a + three-dimensional display object's (local) coordinates.A Vector3D object with coordinates relative to the three-dimensional + display object. + + flash.geom:Vector3Dpointflash.geom:PointA two dimensional Point object representing global x and y coordinates. + + + Converts a two-dimensional point from the Stage (global) coordinates to a + three-dimensional display object's (local) coordinates. + +

To use this method, first create an instance of the Point class. + The x and y values that you assign to the Point object represent global + coordinates because they are relative to the origin (0,0) of the main display area. + Then pass the Point object to the globalToLocal3D() + method as the point parameter. The method returns three-dimensional + coordinates as a Vector3D object containing x, y, and + z values that are relative to the origin + of the three-dimensional display object.

+ +
globalToLocal + Converts the point object from the Stage (global) coordinates + to the display object's (local) coordinates.A Point object with coordinates relative to the display object. + + flash.geom:Pointpointflash.geom:PointAn object created with the Point class. The Point object + specifies the x and y coordinates as properties. + + Converts the point object from Stage (global) coordinates to the display + object's (local) coordinates. + + + Converts the point object from the Stage (global) coordinates + to the display object's (local) coordinates. + +

To use this method, first create an instance of the Point class. The + x and y values that you assign represent global coordinates because they + relate to the origin (0,0) of the main display area. Then pass the Point instance + as the parameter to the globalToLocal() method. The method returns a new Point object with + x and y values that relate to the origin of the display object + instead of the origin of the Stage.

+ +
The following code creates a Shape object and shows the + result of calling the hitTestPoint() method, using different + points as parameters. The globalToLocal() method converts the + point from Stage coordinates to the coordinate space of the shape: + + +import flash.display.Shape; +import flash.geom.Point; + +var circle:Shape = new Shape(); +circle.graphics.beginFill(0x0000FF); +circle.graphics.drawCircle(40, 40, 40); +circle.x = 10; +addChild(circle); + +var point1:Point = new Point(0, 0); +trace(circle.hitTestPoint(point1.x, point1.y, true)); // false +trace(circle.hitTestPoint(point1.x, point1.y, false)); // false +trace(circle.globalToLocal(point1)); // [x=-10, y=0] + +var point2:Point = new Point(10, 1); +trace(circle.hitTestPoint(point2.x, point2.y, true)); // false +trace(circle.hitTestPoint(point2.x, point2.y, false)); // true +trace(circle.globalToLocal(point2)); // [x=0, y=1] + +var point3:Point = new Point(30, 20); +trace(circle.hitTestPoint(point3.x, point3.y, true)); // true +trace(circle.hitTestPoint(point3.x, point3.y, false)); // true +trace(circle.globalToLocal(point3)); // [x=20, y=20] +
localToGlobal()flash.geom.Point class
hitTestObject + Evaluates the bounding box of the display object to see if it overlaps or intersects with the + bounding box of the obj display object.true if the bounding boxes of the display objects intersect; false if not. + + + Booleanobjflash.display:DisplayObjectThe display object to test against. + + Evaluates the bounding box of the display object to see if it overlaps or intersects with the + bounding box of the display object passed as a parameter. + + + Evaluates the bounding box of the display object to see if it overlaps or intersects with the + bounding box of the obj display object. + + The following code creates three Shape objects and shows the + result of calling the hitTestObject() method. Note that although + circle2 and circle3 do not overlap, their bounding boxes do. Thus, the hit test + of circle2 and circle3 returns true. + + +import flash.display.Shape; + +var circle1:Shape = new Shape(); +circle1.graphics.beginFill(0x0000FF); +circle1.graphics.drawCircle(40, 40, 40); +addChild(circle1); + +var circle2:Shape = new Shape(); +circle2.graphics.beginFill(0x00FF00); +circle2.graphics.drawCircle(40, 40, 40); +circle2.x = 50; +addChild(circle2); + +var circle3:Shape = new Shape(); +circle3.graphics.beginFill(0xFF0000); +circle3.graphics.drawCircle(40, 40, 40); +circle3.x = 100; +circle3.y = 67; +addChild(circle3); + +trace(circle1.hitTestObject(circle2)); // true +trace(circle1.hitTestObject(circle3)); // false +trace(circle2.hitTestObject(circle3)); // true +hitTestPoint + Evaluates the display object to see if it overlaps or intersects with the + point specified by the x and y parameters.true if the display object overlaps or intersects with the specified point; + false otherwise. + + BooleanxNumberThe x coordinate to test against this object. + + yNumberThe y coordinate to test against this object. + + shapeFlagBooleanfalseWhether to check against the actual pixels of the object (true) + or the bounding box (false). + + Evaluates the display object to see if it overlaps or intersects with a point specified + by x and y. + + + Evaluates the display object to see if it overlaps or intersects with the + point specified by the x and y parameters. + The x and y parameters specify a point in the + coordinate space of the Stage, not the display object container that contains the + display object (unless that display object container is the Stage). + + The following code creates a Shape object and shows the + result of calling the hitTestPoint() method, using different + points as parameters. The globalToLocal() method converts the + point from Stage coordinates to the coordinate space of the shape: + + +import flash.display.Shape; +import flash.geom.Point; + +var circle:Shape = new Shape(); +circle.graphics.beginFill(0x0000FF); +circle.graphics.drawCircle(40, 40, 40); +circle.x = 10; +addChild(circle); + +var point1:Point = new Point(0, 0); +trace(circle.hitTestPoint(point1.x, point1.y, true)); // false +trace(circle.hitTestPoint(point1.x, point1.y, false)); // false +trace(circle.globalToLocal(point1)); // [x=-10, y=0] + +var point2:Point = new Point(10, 1); +trace(circle.hitTestPoint(point2.x, point2.y, true)); // false +trace(circle.hitTestPoint(point2.x, point2.y, false)); // true +trace(circle.globalToLocal(point2)); // [x=0, y=1] + +var point3:Point = new Point(30, 20); +trace(circle.hitTestPoint(point3.x, point3.y, true)); // true +trace(circle.hitTestPoint(point3.x, point3.y, false)); // true +trace(circle.globalToLocal(point3)); // [x=20, y=20] +opaqueBackgroundlocal3DToGlobal + Converts a three-dimensional point of the three-dimensional display + object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates.A two-dimensional point representing a three-dimensional point + in two-dimensional space. + + flash.geom:Pointpoint3dflash.geom:Vector3DA Vector3D object containing either a three-dimensional point or + the coordinates of the three-dimensional display object. + + + Converts a three-dimensional point of the three-dimensional display + object's (local) coordinates to a two-dimensional point in the Stage (global) coordinates. + +

For example, you can only use two-dimensional coordinates (x,y) to + draw with the display.Graphics methods. To draw a three-dimensional + object, you need to map the three-dimensional coordinates of a + display object to two-dimensional coordinates. First, create an instance of + the Vector3D class that holds the x-, y-, and z- coordinates of the three-dimensional + display object. Then pass the Vector3D object to the local3DToGlobal() + method as the point3d parameter. The method returns a two-dimensional Point + object that can be used + with the Graphics API to draw the three-dimensional object.

+ + +
This example draws a simple three-dimensional cube in a two dimensional space + using display.Graphics methods. The location of this display + object is offset, so the cube's registration point is in its center. A vector + of Vector3D objects holds the cube's three dimensional coordinates. The top + of the cube is draw first, the bottom is drawn second, and then the top and bottom + four corners are connected. You need to add the cube to the display object + container before drawing the cube in order to use the local3DToGlobal() method. + +package { + import flash.display.MovieClip; + import flash.display.Sprite; + import flash.display.Graphics; + import flash.geom.*; + + public class Local3DToGlobalExample extends MovieClip { + private var myCube:Sprite = new Sprite(); + private var v8:Vector.<Vector3D> = new Vector.<Vector3D>(8); + + public function Local3DToGlobalExample():void { + this.x = -(this.stage.stageWidth / 2); + this.y = -(this.stage.stageWidth / 2); + + v8[0] = new Vector3D(-40,-40,-40); + v8[1] = new Vector3D(40,-40,-40); + v8[2] = new Vector3D(40,-40,40); + v8[3] = new Vector3D(-40,-40,40); + v8[4] = new Vector3D(-40,100,-40); + v8[5] = new Vector3D(40,100,-40); + v8[6] = new Vector3D(40,100,40); + v8[7] = new Vector3D(-40,100,40); + + myCube.x = (this.stage.stageWidth / 2); + myCube.y = (this.stage.stageWidth / 2); + myCube.z = 1; + addChild(myCube); + + Cube(); + } + + private function Cube():void { + var ps:Point = new Point(0,0); + + myCube.graphics.lineStyle(2,0xFF0000); + + ps = myCube.local3DToGlobal(v8[0]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[1]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[2]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[3]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[0]); + myCube.graphics.lineTo(ps.x, ps.y); + + ps = myCube.local3DToGlobal(v8[4]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[5]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[6]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[7]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[4]); + myCube.graphics.lineTo(ps.x, ps.y); + + ps = myCube.local3DToGlobal(v8[0]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[4]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[1]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[5]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[2]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[6]); + myCube.graphics.lineTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[3]); + myCube.graphics.moveTo(ps.x, ps.y); + ps = myCube.local3DToGlobal(v8[7]); + myCube.graphics.lineTo(ps.x, ps.y); + } + } +} +
localToGlobal + Converts the point object from the display object's (local) coordinates to the + Stage (global) coordinates.A Point object with coordinates relative to the Stage. + + flash.geom:Pointpointflash.geom:PointThe name or identifier of a point created with the Point class, specifying the + x and y coordinates as properties. + + + Converts the point object from the display object's (local) coordinates to the + Stage (global) coordinates. + +

This method allows you to convert any given x and y coordinates from + values that are relative to the origin (0,0) of a specific display object (local coordinates) + to values that are relative to the origin of the Stage (global coordinates).

+ +

To use this method, first create an instance of the Point class. The + x and y values that you assign represent local coordinates because they + relate to the origin of the display object.

+ +

You then pass the Point instance that you created as the parameter to + the localToGlobal() method. The method returns a new Point object with + x and y values that relate to the origin of the Stage + instead of the origin of the display object.

+ +
The following code creates a Sprite object. The mouseX and + mouseY properties of the sprite are in the coordinate space of the display + object. This code uses the localToGlobal() method to translate these + properties to the global (Stage) coordinates: + + +import flash.display.Sprite; +import flash.events.MouseEvent; +import flash.geom.Point; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFFCC00); +square.graphics.drawRect(0, 0, 100, 100); +square.x = 100; +square.y = 200; + +addChild(square); + +square.addEventListener(MouseEvent.CLICK, traceCoordinates) + +function traceCoordinates(event:MouseEvent):void { + var clickPoint:Point = new Point(square.mouseX, square.mouseY); + trace("display object coordinates:", clickPoint); + trace("stage coordinates:", square.localToGlobal(clickPoint)); +} +
globalToLocal()flash.geom.Point class
accessibilityProperties + The current accessibility options for this display object.flash.accessibility:AccessibilityProperties + The current accessibility options for this display object. If you modify the accessibilityProperties + property or any of the fields within accessibilityProperties, you must call + the Accessibility.updateProperties() method to make your changes take effect. + +

Note: For an object created in the Flash authoring environment, the value of accessibilityProperties + is prepopulated with any information you entered in the Accessibility panel for + that object.

+ +
The following example shows how the to attach a simple AccessibilityProperties + object to a TextField instance: + + +import flash.text.TextField; +import flash.accessibility.AccessibilityProperties; +import flash.accessibility.Accessibility; +import flash.system.Capabilities; + +var tf:TextField = new TextField(); +tf.text = "hello"; + +var accessProps:AccessibilityProperties = new AccessibilityProperties(); +accessProps.name = "Greeting"; + +tf.accessibilityProperties = accessProps; + +if (Capabilities.hasAccessibility) { + Accessibility.updateProperties(); +} + +trace(tf.accessibilityProperties.name); // Greeting +
flash.accessibility.Accessibility.updateProperties()flash.accessibility.AccessibilityProperties
alpha + Indicates the alpha transparency value of the object specified.Number + Indicates the alpha transparency value of the object specified. + Valid values are 0 (fully transparent) to 1 (fully opaque). + The default value is 1. Display objects with alpha + set to 0 are active, even though they are invisible. + + The following code sets the alpha property of a sprite + to 50% when the mouse rolls over the sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFF0000); +circle.graphics.drawCircle(40, 40, 40); +addChild(circle); + +circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject); +circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject); + +function dimObject(event:MouseEvent):void { + event.target.alpha = 0.5; +} + +function restoreObject(event:MouseEvent):void { + event.target.alpha = 1.0; +} +blendMode + A value from the BlendMode class that specifies which blend mode to use.String + A value from the BlendMode class that specifies which blend mode to use. + A bitmap can be drawn internally in two ways. If you have a blend mode enabled or an + external clipping mask, the bitmap is drawn by adding a bitmap-filled square shape to the vector + render. If you attempt to set this property to an invalid value, Flash runtimes set the value + to BlendMode.NORMAL. + +

The blendMode property affects each pixel of the display object. + Each pixel is composed of three constituent + colors (red, green, and blue), and each constituent color has a value between 0x00 and 0xFF. + Flash Player or Adobe AIR compares each constituent color of one pixel in the movie clip with + the corresponding color of the pixel in the background. For example, if blendMode + is set to BlendMode.LIGHTEN, Flash Player or Adobe AIR compares the red value of the display object with + the red value of the background, and uses the lighter of the two as the + value for the red component of the displayed color.

+ +

The following table describes the blendMode settings. + The BlendMode class defines string values you can use. + The illustrations in the table show blendMode values applied to a circular + display object (2) superimposed on another display object (1).

+ + +

+ + + + +

+ + + BlendMode ConstantIllustrationDescriptionBlendMode.NORMALThe display object appears in front of the background. Pixel values of the display object + override those of the background. Where the display object is transparent, the background is + visible.BlendMode.LAYERForces the creation of a transparency group for the display object. This means that the display + object is pre-composed in a temporary buffer before it is processed further. This is done + automatically if the display object is pre-cached using bitmap caching or if the display object is + a display object container with at least one child object with a blendMode + setting other than BlendMode.NORMAL. Not supported under GPU rendering. + BlendMode.MULTIPLYMultiplies the values of the display object constituent colors by the colors of the background color, + and then normalizes by dividing by 0xFF, + resulting in darker colors. This setting is commonly used for shadows and depth effects. + +

For example, if a constituent color (such as red) of one pixel in the display object and the + corresponding color of the pixel in the background both have the value 0x88, the multiplied + result is 0x4840. Dividing by 0xFF yields a value of 0x48 for that constituent color, + which is a darker shade than the color of the display object or the color of the background.

BlendMode.SCREENMultiplies the complement (inverse) of the display object color by the complement of the background + color, resulting in a bleaching effect. This setting is commonly used for highlights or to remove black + areas of the display object.BlendMode.LIGHTENSelects the lighter of the constituent colors of the display object and the color of the background (the + colors with the larger values). This setting is commonly used for superimposing type. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background + pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is + 0xFFF833 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33). Not supported under GPU rendering.

BlendMode.DARKENSelects the darker of the constituent colors of the display object and the colors of the + background (the colors with the smaller values). This setting is commonly used for superimposing type. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background + pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is + 0xDDCC00 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33). Not supported under GPU rendering.

BlendMode.DIFFERENCECompares the constituent colors of the display object with the colors of its background, and subtracts + the darker of the values of the two constituent colors from the lighter value. This setting is commonly + used for more vibrant colors. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background + pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is + 0x222C33 (because 0xFF - 0xDD = 0x22, 0xF8 - 0xCC = 0x2C, and 0x33 - 0x00 = 0x33).

BlendMode.ADDAdds the values of the constituent colors of the display object to the colors of its background, applying a + ceiling of 0xFF. This setting is commonly used for animating a lightening dissolve between + two objects. + +

For example, if the display object has a pixel with an RGB value of 0xAAA633, and the background + pixel has an RGB value of 0xDD2200, the resulting RGB value for the displayed pixel is + 0xFFC833 (because 0xAA + 0xDD > 0xFF, 0xA6 + 0x22 = 0xC8, and 0x33 + 0x00 = 0x33).

BlendMode.SUBTRACTSubtracts the values of the constituent colors in the display object from the values of the + background color, applying a floor of 0. This setting is commonly used for animating a + darkening dissolve between two objects. + +

For example, if the display object has a pixel with an RGB value of 0xAA2233, and the background + pixel has an RGB value of 0xDDA600, the resulting RGB value for the displayed pixel is + 0x338400 (because 0xDD - 0xAA = 0x33, 0xA6 - 0x22 = 0x84, and 0x00 - 0x33 < 0x00).

BlendMode.INVERTInverts the background.BlendMode.ALPHAApplies the alpha value of each pixel of the display object to the background. + This requires the blendMode setting of the parent display object to be set to + BlendMode.LAYER. + For example, in the illustration, the parent display object, which is a white background, + has blendMode = BlendMode.LAYER. Not supported under GPU rendering.BlendMode.ERASEErases the background based on the alpha value of the display object. This requires the + blendMode of the parent display object to be set to + BlendMode.LAYER. For example, in the + illustration, the parent display object, which is a white background, has + blendMode = BlendMode.LAYER. Not supported under GPU rendering.BlendMode.OVERLAYAdjusts the color of each pixel based on the darkness of the background. + If the background is lighter than 50% gray, the display object and background colors are + screened, which results in a lighter color. If the background is darker than 50% gray, + the colors are multiplied, which results in a darker color. + This setting is commonly used for shading effects. Not supported under GPU rendering.BlendMode.HARDLIGHTAdjusts the color of each pixel based on the darkness of the display object. + If the display object is lighter than 50% gray, the display object and background colors are + screened, which results in a lighter color. If the display object is darker than 50% gray, + the colors are multiplied, which results in a darker color. + This setting is commonly used for shading effects. Not supported under GPU rendering.BlendMode.SHADERN/AAdjusts the color using a custom shader routine. The shader that is used is specified + as the Shader instance assigned to the blendShader property. Setting the + blendShader property of a display object to a Shader instance + automatically sets the display object's blendMode property to + BlendMode.SHADER. If the blendMode property is set to + BlendMode.SHADER without first setting the blendShader property, + the blendMode property is set to BlendMode.NORMAL. Not supported under GPU rendering.
+ +
The following code creates two sprite objects, a square and a circle, + and sets the blend mode of the circle (in the foreground) to BlendMode.SUBTRACT + when the pointer rolls over the circle: + +import flash.display.Sprite; +import flash.display.BlendMode; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFF88CC); +square.graphics.drawRect(0, 0, 80, 80); +addChild(square); + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xAA0022); +circle.graphics.drawCircle(40, 40, 40); +addChild(circle); + +circle.addEventListener(MouseEvent.MOUSE_OVER, dimObject); +circle.addEventListener(MouseEvent.MOUSE_OUT, restoreObject); + +function dimObject(event:MouseEvent):void { + event.target.blendMode = BlendMode.SUBTRACT; +} + +function restoreObject(event:MouseEvent):void { + event.target.blendMode = BlendMode.NORMAL; +} +
flash.display.BlendModeblendShader
cacheAsBitmapMatrix + If non-null, this Matrix object defines how a display object is rendered when + cacheAsBitmap is set to true.flash.geom:MatrixThe transformation matrix used when rendering a cached version of + this display object's bitmap. + + If non-null, this Matrix object defines how a display object is rendered when + cacheAsBitmap is set to true. The application uses + this matrix as a transformation matrix that is applied when rendering the bitmap version of + the display object. + +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems. It also has + limited support on AIR for TV devices. + Specifically, on AIR for TV devices, supported transformations include scaling and translation, + but not rotation and skewing. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

With cacheAsBitmapMatrix set, the application retains a cached + bitmap image across various 2D transformations, including translation, rotation, + and scaling. If the application uses hardware acceleration, the object will + be stored in video memory as a texture. This allows the GPU to apply + the supported transformations to the object. The GPU + can perform these transformations faster than the CPU.

+ + +

To use the hardware acceleration, set Rendering to GPU in + the General tab of the iPhone Settings dialog box in Flash Professional CS5. + Or set the renderMode property to gpu in the + application descriptor file. Note that AIR for TV devices automatically + use hardware acceleration if it is available.

+ +

For example, the following code sends an untransformed bitmap representation + of the display object to the GPU:

+ + matrix:Matrix = new Matrix(); // creates an identity matrix + mySprite.cacheAsBitmapMatrix = matrix; + mySprite.cacheAsBitmap = true; + +

Usually, the identity matrix (new Matrix()) suffices. However, + you can use another matrix, such as a scaled-down matrix, to upload + a different bitmap to the GPU. For example, the following example applies + a cacheAsBitmapMatrix matrix that is scaled by 0.5 on the x and y axes. + The bitmap object that the GPU uses is smaller, however the GPU adjusts + its size to match the transform.matrix property of the display object:

+ + matrix:Matrix = new Matrix(); // creates an identity matrix + matrix.scale(0.5, 0.5); // scales the matrix + mySprite.cacheAsBitmapMatrix = matrix; + mySprite.cacheAsBitmap = true; + +

Generally, you should choose to use a matrix that transforms the display object + to the size that it will appear in the application. For example, if + your application displays the bitmap version of the sprite scaled down by a half, + use a matrix that scales down by a half. If you application will display + the sprite larger than its current dimensions, use a matrix that + scales up by that factor.

+ +

Note: The cacheAsBitmapMatrix property + is suitable for 2D transformations. If you need to apply transformations in 3D, + you may do so by setting a 3D property of the object and manipulating its + transform.matrix3D property. If the application is packaged + using GPU mode, this allows the 3D transforms to be applied to + the object by the GPU. The cacheAsBitmapMatrix is ignored + for 3D objects.

+ +
The following example applies uses the cacheAsBitmapMatrix property to apply transformations + to a bitmap version of the movie clip my_shape. + +import flash.geom.Matrix; +import flash.display.*; +import flash.utils.Timer; + +var my_shape:MovieClip = new MovieClip(); +my_shape.graphics.beginFill(0xCCFF00); +my_shape.graphics.drawRect(200, 0, 100, 100); +addChild(my_shape); + +var my_timer:Timer = new Timer(250); +my_timer.start(); +my_timer.addEventListener(TimerEvent.TIMER, timerHandler); + +// make sure this Display Object remains cached for all 2D transforms +my_shape.cacheAsBitmap = true; +my_shape.cacheAsBitmapMatrix = new Matrix(); + +// rotation variables +const initAngle:Number = 0; +const pi:Number = 3.142; +const incrAngle:Number = pi/10; + +// scaling variables +const initScale:Number = 0.25; +const incrScale: Number = 1.1; +var initHeight : Number = my_shape.height; +var initWidth : Number = my_shape.width; + +// translation variables +var incrX : Number = root.width / 20; +var incrY : Number = root.height / 10; + +// do some initial transforms +var tempMat : Matrix = my_shape.transform.matrix; +tempMat.rotate(initAngle); +tempMat.scale(initScale, initScale); + +my_shape.transform.matrix = tempMat; + +function timerHandler(evt:TimerEvent):void { + + tempMat = my_shape.transform.matrix; + + tempMat.rotate(incrAngle); + tempMat.translate(incrX, incrY); + tempMat.scale(incrScale, incrScale); + + my_shape.transform.matrix = tempMat; + + // ensure we are still in a reasonable state or reset + if(my_shape.height > stage.stageHeight/2) + { + my_shape.height = initHeight; + } + + if(my_shape.width > stage.stageWidth/2) + { + my_shape.width = initWidth; + } + + if(my_shape.x > stage.stageWidth) + { + my_shape.x = 0; + } + else if (my_shape.x < 0) + { + my_shape.x = stage.stageWidth; + } + + + if(my_shape.y > stage.stageHeight) + { + my_shape.y = 0; + } + else if (my_shape.y < 0) + { + my_shape.y = stage.stageHeight; + } + +} +
cacheAsBitmapflash.geom.Matrix3D
cacheAsBitmap + If set to true, Flash runtimes cache an internal bitmap representation of the + display object.BooleanWhether to cache this DisplayObject as a bitmap. + + + If set to true, Flash runtimes cache an internal bitmap representation of the + display object. This caching can increase performance for display objects that contain complex + vector content. + +

All vector data for a display object that has a cached bitmap is drawn to the bitmap + instead of the main display. If cacheAsBitmapMatrix is null or unsupported, + the bitmap is then copied to the main display as unstretched, unrotated pixels snapped to + the nearest pixel boundaries. Pixels are mapped 1 to 1 with + the parent object. If the bounds of the bitmap change, the bitmap is recreated instead + of being stretched.

+ +

If cacheAsBitmapMatrix is non-null and supported, the object is drawn to the off-screen bitmap + using that matrix and the stretched and/or rotated results of that rendering are used + to draw the object to the main display.

+ +

No internal bitmap is created unless the cacheAsBitmap property is set to + true.

+ +

After you set the cacheAsBitmap property to true, + the rendering does not change, however the display object performs pixel snapping + automatically. The animation speed can be significantly faster depending + on the complexity of the vector content. +

+ +

The cacheAsBitmap property is automatically set to true + whenever you apply a filter to a display object (when its filter array is not empty), + and if a display object has a filter applied to it, cacheAsBitmap is reported as + true for that display object, even if you set the property to false. + If you clear all filters for a display object, the cacheAsBitmap setting changes to + what it was last set to.

+ +

A display object does not use a bitmap even if the cacheAsBitmap + property is set to true and instead renders from vector data in the following cases:

+ +
  • The bitmap is too large. + In AIR 1.5 and Flash Player 10, the maximum size for a bitmap image is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a bitmap image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier, the limitation is + is 2880 pixels in height and 2,880 pixels in width.
  • The bitmap fails to allocate (out of memory error).
+ +

The cacheAsBitmap property is best used with movie clips that have + mostly static content and that do not scale and rotate frequently. With such movie + clips, cacheAsBitmap can lead to performance increases when the + movie clip is translated (when its x and y position is changed).

+ +
The following example applies a drop shadow to a Shape instance. + It then traces the value of the cacheAsBitmap property, which is set to + true when the filter is applied: + +import flash.display.Sprite; +import flash.filters.DropShadowFilter + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xAA0022); +circle.graphics.drawCircle(40, 40, 40); + +addChild(circle); + +trace(circle.cacheAsBitmap); // false + +var filter:DropShadowFilter = new DropShadowFilter(); +circle.filters = [filter]; + +trace(circle.cacheAsBitmap); // true +
cacheAsBitmapMatrixopaqueBackground
filters + An indexed array that contains each filter object currently associated with the display object.ArrayWhen filters includes a ShaderFilter and the shader + output type is not compatible with this operation + (the shader must specify a pixel4 + output). + + ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter and the shader + doesn't specify any image input or the first + input is not an image4 input. + + ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter and the shader + specifies an image input that isn't provided. + + ArgumentErrorArgumentErrorWhen filters includes a ShaderFilter, a + ByteArray or Vector.<Number> instance as + a shader input, and the width + and height properties aren't specified for the + ShaderInput object, or the specified values don't match the amount of + data in the input data. See the ShaderInput.input + property for more information. + + ArgumentErrorArgumentError + An indexed array that contains each filter object currently associated with the display object. + The flash.filters package contains several classes that define specific filters you can + use. + +

Filters can be applied in Flash Professional at design time, or at run time by using + ActionScript code. To apply a filter by using ActionScript, you must make a temporary copy of the + entire filters array, modify the temporary array, then assign the value + of the temporary array back to the filters array. You cannot directly + add a new filter object to the filters array.

+ +

To add a filter by using ActionScript, perform the following steps (assume that the + target display object is named myDisplayObject):

+ +
  1. Create a new filter object by using the constructor method of your chosen filter + class.
  2. Assign the value of the myDisplayObject.filters array to a temporary array, such + as one named myFilters.
  3. Add the new filter object to the myFilters temporary array.
  4. Assign the value of the temporary array to the myDisplayObject.filters array.
+ +

If the filters array is undefined, you do not need to use a temporary array. + Instead, you can directly assign an array literal that contains one or more filter objects that + you create. The first example in the Examples section adds a drop shadow filter by using + code that handles both defined and undefined filters arrays.

+ +

To modify an existing filter object, + you must use the technique of modifying a copy of the filters array:

+ +
  1. Assign the value of the filters array to a temporary array, such as one + named myFilters.
  2. Modify the property by using the temporary array, myFilters. For example, + to set the quality property of the first filter in the array, you could use the + following code: myFilters[0].quality = 1;
  3. Assign the value of the temporary array to the filters array.
+ +

At load time, if a display object has an associated filter, it is marked to cache itself as a + transparent bitmap. From this point forward, as long as the display object has a valid filter list, + the player caches the display object as a bitmap. This source bitmap is used as a source + image for the filter effects. Each display object usually has two bitmaps: one with the + original unfiltered source display object and another for the final image after filtering. + The final image is used when rendering. As long as the display object does not + change, the final image does not need updating.

+ +

The flash.filters package includes classes for filters. For example, to create a DropShadow + filter, you would write:

+ + + import flash.filters.DropShadowFilter + var myFilter:DropShadowFilter = new DropShadowFilter (distance, angle, color, alpha, blurX, blurY, quality, inner, knockout) + + +

You can use the is operator to determine the type of filter assigned to + each index position in the filter array. For example, the following code shows + how to determine the position of the first filter in the filters array that + is a DropShadowFilter: +

+ + + import flash.text.TextField; + import flash.filters.~~; + var tf:TextField = new TextField(); + var filter1:DropShadowFilter = new DropShadowFilter(); + var filter2:GradientGlowFilter = new GradientGlowFilter(); + tf.filters = [filter1, filter2]; + + tf.text = "DropShadow index: " + filterPosition(tf, DropShadowFilter).toString(); // 0 + addChild(tf) + + function filterPosition(displayObject:DisplayObject, filterClass:Class):int { + for (var i:uint = 0; i < displayObject.filters.length; i++) { + if (displayObject.filters[i] is filterClass) { + return i; + } + } + return -1; + } + +

Note: Since you cannot directly add a new filter object to the + DisplayObject.filters array, the following code has no + effect on the target display object, named myDisplayObject:

+ + + myDisplayObject.filters.push(myDropShadow); + + +
flash.filters packageflash.display.ShaderInput.input
height + Indicates the height of the display object, in pixels.Number + Indicates the height of the display object, in pixels. The height is calculated based on the bounds of the content of the display object. + When you set the height property, the scaleY property is adjusted accordingly, as shown in the + following code: + + + var rect:Shape = new Shape(); + rect.graphics.beginFill(0xFF0000); + rect.graphics.drawRect(0, 0, 100, 100); + trace(rect.scaleY) // 1; + rect.height = 200; + trace(rect.scaleY) // 2; + +

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a height + of 0, even if you try to set height to a different value.

+ +
The following code creates two TextField objects and adjusts the + height property of each based on the textHeight property of + each; it also positions the second text field by setting its y property: + +import flash.text.TextField; + +var tf1:TextField = new TextField(); +tf1.text = "Text Field 1"; +tf1.border = true; +tf1.wordWrap = true; +tf1.width = 40; +tf1.height = tf1.textHeight + 5; +addChild(tf1); + +var tf2:TextField = new TextField(); +tf2.text = "Text Field 2"; +tf2.border = true; +tf2.wordWrap = true; +tf2.width = 40; +tf2.height = tf2.textHeight + 5; +tf2.y = tf1.y + tf1.height + 5; +addChild(tf2); +
loaderInfo + Returns a LoaderInfo object containing information about loading the file + to which this display object belongs.flash.display:LoaderInfo + Returns a LoaderInfo object containing information about loading the file + to which this display object belongs. The loaderInfo property is defined only + for the root display object of a SWF file or for a loaded Bitmap (not for a Bitmap that is drawn + with ActionScript). To find the loaderInfo object associated with the SWF file that contains + a display object named myDisplayObject, use myDisplayObject.root.loaderInfo. + +

A large SWF file can monitor its download by calling + this.root.loaderInfo.addEventListener(Event.COMPLETE, func).

+ +
The following code assumes that this refers to + a display object. The code outputs the URL of the root SWF file for the + display object: + + trace (this.loaderInfo.url); + +
LoaderInfo class
mask + The calling display object is masked by the specified mask object.flash.display:DisplayObjectSets a mask for the display object. + + + The calling display object is masked by the specified mask object. + To ensure that masking works when the Stage is scaled, the mask display object + must be in an active part of the display list. The mask object itself is not drawn. + Set mask to null to remove the mask. + +

To be able to scale a mask object, it must be on the display list. To be able to drag a mask Sprite object + (by calling its startDrag() method), it must be on the display list. To call the + startDrag() method for a mask sprite based on a mouseDown event + being dispatched by the sprite, set the sprite's buttonMode property to true.

+ +

When display objects are cached by setting the cacheAsBitmap property to + true an the cacheAsBitmapMatrix property to a Matrix object, + both the mask and the display object being masked must be part of the same cached + bitmap. Thus, if the display object is cached, then the mask must be a child of the display object. + If an ancestor of the display object on the display list is cached, then the mask must be a child of + that ancestor or one of its descendents. If more than one ancestor of the masked object is cached, + then the mask must be a descendent of the cached container closest to the masked object in the display list.

+ +

Note: A single mask object cannot be used to mask more than one calling display object. + When the mask is assigned to a second display object, it is removed as the mask of the first + object, and that object's mask property becomes null.

+ +
The following code creates a TextField object as well as a Sprite object + that is set as a mask for the TextField object. When the user clicks the text + field, the drag() event listener function calls the startDrag() + method of the mask Sprite object: + +import flash.text.TextField; +import flash.display.Sprite; +import flash.events.MouseEvent; + +var tf:TextField = new TextField(); +tf.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " +tf.selectable = false; +tf.wordWrap = true; +tf.width = 150; +addChild(tf); + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFF0000); +square.graphics.drawRect(0, 0, 40, 40); +addChild(square); + +tf.mask = square; + +tf.addEventListener(MouseEvent.MOUSE_DOWN, drag); +tf.addEventListener(MouseEvent.MOUSE_UP, noDrag); + +function drag(event:MouseEvent):void { + square.startDrag(); +} +function noDrag(event:MouseEvent):void { + square.stopDrag(); +} +
mouseX + Indicates the x coordinate of the mouse or user input device position, in pixels.Number + Indicates the x coordinate of the mouse or user input device position, in pixels. + +

Note: For a DisplayObject that has been rotated, the returned x coordinate will reflect the + non-rotated object.

+ +
The following code creates a Sprite object and traces the mouseX + and mouseY positions when the user clicks the sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFF0000); +square.graphics.drawRect(0, 0, 200, 200); +addChild(square); + +square.addEventListener(MouseEvent.CLICK, traceCoordinates); + +function traceCoordinates(event:MouseEvent):void { + trace(square.mouseX, square.mouseY); +} +
mouseY + Indicates the y coordinate of the mouse or user input device position, in pixels.Number + Indicates the y coordinate of the mouse or user input device position, in pixels. + +

Note: For a DisplayObject that has been rotated, the returned y coordinate will reflect the + non-rotated object.

+ +
The following code creates a Sprite object and traces the mouseX + and mouseY positions when the user clicks the sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFF0000); +square.graphics.drawRect(0, 0, 200, 200); +addChild(square); + +square.addEventListener(MouseEvent.CLICK, traceCoordinates); + +function traceCoordinates(event:MouseEvent):void { + trace(square.mouseX, square.mouseY); +} +
name + Indicates the instance name of the DisplayObject.StringIf you are attempting to set this property on an object that was + placed on the timeline in the Flash authoring tool. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe name of this DisplayObject. + + + Indicates the instance name of the DisplayObject. The object can be identified in + the child list of its parent display object container by calling the + getChildByName() method of the display object container. + + The following code creates two Sprite object and traces the + associated name property when the user clicks either of the objects: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFF0000); +circle1.graphics.drawCircle(40, 40, 40); +circle1.name = "circle1"; +addChild(circle1); +circle1.addEventListener(MouseEvent.CLICK, traceName); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x0000FF); +circle2.graphics.drawCircle(140, 40, 40); +circle2.name = "circle2"; +addChild(circle2); +circle2.addEventListener(MouseEvent.CLICK, traceName); + +function traceName(event:MouseEvent):void { + trace(event.target.name); +} +opaqueBackground + Specifies whether the display object is opaque with a certain background color.Object + Specifies whether the display object is opaque with a certain background color. + A transparent bitmap contains alpha + channel data and is drawn transparently. An opaque bitmap has no alpha channel (and renders faster + than a transparent bitmap). If the bitmap is opaque, you specify its own background color to use. + +

If set to a number value, the surface is opaque (not transparent) with the RGB background + color that the number specifies. If set to null (the default value), the display + object has a transparent background.

+ +

The opaqueBackground property is intended mainly for use with the + cacheAsBitmap property, for rendering optimization. For display objects in which the + cacheAsBitmap property is set to true, setting opaqueBackground can + improve rendering performance.

+ +

The opaque background region is not matched when calling the hitTestPoint() + method with the shapeFlag parameter set to true.

+ +

The opaque background region does not respond to mouse events.

+ +
The following code creates a Shape object with a blue circle + and sets its opaqueBackground property to red (0xFF0000): + +import flash.display.Shape; + +var circle:Shape = new Shape(); +circle.graphics.beginFill(0x0000FF); +circle.graphics.drawCircle(40, 40, 40); +circle.opaqueBackground = 0xFF0000; +addChild(circle); +
cacheAsBitmaphitTestPoint()
parent + Indicates the DisplayObjectContainer object that contains this display object.flash.display:DisplayObjectContainerThe parent display object belongs to a security sandbox + to which you do not have access. You can avoid this situation by having + the parent movie call the Security.allowDomain() method. + + SecurityErrorSecurityError + Indicates the DisplayObjectContainer object that contains this display object. Use the parent + property to specify a relative path to display objects that are above the + current display object in the display list hierarchy. + +

You can use parent to move up multiple levels in the display list as in the following:

+ + + this.parent.parent.alpha = 20; + + +
The following code creates three Sprite objects and shows how + the parent property reflects the display list hierarchy: + + +import flash.display.Sprite; + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; +var sprite3:Sprite = new Sprite(); +sprite3.name = "sprite3"; + +sprite1.addChild(sprite2); +sprite2.addChild(sprite3); + +trace(sprite2.parent.name); // sprite1 +trace(sprite3.parent.name); // sprite2 +trace(sprite3.parent.parent.name); // sprite1 +
root + For a display object in a loaded SWF file, the root property is the + top-most display object in the portion of the display list's tree structure represented by that SWF file.flash.display:DisplayObjectReturn the root display object for this object. + + + For a display object in a loaded SWF file, the root property is the + top-most display object in the portion of the display list's tree structure represented by that SWF file. + For a Bitmap object representing a loaded image file, the root property is the Bitmap object + itself. For the instance of the main class of the first SWF file loaded, the root property is the + display object itself. The root property of the Stage object is the Stage object itself. The root + property is set to null for any display object that has not been added to the display list, unless + it has been added to a display object container that is off the display list but that is a child of the + top-most display object in a loaded SWF file. + +

For example, if you create a new Sprite object by calling the Sprite() constructor method, + its root property is null until you add it to the display list (or to a display + object container that is off the display list but that is a child of the top-most display object in a SWF file).

+ +

For a loaded SWF file, even though the Loader object used to load the file may not be on the display list, + the top-most display object in the SWF file has its root property set to itself. The Loader object + does not have its root property set until it is added as a child of a display object for which the + root property is set.

+ +
The following code shows the difference between the root + property for the Stage object, for a display object (a Loader object) that is not loaded (both before + and after it has been added to the display list), and for a loaded object (a loaded Bitmap object): + +import flash.display.Loader; +import flash.net.URLRequest; +import flash.events.Event; + +trace(stage.root); // [object Stage] + +var ldr:Loader = new Loader(); +trace (ldr.root); // null + +addChild(ldr); +trace (ldr.root); // [object ...] + +var urlReq:URLRequest = new URLRequest("example.jpg"); +ldr.load(urlReq); + +ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); + +function loaded(event:Event):void { + trace(ldr.content.root); // [object Bitmap] +} +
rotationX + Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number + Indicates the x-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent + clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or + subtracted from 360 to obtain a value within the range. + + In this example, two ellipses rotate using their rotationX and + rotationY properties. The first ellipse's registration point is set + to its center. It rotates around itself. The second ellipse rotates around + an external point. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.geom.*; + import flash.display.Graphics; + import flash.events.TimerEvent; + import flash.utils.Timer; + + public class RotationExample1 extends MovieClip { + private var ellipse:Shape = new Shape(); + private var speed:int = 10; + private var ellipse1:Shape; + private var ellipse2:Shape; + + public function RotationExample1():void { + + ellipse1 = drawEllipse(-50, -40, (this.stage.stageWidth / 2), + (this.stage.stageHeight / 2)); + + ellipse2 = drawEllipse(30, 40, (this.stage.stageWidth / 2), + (this.stage.stageHeight / 2)); + + this.addChild(ellipse1); + this.addChild(ellipse2); + + var t:Timer = new Timer(50); + t.addEventListener(TimerEvent.TIMER, timerHandler); + t.start(); + } + + private function drawEllipse(x1, y1, x2, y2):Shape { + + var e:Shape = new Shape(); + e.graphics.beginFill(0xFF0000); + e.graphics.lineStyle(2); + e.graphics.drawEllipse(x1, y1, 100, 80); + e.graphics.endFill(); + + e.x = x2; + e.y = y2; + e.z = 1; + return e; + } + + private function timerHandler(event:TimerEvent):void { + ellipse1.rotationY += speed; + ellipse1.rotationX -= speed; + + ellipse2.rotationY += speed; + ellipse2.rotationX -= speed; + } + } +} + The following example shows how you can 3D rotate a Sprite object around its x-axis with Flash Professional, ActionScript 3.0, and Flash Player 10 by setting the object's rotationX property. + Example provided by + ActionScriptExamples.com. + +//Requires: +// - Slider control UI component in Flash library. +// - Publish for Flash Player 10. +// + +[SWF(width="400", height="300")] + +import fl.controls.Slider; +import fl.controls.SliderDirection; +import fl.events.SliderEvent; + +var slider:Slider = new Slider(); +slider.direction = SliderDirection.HORIZONTAL; +slider.minimum = 0; +slider.maximum = 360; +slider.value = 45; +slider.tickInterval = 45; +slider.snapInterval = 1; +slider.liveDragging = true; +slider.addEventListener(SliderEvent.CHANGE, slider_change); +slider.move(10, 10); +addChild(slider); + +var spr:Sprite = new Sprite(); +spr.graphics.lineStyle(2, 0xFF0000); +spr.graphics.drawRect(0, 0, 100, 80); +spr.x = Math.round((stage.stageWidth - spr.width)/2); +spr.y = Math.round((stage.stageHeight - spr.height)/2); +spr.rotationX = 45; +addChild(spr); + +function slider_change(evt:SliderEvent):void { + spr.rotationX = evt.value; +} +rotationY + Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number + Indicates the y-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent + clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or + subtracted from 360 to obtain a value within the range. + + + In this example, two ellipses rotate using their rotationX and + rotationY properties. The first ellipse's registration point is set + to its center. It rotates around itself. The second ellipse rotates around + an external point. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.geom.*; + import flash.display.Graphics; + import flash.events.TimerEvent; + import flash.utils.Timer; + + public class RotationExample1 extends MovieClip { + private var ellipse:Shape = new Shape(); + private var speed:int = 10; + private var ellipse1:Shape; + private var ellipse2:Shape; + + public function RotationExample1():void { + + ellipse1 = drawEllipse(-50, -40, (this.stage.stageWidth / 2), + (this.stage.stageHeight / 2)); + + ellipse2 = drawEllipse(30, 40, (this.stage.stageWidth / 2), + (this.stage.stageHeight / 2)); + + this.addChild(ellipse1); + this.addChild(ellipse2); + + var t:Timer = new Timer(50); + t.addEventListener(TimerEvent.TIMER, timerHandler); + t.start(); + } + + private function drawEllipse(x1, y1, x2, y2):Shape { + + var e:Shape = new Shape(); + e.graphics.beginFill(0xFF0000); + e.graphics.lineStyle(2); + e.graphics.drawEllipse(x1, y1, 100, 80); + e.graphics.endFill(); + + e.x = x2; + e.y = y2; + e.z = 1; + return e; + } + + private function timerHandler(event:TimerEvent):void { + ellipse1.rotationY += speed; + ellipse1.rotationX -= speed; + + ellipse2.rotationY += speed; + ellipse2.rotationX -= speed; + } + } +} +rotationZ + Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container.Number + Indicates the z-axis rotation of the DisplayObject instance, in degrees, from its original orientation relative to the 3D parent container. Values from 0 to 180 represent + clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or + subtracted from 360 to obtain a value within the range. + + + rotation + Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation.Number + Indicates the rotation of the DisplayObject instance, in degrees, from its original orientation. Values from 0 to 180 represent + clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or + subtracted from 360 to obtain a value within the range. For example, the statement my_video.rotation = 450 is the + same as my_video.rotation = 90. + + The following code creates a Sprite object and rotates + the object when the user clicks it: + + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFFCC00); +square.graphics.drawRect(-50, -50, 100, 100); +square.x = 150; +square.y = 150; +addChild(square); + +square.addEventListener(MouseEvent.CLICK, rotate); + +function rotate(event:MouseEvent):void { + square.rotation += 15; +} +scale9Grid + The current scaling grid that is in effect.flash.geom:RectangleIf you pass an invalid argument to the method. + + ArgumentErrorArgumentError + The current scaling grid that is in effect. If set to null, + the entire display object is scaled normally when any scale transformation is + applied. + +

When you define the scale9Grid property, the display object is divided into a + grid with nine regions based on the scale9Grid rectangle, which defines the + center region of the grid. The eight other regions of the grid are the following areas:

+ +
  • The upper-left corner outside of the rectangle
  • The area above the rectangle
  • The upper-right corner outside of the rectangle
  • The area to the left of the rectangle
  • The area to the right of the rectangle
  • The lower-left corner outside of the rectangle
  • The area below the rectangle
  • The lower-right corner outside of the rectangle
+ +

You can think of the eight regions outside of the center (defined by the rectangle) + as being like a picture frame that has special rules applied to it when scaled.

+ +

When the scale9Grid property is set and a display object is scaled, all text and + gradients are scaled normally; however, for other types of objects the following rules apply:

+ +
  • Content in the center region is scaled normally.
  • Content in the corners is not scaled.
  • Content in the top and bottom regions is scaled horizontally only. Content in the + left and right regions is scaled vertically only.
  • All fills (including bitmaps, video, and gradients) are stretched to fit their shapes.
+ +

If a display object is rotated, all subsequent scaling is normal (and the + scale9Grid property is ignored).

+ +

For example, consider the following display object and a rectangle that is applied as the display + object's scale9Grid:

+ + +

The display object.

+

The red rectangle shows the scale9Grid.

+ +

When the display object is scaled or stretched, the objects within the rectangle scale + normally, but the objects outside of the rectangle scale according to the + scale9Grid rules:

+ + Scaled to 75%:Scaled to 50%:Scaled to 25%:Stretched horizontally 150%: + +

A common use for setting scale9Grid is to set up a display object to be used + as a component, in which edge regions retain the same width when the component is scaled.

+ +
The following code creates a Shape object with a rectangle drawn in its + graphics property. The rectangle has a 20-pixel-thick line as the border and + it is filled with a gradient. The timer event calls the scale() function, which + scales the Shape object by adjusting the scaleX and scaleY properties. + The scale9Grid applied to the Shape object prevents the rectangle's border line + from scaling — only the gradient fill scales: + + +import flash.display.Shape; +import flash.display.GradientType; +import flash.display.SpreadMethod; +import flash.display.InterpolationMethod; +import flash.geom.Matrix; +import flash.geom.Rectangle; +import flash.utils.Timer; +import flash.events.TimerEvent; + +var square:Shape = new Shape(); +square.graphics.lineStyle(20, 0xFFCC00); +var gradientMatrix:Matrix = new Matrix(); +gradientMatrix.createGradientBox(15, 15, Math.PI, 10, 10); +square.graphics.beginGradientFill(GradientType.RADIAL, + [0xffff00, 0x0000ff], + [100, 100], + [0, 0xFF], + gradientMatrix, + SpreadMethod.REFLECT, + InterpolationMethod.RGB, + 0.9); +square.graphics.drawRect(0, 0, 100, 100); + +var grid:Rectangle = new Rectangle(20, 20, 60, 60); +square.scale9Grid = grid ; + +addChild(square); + +var tim:Timer = new Timer(100); +tim.start(); +tim.addEventListener(TimerEvent.TIMER, scale); + +var scaleFactor:Number = 1.01; + +function scale(event:TimerEvent):void { + square.scaleX *= scaleFactor; + square.scaleY *= scaleFactor; + + if (square.scaleX > 2.0) { + scaleFactor = 0.99; + } + if (square.scaleX < 1.0) { + scaleFactor = 1.01; + } +} +
flash.geom.Rectangle
scaleX + Indicates the horizontal scale (percentage) of the object as applied from the registration point.Number + Indicates the horizontal scale (percentage) of the object as applied from the registration point. The default + registration point is (0,0). 1.0 equals 100% scale. + +

Scaling the local coordinate system changes the x and y property values, which are defined in + whole pixels.

+ +
The following code creates a Sprite object with a rectangle drawn in its + graphics property. When the user clicks the sprite, it scales by 10%: + + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFFCC00); +square.graphics.drawRect(0, 0, 100, 100); +addChild(square); + +square.addEventListener(MouseEvent.CLICK, scale); + +function scale(event:MouseEvent):void { + square.scaleX *= 1.10; + square.scaleY *= 1.10; +} +
scaleY + Indicates the vertical scale (percentage) of an object as applied from the registration point of the object.Number + Indicates the vertical scale (percentage) of an object as applied from the registration point of the object. The + default registration point is (0,0). 1.0 is 100% scale. + +

Scaling the local coordinate system changes the x and y property values, which are defined in + whole pixels.

+ +
The following code creates a Sprite object with a rectangle drawn in its + graphics property. When the user clicks the sprite, it scales by 10%: + + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFFCC00); +square.graphics.drawRect(0, 0, 100, 100); +addChild(square); + +square.addEventListener(MouseEvent.CLICK, scale); + +function scale(event:MouseEvent):void { + square.scaleX *= 1.10; + square.scaleY *= 1.10; +} +
scaleZ + Indicates the depth scale (percentage) of an object as applied from the registration point of the object.Number + Indicates the depth scale (percentage) of an object as applied from the registration point of the object. The + default registration point is (0,0). 1.0 is 100% scale. + +

Scaling the local coordinate system changes the x, y and z property values, which are defined in + whole pixels.

+ + +
z
scrollRect + The scroll rectangle bounds of the display object.flash.geom:Rectangle + The scroll rectangle bounds of the display object. The display object is cropped to the size + defined by the rectangle, and it scrolls within the rectangle when you change the + x and y properties of the scrollRect object. + +

The properties of the scrollRect Rectangle object use the display object's coordinate space + and are scaled just like the overall display object. The corner bounds of the cropped window on the scrolling + display object are the origin of the display object (0,0) and the point defined by the + width and height of the rectangle. They are not centered around the origin, but + use the origin to define the upper-left corner of the area. A scrolled display object always + scrolls in whole pixel increments.

+ +

You can scroll an object left and right by setting the x property of the + scrollRect Rectangle object. You can scroll an object up and down by setting + the y property of the scrollRect Rectangle object. If the display object + is rotated 90° and you scroll it left and right, the display object actually scrolls up and down.

+ +
The following example shows how the scrollRect property defines the + scrolling area for a display object, circle. When you click the circle object, + the clicked() event handler method adjusts the y property of the + scrollRect property of the circle object, causing the object to scroll down: + + +import flash.display.Sprite; +import flash.geom.Rectangle; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(200, 200, 200); +circle.scrollRect = new Rectangle(0, 0, 200, 200); +addChild(circle); + +circle.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void { + var rect:Rectangle = event.target.scrollRect; + rect.y -= 5; + event.target.scrollRect = rect; +} +
flash.geom.Rectangle
stage + The Stage of the display object.flash.display:Stage + The Stage of the display object. A Flash runtime application has only one Stage object. + For example, you can create and load multiple display objects into the display list, and the + stage property of each display object refers to the same Stage object (even if the + display object belongs to a loaded SWF file). + +

If a display object is not added to the display list, its stage property is set to + null.

+ +
The following code creates two TextField objects and uses the + width property of the Stage object to position the text fields: + + +import flash.text.TextField; + +var tf1:TextField = new TextField(); +tf1.text = "Text Field 1"; +tf1.border = true; +tf1.x = 10; +addChild(tf1); +tf1.width = tf1.stage.stageWidth / 2 - 10; + +var tf2:TextField = new TextField(); +tf2.text = "Text Field 2"; +tf2.border = true; +tf2.x = tf1.x + tf1.width + 5; +addChild(tf2); +tf2.width = tf2.stage.stageWidth / 2 - 10; + +trace(stage.stageWidth); +
transform + An object with properties pertaining to a display object's matrix, color transform, and pixel bounds.flash.geom:Transform + An object with properties pertaining to a display object's matrix, color transform, and pixel bounds. + The specific properties — matrix, colorTransform, and three read-only properties + (concatenatedMatrix, concatenatedColorTransform, + and pixelBounds) — are described in the entry for the Transform class. + +

Each of the transform object's properties is itself an object. This concept is important because the only + way to set new values for the matrix or colorTransform objects is to create a new object and copy that + object into the transform.matrix or transform.colorTransform property.

+ +

For example, to increase the tx value of a display object's matrix, you must make a + copy of the entire matrix object, then copy the new object into the matrix property of the transform + object:

+ +

+    var myMatrix:Matrix = myDisplayObject.transform.matrix;  
+    myMatrix.tx += 10; 
+    myDisplayObject.transform.matrix = myMatrix;  
+    
+ +

You cannot directly set the tx property. The following code has + no effect on myDisplayObject:

+ +

+    myDisplayObject.transform.matrix.tx += 10;
+    
+ +

You can also copy an entire transform object and assign it to another + display object's transform property. For example, the following code + copies the entire transform object from myOldDisplayObj to + myNewDisplayObj:

+ myNewDisplayObj.transform = myOldDisplayObj.transform; +

The resulting display object, myNewDisplayObj, now has the same values for its + matrix, color transform, and pixel bounds as the old display object, myOldDisplayObj.

+ +

Note that AIR for TV devices use hardware acceleration, if it is available, for color transforms.

+ +
The following code sets up a square Sprite object. + When the user clicks the sprite, the transformer() method adjusts + the colorTransform and matrix properties of the + transform property of the sprite: + + +import flash.display.Sprite; +import flash.geom.ColorTransform; +import flash.geom.Matrix; +import flash.geom.Transform; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.lineStyle(20, 0xFF2200); +square.graphics.beginFill(0x0000DD); +square.graphics.drawRect(0, 0, 100, 100); +addChild(square); + +var resultColorTransform:ColorTransform = new ColorTransform(); +resultColorTransform.alphaMultiplier = 0.5; +resultColorTransform.redOffset = 155; +resultColorTransform.greenMultiplier = 0.5; + +var skewMatrix:Matrix = new Matrix(1, 1, 0, 1); + +square.addEventListener(MouseEvent.CLICK, transformer); + +function transformer(event:MouseEvent):void { + var transformation:Transform = square.transform; + var tempMatrix:Matrix = square.transform.matrix; + tempMatrix.concat(skewMatrix); + square.transform.colorTransform = resultColorTransform; + + square.transform.matrix = tempMatrix; +} +
Transform class
visible + Whether or not the display object is visible.Boolean + Whether or not the display object is visible. Display objects that are not visible + are disabled. For example, if visible=false for an InteractiveObject instance, + it cannot be clicked. + + The following code uses a Timer object to call a function that + periodically changes the visible property of a display object, + resulting in a blinking effect: + + +import flash.text.TextField; +import flash.utils.Timer; +import flash.events.TimerEvent; + +var tf:TextField = new TextField(); +tf.text = "Hello."; +addChild(tf); + +var tim:Timer = new Timer(250); +tim.start(); +tim.addEventListener(TimerEvent.TIMER, blinker); + +function blinker(event:TimerEvent):void { + tf.visible = !tf.visible; +} +width + Indicates the width of the display object, in pixels.Number + Indicates the width of the display object, in pixels. The width is calculated based on the bounds of the content of the display object. + When you set the width property, the scaleX property is adjusted accordingly, as shown in the + following code: + + + var rect:Shape = new Shape(); + rect.graphics.beginFill(0xFF0000); + rect.graphics.drawRect(0, 0, 100, 100); + trace(rect.scaleX) // 1; + rect.width = 200; + trace(rect.scaleX) // 2; + +

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a width + of 0, even if you try to set width to a different value.

+ +
The following code sets up a square Sprite object. + When the user clicks the sprite, the widen() method increases + the width property of the sprite: + + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xFF0000); +square.graphics.drawRect(0, 0, 100, 100); +addChild(square); + +square.addEventListener(MouseEvent.CLICK, widen); + +function widen(event:MouseEvent):void { + square.width += 10; +} +
x + Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of + the parent DisplayObjectContainer.Number + Indicates the x coordinate of the DisplayObject instance relative to the local coordinates of + the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has + transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. + Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's + children inherit a coordinate system that is rotated 90° counterclockwise. + The object's coordinates refer to the registration point position. + + The following code sets up a circle Sprite object. + A Timer object is used to change the x property of the sprite + every 50 milliseconds: + + +import flash.display.Sprite; +import flash.utils.Timer; +import flash.events.TimerEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFF0000); +circle.graphics.drawCircle(100, 100, 100); +addChild(circle); + +var tim:Timer = new Timer(50); +tim.start(); +tim.addEventListener(TimerEvent.TIMER, bounce); + +var xInc:Number = 2; + +function bounce(event:TimerEvent):void { + circle.x += xInc; + if (circle.x > circle.width) { + xInc = -2; + } + if (circle.x < 0) { + xInc = 2; + } +} +y + Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of + the parent DisplayObjectContainer.Number + Indicates the y coordinate of the DisplayObject instance relative to the local coordinates of + the parent DisplayObjectContainer. If the object is inside a DisplayObjectContainer that has + transformations, it is in the local coordinate system of the enclosing DisplayObjectContainer. + Thus, for a DisplayObjectContainer rotated 90° counterclockwise, the DisplayObjectContainer's + children inherit a coordinate system that is rotated 90° counterclockwise. + The object's coordinates refer to the registration point position. + + The following code creates two TextField objects and adjusts the + height property of each based on the textHeight property of + each; it also positions the second text field by setting its y property: + +import flash.text.TextField; + +var tf1:TextField = new TextField(); +tf1.text = "Text Field 1"; +tf1.border = true; +tf1.wordWrap = true; +tf1.width = 40; +tf1.height = tf1.textHeight + 5; +addChild(tf1); + +var tf2:TextField = new TextField(); +tf2.text = "Text Field 2"; +tf2.border = true; +tf2.wordWrap = true; +tf2.width = 40; +tf2.height = tf2.textHeight + 5; +tf2.y = tf1.y + tf1.height + 5; +addChild(tf2); +z + Indicates the z coordinate position along the z-axis of the DisplayObject + instance relative to the 3D parent container.Number + Indicates the z coordinate position along the z-axis of the DisplayObject + instance relative to the 3D parent container. The z property is used for + 3D coordinates, not screen or pixel coordinates. +

When you set a z property for a display object to something other than the default + value of 0, a corresponding Matrix3D object is automatically created. for adjusting a + display object's position and orientation + in three dimensions. When working with the z-axis, + the existing behavior of x and y properties changes from screen or pixel coordinates to + positions relative to the 3D parent container.

+

For example, a child of the _root at position x = 100, y = 100, z = 200 + is not drawn at pixel location (100,100). The child is drawn wherever the 3D projection + calculation puts it. The calculation is:

+

(x~~cameraFocalLength/cameraRelativeZPosition, y~~cameraFocalLength/cameraRelativeZPosition)

+ + +
This example draws two ellipses and has them go back and forth (down and up the + z axis) toward the vanishing point. One ellipse is set to move faster + than the other. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.display.Graphics; + import flash.events.Event; + import flash.geom.*; + + public class ZAxisExample1 extends MovieClip { + private var ellipse1Back:int = 1; + private var ellipse2Back:int = 1; + private var depth:int = 1000; + + public function ZAxisExample1():void { + + var ellipse1 = drawEllipse((this.stage.stageWidth / 2) - 100, + (this.stage.stageHeight / 2), 100, 80, 10); + var ellipse2 = drawEllipse((this.stage.stageWidth / 2) + 100, + (this.stage.stageHeight / 2), 100, 80, 300); + + this.addChild(ellipse1); + this.addChild(ellipse2); + + ellipse1.addEventListener(Event.ENTER_FRAME, ellipse1FrameHandler); + ellipse2.addEventListener(Event.ENTER_FRAME, ellipse2FrameHandler); + } + + private function drawEllipse(x:Number, y:Number, w:Number, h:Number, z:Number):Shape { + var s:Shape = new Shape(); + s.z = z; + s.graphics.beginFill(0xFF0000); + s.graphics.lineStyle(2); + s.graphics.drawEllipse(x, y, w, h); + s.graphics.endFill(); + return s; + } + + private function ellipse1FrameHandler(e:Event):void { + ellipse1Back = setDepth(e, ellipse1Back); + e.currentTarget.z += ellipse1Back * 10; + } + + private function ellipse2FrameHandler(e:Event):void { + ellipse2Back = setDepth(e, ellipse2Back); + e.currentTarget.z += ellipse2Back * 20; + } + + private function setDepth(e:Event, d:int):int { + if(e.currentTarget.z > depth) { + e.currentTarget.z = depth; + d = -1; + }else if (e.currentTarget.z < 0) { + e.currentTarget.z = 0; + d = 1; + } + return d; + } + } +} +
flash.geom.PerspectiveProjectionflash.geom.Matrix3Dtransform
blendShader + Sets a shader that is used for blending the foreground and background.flash.display:ShaderWhen the shader output type is not compatible with this operation + (the shader must specify a pixel4 + output). + + ArgumentErrorArgumentErrorWhen the shader specifies fewer than two image inputs or the first + two inputs are not image4 inputs. + + ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. + + ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as + an input and the width + and height properties aren't specified for the + ShaderInput, or the specified values don't match the amount of + data in the input object. See the ShaderInput.input + property for more information. + + ArgumentErrorArgumentError + Sets a shader that is used for blending the foreground and background. When the + blendMode property is set to BlendMode.SHADER, the specified + Shader is used to create the blend mode output for the display object. + +

Setting the blendShader property of a display object to a Shader instance + automatically sets the display object's blendMode property to + BlendMode.SHADER. If the blendShader property is set (which sets the + blendMode property to BlendMode.SHADER), then the value of the + blendMode property is changed, the blend mode can be reset to use the blend + shader simply by setting the blendMode property to BlendMode.SHADER. + The blendShader property does not need to be set again except to change the + shader that's used for the blend mode.

+ +

The Shader assigned to the blendShader property must specify at least two + image4 inputs. The inputs do not need to be specified in code using the + associated ShaderInput objects' input properties. The background display object + is automatically + used as the first input (the input with index 0). The foreground display object + is used as the second input (the input with index 1). A shader used as a blend + shader can specify more than two inputs. In that case, any additional input must be specified + by setting its ShaderInput instance's input property.

+ +

When you assign a Shader instance to this property the shader is copied internally. The + blend operation uses that internal copy, not a reference to the original shader. Any changes + made to the shader, such as changing a parameter value, input, or bytecode, are not applied + to the copied shader that's used for the blend mode.

+ +
flash.display.BlendModeflash.display.Shaderflash.display.ShaderInput
Loader + The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files.flash.display:DisplayObjectContainer + The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files. Use the + load() method to initiate loading. The loaded display object is added as a child + of the Loader object. + +

Use the URLLoader class to load text or binary data.

+ +

The Loader class overrides the following methods that it inherits, because a Loader object can only + have one child display object—the display object that it loads. Calling the following methods throws an + exception: addChild(), addChildAt(), removeChild(), + removeChildAt(), and setChildIndex(). To remove a loaded display object, + you must remove the Loader object from its parent DisplayObjectContainer child array.

+ +

Note: The ActionScript 2.0 MovieClipLoader and LoadVars classes are not used + in ActionScript 3.0. The Loader and URLLoader classes replace them.

+ +

When you use the Loader class, consider the Flash Player and Adobe AIR security model:

+ +
  • You can load content from any accessible source.
  • Loading is not allowed if the calling SWF file is in a network sandbox and the file + to be loaded is local.
  • If the loaded content is a SWF file written with ActionScript 3.0, it cannot be + cross-scripted by a SWF file in another security sandbox unless that cross-scripting + arrangement was approved through a call to the System.allowDomain() or + the System.allowInsecureDomain() method in the loaded content file.
  • If the loaded content is an AVM1 SWF file (written using ActionScript 1.0 or 2.0), + it cannot be cross-scripted by an AVM2 SWF file (written using ActionScript 3.0). However, + you can communicate between the two SWF files by using the LocalConnection class.
  • If the loaded content is an image, its data cannot be accessed by a SWF file + outside of the security sandbox, unless the domain of that SWF file was included in a + URL policy file at the origin domain of the image.
  • Movie clips in the local-with-file-system sandbox cannot script movie clips in the + local-with-networking sandbox, and the reverse is also prevented.
  • You cannot connect to commonly reserved ports. For a complete list of blocked ports, + see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.
+ +

However, in AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +

When loading a SWF file from an untrusted source (such as a domain other than that of + the Loader object's root SWF file), you may want to define a mask for the Loader object, + to prevent the loaded content (which is a child of the Loader object) from drawing to + portions of the Stage outside of that mask, as shown in the following code:

+ + import flash.display.~~; + import flash.net.URLRequest; + var rect:Shape = new Shape(); + rect.graphics.beginFill(0xFFFFFF); + rect.graphics.drawRect(0, 0, 100, 100); + rect.graphics.endFill(); + addChild(rect); + var ldr:Loader = new Loader(); + ldr.mask = rect; + var url:String = "http://www.unknown.example.com/content.swf"; + var urlReq:URLRequest = new URLRequest(url); + ldr.load(urlReq); + addChild(ldr); + + +
The following example uses the LoaderExample class to illustrate how various + event listeners are used. This task is accomplished by performing the following steps: +
  1. A url property is created, which is the location and name of the image file
  2. In the LoaderExample constructor, a new Loader object named loader is + created, which is then passed to the configureListeners() method, described in step 3.
  3. The constructor creates a new instance of a URLRequest object, + request, with url passed so that the file name and location are known.
  4. The request object is passed to the loader object's + load() method, which loads the image onto the display list.
  5. A clickHandler event listener is registered for the click event on the loader. + After a mouse click, the loaded image is unloaded.
  6. The configureListeners() method adds seven event listeners by using the following methods: +
    • The completeHandler() method executes when the image finishes loading.
    • The httpStatusHandler() method executes if the image is not loaded + locally and only if the network request is made available and the Flash Player can detect it.
    • The initHandler() method executes before the completeHandler() + method and after the progressHandler() method. Generally, the init + event is more useful when loading SWF files.
    • The ioErrorHandler() method executes if the image file is not available or not + accessible.
    • The openHandler() method executes when the image file is first opened.
    • The progressHandler() method executes when the image file starts to load and + again when the image is finished loading.
    • The unLoadHandler() method executes when the image is unloaded by using the + unload() method when the user clicks the image.
    +
+

Keep in mind the following requirements:

+ +
  • This example requires that you place a file named Image.gif in the same directory as the compiled SWF file. + Use an image that has an area that fits within the dimensions of the main SWF file.
  • Although this example makes use of all events available to the LoaderInfo object, most situations + require only a subset. In particular, when loading only an image file, the complete event + (and perhaps the ioError event) are sufficient when loading a local image.
+ + +package { + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.*; + import flash.net.URLRequest; + + public class LoaderExample extends Sprite { + private var url:String = "Image.gif"; + + public function LoaderExample() { + var loader:Loader = new Loader(); + configureListeners(loader.contentLoaderInfo); + loader.addEventListener(MouseEvent.CLICK, clickHandler); + + var request:URLRequest = new URLRequest(url); + loader.load(request); + + addChild(loader); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(Event.INIT, initHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(Event.UNLOAD, unLoadHandler); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function initHandler(event:Event):void { + trace("initHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function unLoadHandler(event:Event):void { + trace("unLoadHandler: " + event); + } + + private function clickHandler(event:MouseEvent):void { + trace("clickHandler: " + event); + var loader:Loader = Loader(event.target); + loader.unload(); + } + } +} +
flash.display.LoaderInfoflash.net.URLLoaderflash.display.DisplayObjectLoader + Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. + Creates a Loader object that you can use to load files, such as SWF, JPEG, GIF, or PNG files. + Call the load() method to load the asset as a child of the Loader instance. + You can then add the Loader object to the display list (for instance, by using the + addChild() method of a DisplayObjectContainer instance). + The asset appears on the Stage as it loads. + +

You can also use a Loader instance "offlist," that is without adding it to a display object + container on the display list. In this mode, the Loader instance might be used to load a SWF file + that contains additional modules of an application.

+ +

To detect when the SWF file is finished loading, you can use the events of the LoaderInfo + object associated with the contentLoaderInfo property of the Loader object. + At that point, the code in the module SWF file can be executed to initialize and start the module. + In the offlist mode, a Loader instance might also be used to load a SWF file that contains components or + media assets. Again, you can use the LoaderInfo object event notifications to detect when the + components are finished loading. At that point, the application can start using the components + and media assets in the library of the SWF file by instantiating the ActionScript 3.0 classes that represent + those components and assets.

+ +

To determine the status of a Loader object, monitor the following events that the LoaderInfo + object associated with the contentLoaderInfo property of the Loader object:

+ +
  • The open event is dispatched when loading begins.
  • The ioError or securityError event is dispatched if the file + cannot be loaded or if an error occured during the load process.
  • The progress event fires continuously while the file is being loaded.
  • The complete event is dispatched when a file completes downloading, but before + the loaded movie clip's methods and properties are available.
  • The init event is dispatched after the properties and methods of the loaded SWF file + are accessible, so you can begin manipulating the loaded SWF file. + This event is dispatched before the complete handler. In streaming SWF files, + the init event can occur significantly earlier than the complete event. + For most purposes, use the init handler.
+ +
flash.display.Loader.load()flash.display.LoaderInfo
close + Cancels a load() method operation that is currently in progress for the Loader instance. + Cancels a load() method operation that is currently in progress for the Loader instance. + + flash.display.Loader.load()loadBytes + Loads from binary data stored in a ByteArray object.If the length property of the ByteArray object is not + greater than 0. + + ArgumentErrorArgumentErrorIf the checkPolicyFile or securityDomain + property of the context parameter are non-null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the requestedContentParent property of the context parameter + is a Loader. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is + set to non-null and has some values which are not Strings. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the provided applicationDomain property of the + context property is from a disallowed domain. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorbytesflash.utils:ByteArrayA ByteArray object. The contents of the ByteArray can be + any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG. + + contextflash.system:LoaderContextnullA LoaderContext object. Only the applicationDomain property + of the LoaderContext object applies; the checkPolicyFile and securityDomain + properties of the LoaderContext object do not apply. + +

If the context parameter is not + specified or refers to a null object, the content is loaded into the current security domain— a + process referred to as "import loading" in Flash Player security documentation. Specifically, + if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, + then the loading SWF can import it directly into its own security domain.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
+ Loads from binary data stored in a ByteArray object. + +

The loadBytes() method is asynchronous. You must wait for the "init" event before + accessing the properties of a loaded object.

+ +

When you use this method, consider the Flash Player security model, + which is described in the Loader class description.

+ +
flash.utils.ByteArrayflash.system.LoaderContext.applicationDomainasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a + flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws + an error. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the operation is + complete. The complete event is always dispatched after the init event. + + Dispatched by the contentLoaderInfo object when the operation is + complete.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods + of the loaded data are accessible. The init event always precedes the complete + event. + + Dispatched by the contentLoaderInfo object when the properties and methods + of the loaded data are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when the runtime cannot parse + the data in the byte array. + + Dispatched by the contentLoaderInfo object when the runtime cannot parse + the data in the byte array.openflash.events:EventDispatched by the contentLoaderInfo object when the operation starts. + + Dispatched by the contentLoaderInfo object when the operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is transfered in memory. + + Dispatched by the contentLoaderInfo object as data is transfered in memory.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. + + Dispatched by the contentLoaderInfo object when a loaded object is removed.
loadFilePromise + Loads an IFilePromise instance.If the requestedContentParent property of the context parameter + is a Loader. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is + set to non-null and has some values which are not Strings. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the IFilePromise object passed as parameter is null + + ArgumentErrorArgumentErrorpromiseflash.desktop:IFilePromiseA IFilePromise object. The data source of the object can be + any of the file formats supported by the Loader class: SWF, GIF, JPEG, or PNG. + + contextflash.system:LoaderContextnullA LoaderContext object. Only the applicationDomain property + of the LoaderContext object applies; the checkPolicyFile and securityDomain + properties of the LoaderContext object do not apply. + +

If the context parameter is not + specified or refers to a null object, the content is loaded into the current security domain— a + process referred to as "import loading" in Flash Player security documentation. Specifically, + if the loading SWF file trusts the remote SWF by incorporating the remote SWF into its code, + then the loading SWF can import it directly into its own security domain.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
+ Loads an IFilePromise instance. + +

The loadFilePromise method takes an IFilePromise object and + loads the binary data. If the data is a progressive stream, such as a video wait for the "init" + or progress events before accessing the properties of the loaded object. Otherwise, wait for + the complete event to make sure that the data is fully loaded.

+ +

When you use this method, consider the Flash Player security model, + which is described in the Loader class description.

+ +
MediaPromiseCameraRoll.browseForImage()CameraUIasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a + flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws + an error. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the operation is + complete. The complete event is always dispatched after the init event. + + Dispatched by the contentLoaderInfo object when the operation is + complete.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods + of the loaded data are accessible. The init event always precedes the complete + event. + + Dispatched by the contentLoaderInfo object when the properties and methods + of the loaded data are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when the runtime cannot parse + the data in the data source or if the data source stream is not readable. + + Dispatched by the contentLoaderInfo object when the runtime cannot parse + the data in the data source or if the data source stream is not readable.openflash.events:EventDispatched by the contentLoaderInfo object when the operation starts. + + Dispatched by the contentLoaderInfo object when the operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is transfered in memory. + + Dispatched by the contentLoaderInfo object as data is transfered in memory.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. + + Dispatched by the contentLoaderInfo object when a loaded object is removed.
load + Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of + this Loader object.The digest property of the request object is not + null. You should only set the digest property of a URLRequest object + when calling the URLLoader.load() method when loading a SWZ file (an Adobe + platform component). + + IOErrorflash.errors:IOErrorThe value of LoaderContext.securityDomain must be either null + or SecurityDomain.currentDomain. This reflects the fact that you can only + place the loaded media in its natural security sandbox or your own (the latter requires a + policy file). + + SecurityErrorSecurityErrorLocal SWF files may not set LoaderContext.securityDomain to anything + other than null. It is not permitted to import non-local media into a local + sandbox, or to place other local media in anything other than its natural sandbox. + + SecurityErrorSecurityError You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorIf the applicationDomain or securityDomain + properties of the context parameter are from a disallowed domain. + + SecurityErrorSecurityErrorIf a local SWF file is attempting to use the securityDomain property + of the context parameter. + + SecurityErrorSecurityErrorIf the requestedContentParent property of the context parameter + is a Loader. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the LoaderContext.parameters parameter is + set to non-null and has some values which are not Strings. + + IllegalOperationErrorflash.errors:IllegalOperationErrorrequestflash.net:URLRequest The absolute or relative URL of the SWF, JPEG, GIF, or PNG file to be loaded. A + relative path must be relative to the main SWF file. Absolute URLs must include the + protocol reference, such as http:// or file:///. Filenames cannot include disk drive + specifications. + + contextflash.system:LoaderContextnullA LoaderContext object, which has properties that define the following: + +
  • Whether or not to check for the existence of a policy file + upon loading the object
  • The ApplicationDomain for the loaded object
  • The SecurityDomain for the loaded object
  • The ImageDecodingPolicy for the loaded image object
+

If the context parameter is not specified or refers to a null object, + the loaded content remains in its own security domain.

+ +

For complete details, see the description of the properties in the + LoaderContext class.

+ +
Loads a SWF file or image file into a DisplayObject that is a child of this Loader instance. + +
+ Loads a SWF, JPEG, progressive JPEG, unanimated GIF, or PNG file into an object that is a child of + this Loader object. If you load an animated GIF file, only the first frame is displayed. + As the Loader object can contain only a single child, issuing a subsequent load() + request terminates the previous request, if still pending, and commences a new load. + +

Note: + In AIR 1.5 and Flash Player 10, the maximum size for a loaded image is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an loaded image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation + is 2,880 pixels in height and 2,880 pixels in width.

+ +

A SWF file or image loaded into a Loader object inherits the position, rotation, and scale + properties of the parent display objects of the Loader object.

+ +

Use the unload() method to remove movies or images loaded with this + method, or to cancel a load operation that is in progress.

+ +

You can prevent a SWF file from using this method by setting the allowNetworking + parameter of the the object and embed tags in the HTML + page that contains the SWF content.

+ +

When you use this method, consider the Flash Player security model, + which is described in the Loader class description.

+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standard). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
contentLoaderInfoflash.net.URLRequestflash.display.DisplayObjectflash.display.Loader.unload()flash.display.LoaderInfoflash.system.LoaderContextasyncErrorflash.events:AsyncErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer. This could happen if the loaded content is a + flash.display.AVM1Movie or if the addChild() call to the requestedContentParent throws + an error. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and it is not possible to add the + loaded content as a child to the specified DisplayObjectContainer.completeflash.events:EventDispatched by the contentLoaderInfo object when the file has + completed loading. The complete event is always dispatched after the init event. + + Dispatched by the contentLoaderInfo object when the file has + completed loading.httpStatusflash.events:HTTPStatusEventDispatched by the contentLoaderInfo object when a network + request is made over HTTP and Flash Player can detect the HTTP status code. + + Dispatched by the contentLoaderInfo object when a network + request is made over HTTP and Flash Player can detect the HTTP status code.initflash.events:EventDispatched by the contentLoaderInfo object when the properties and methods + of the loaded SWF file are accessible. The init event always precedes the complete + event. + + Dispatched by the contentLoaderInfo object when the properties and methods + of the loaded SWF file are accessible.ioErrorflash.events:IOErrorEventDispatched by the contentLoaderInfo object when an input or output + error occurs that causes a load operation to fail. + + Dispatched by the contentLoaderInfo object when an input or output + error occurs that causes a load operation to fail.openflash.events:EventDispatched by the contentLoaderInfo object when the loading operation starts. + + Dispatched by the contentLoaderInfo object when the loading operation starts.progressflash.events:ProgressEventDispatched by the contentLoaderInfo object as data is received + while load operation progresses. + + Dispatched by the contentLoaderInfo object as data is received + while load operation progresses.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if a SWF file + in the local-with-filesystem sandbox attempts to load content in the local-with-networking sandbox, or vice versa. + + Dispatched by the contentLoaderInfo object if a SWF file + in the local-with-filesystem sandbox attempts to load content in the local-with-networking sandbox, or vice versa.securityErrorflash.events:SecurityErrorEventDispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF. + + Dispatched by the contentLoaderInfo object if the + LoaderContext.requestedContentParent property has been specified and the security sandbox + of the LoaderContext.requestedContentParent does not have access to the loaded SWF.unloadflash.events:EventDispatched by the contentLoaderInfo object when a loaded object is removed. + + Dispatched by the contentLoaderInfo object when a loaded object is removed.
unloadAndStop + Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files.gcBooleantrueProvides a hint to the garbage collector to run on the child SWF objects (true) or not (false). + If you are unloading many objects asynchronously, setting the gc paramter to false might improve + application performance. However, if the parameter is set to + false, media and display objects of the child SWF file might persist in memory after running the + unloadAndStop() command. + + + Attempts to unload child SWF file contents and stops the execution of commands from loaded SWF files. + This method attempts to unload SWF files + that were loaded using Loader.load() or Loader.loadBytes() by removing references to EventDispatcher, + NetConnection, Timer, Sound, or Video objects of the child SWF file. As a result, the following occurs for the child SWF file + and the child SWF file's display list: +
  • Sounds are stopped.
  • Stage event listeners are removed.
  • Event listeners for enterFrame, frameConstructed, exitFrame, + activate and deactivate are removed.
  • Timers are stopped.
  • Camera and Microphone instances are detached
  • Movie clips are stopped.
+
flash.display.DisplayObjectflash.display.Loader.load()
unload + Removes a child of this Loader object that was loaded by using the load() method. + Removes a child of this Loader object that was loaded by using the load() method. + The property of the associated LoaderInfo object is reset to null. + The child is not necessarily destroyed because other objects might have references to it; however, + it is no longer a child of the Loader object. + +

As a best practice, before you unload a child SWF file, you should explicitly + close any streams in the child SWF file's objects, such as LocalConnection, NetConnection, + NetStream, and Sound objects. Otherwise, audio in the child SWF file might continue to play, even + though the child SWF file was unloaded. To close streams in the child SWF file, add an event listener + to the child that listens for the unload event. When the parent calls + Loader.unload(), the unload event is dispatched to the child. + The following code shows how you might do this:

+
+function closeAllStreams(evt:Event) { 
+    myNetStream.close();
+    mySound.close();
+    myNetConnection.close();
+    myLocalConnection.close();
+}
+
+myMovieClip.loaderInfo.addEventListener(Event.UNLOAD, closeAllStreams);
+ +
Loader.load()flash.media.Sound.close()flash.net.LocalConnection.close()flash.net.NetConnection.close()flash.net.NetStream.close()delete operator
contentLoaderInfo + Returns a LoaderInfo object corresponding to the object being loaded.flash.display:LoaderInfo + Returns a LoaderInfo object corresponding to the object being loaded. LoaderInfo objects + are shared between the Loader object and the loaded content object. The LoaderInfo object + supplies loading progress information and statistics about the loaded file. + +

Events related to the load are dispatched by the LoaderInfo object referenced by the + contentLoaderInfo property of the Loader object. The contentLoaderInfo + property is set to a valid LoaderInfo object, even before the content is loaded, so that you can add + event listeners to the object prior to the load.

+ +

To detect uncaught errors that happen in a loaded SWF, use the + Loader.uncaughtErrorEvents property, not the + Loader.contentLoaderInfo.uncaughtErrorEvents property.

+ +
The following example shows how you can load and position an image in ActionScript 3.0 using the Loader class and the complete event on the Loader object's contentLoaderInfo property. + Example provided by + ActionScriptExamples.com. + +var url:String = "http://www.helpexamples.com/flash/images/image2.jpg"; +var urlRequest:URLRequest = new URLRequest(url); +var loader:Loader = new Loader(); +loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete); +loader.load(urlRequest); +addChild(loader); + +function loader_complete(evt:Event):void { + var target_mc:Loader = evt.currentTarget.loader as Loader; + target_mc.x = (stage.stageWidth - target_mc.width) / 2; + target_mc.y = (stage.stageHeight - target_mc.height) / 2; +} + +
flash.display.LoaderInfo
content + Contains the root display object of the SWF file or image (JPG, PNG, or GIF) + file that was loaded by using the load() or loadBytes() methods.flash.display:DisplayObjectThe loaded SWF file or image file belongs to a security + sandbox to which you do not have access. For a loaded SWF file, you can avoid this situation by having + the file call the Security.allowDomain() method or by having the loading file specify a + loaderContext parameter with its securityDomain property set to + SecurityDomain.currentDomain when you call the load() or + loadBytes() method. + + SecurityErrorSecurityError + Contains the root display object of the SWF file or image (JPG, PNG, or GIF) + file that was loaded by using the load() or loadBytes() methods. + + flash.display.DisplayObjectflash.display.Loader.load()uncaughtErrorEvents + An object that dispatches an uncaughtError event when an unhandled error + occurs in the SWF that's loaded by this Loader object.flash.events:UncaughtErrorEvents + An object that dispatches an uncaughtError event when an unhandled error + occurs in the SWF that's loaded by this Loader object. + An uncaught error happens when an error is + thrown outside of any try..catch blocks or when an ErrorEvent + object is dispatched with no registered listeners. + +

Note that a Loader object's uncaughtErrorEvents property + dispatches events that bubble through it, not events that it dispatches directly. + It never dispatches an uncaughtErrorEvent in the target phase. It only + dispatches the event in the capture and bubbling phases. To detect an uncaught error + in the current SWF (the SWF in which the Loader object + is defined) use the LoaderInfo.uncaughtErrorEvents property instead.

+ +

If the content loaded by the Loader object is an AVM1 (ActionScript 2) SWF file, + uncaught errors in the AVM1 SWF file do not result in an uncaughtError + event.

+ +
The following example demonstrates the use of an uncaught error event + handler to detect uncaught errors in a loaded SWF. The example defines + an uncaughtError event handler to detect uncaught errors. + +

In the constructor, the code creates a Loader object and registers a listener for + the uncaughtError event dispatched by the Loader object's + uncaughtErrorEvents property.

+ +

In the uncaughtErrorHandler() method, the code checks the data type of + the error property and responds accordingly.

+ +package +{ + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.ErrorEvent; + import flash.events.UncaughtErrorEvent; + import flash.net.URLRequest; + + public class LoaderUncaughtErrorEventExample extends Sprite + { + private var ldr:Loader; + + public function LoaderUncaughtErrorEventExample() + { + ldr = new Loader(); + ldr.load(new URLRequest("child.swf")); + ldr.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + } +} +
UncaughtErrorEventLoaderInfo.uncaughtErrorEvents
NativeMenuItem + The NativeMenuItem class represents a single item in a menu.flash.events:EventDispatcher + The NativeMenuItem class represents a single item in a menu. + +

A menu item can be a command, a submenu, or a separator line:

+ +
  • To create a command item, call the NativeMenuItem constructor, passing in a + string for the label and false for the isSeparator + parameter.
  • To create a submenu, create a command item for the parent menu and + assign the NativeMenu object of the submenu to the item's submenu + property. You can also call the addSubmenu() method of the + parent NativeMenu object to create the item and set the submenu + property at the same time.
  • To create a separator, call the NativeMenuItem constructor, passing in an empty + string for the label and true for the isSeparator + parameter.
+ +

Listen for select events on an item or a parent menu to detect when a + menu command is selected. Neither submenus nor separators dispatch + select events. Listen for preparing events to determine when + a menu item is about to be displayed or activated through a key equivalent.

+ +
flash.display.NativeMenuflash.display.NativeMenu.addSubmenu()preparing + Dispatched by this NativeMenuItem object when its key equivalent is pressed and immediately before the containing menu is displayed.flash.events.Event.PREPARINGflash.events.Event + Dispatched by this NativeMenuItem object when its key equivalent is pressed and immediately before the containing menu is displayed. + +

Listen to this event to update the item either before the containing menu is displayed, or when its key + equivalent is pressed by the user. The preparing event is dispatched before the key equivalent + is fully evaluated. You can enable, disable, or remove the item from the menu in the preparing event handler + and those changes will be in effect when the key equivalent is processed. For example, if you remove or disable this + menu item, then the sequence of events is effectively canceled + and no select event is dispatched. + A preparing event is also dispatched by the other items in a menu.

+ +

The preparing event supersedes the displaying event and provides additional functionality. Listen for the + preparing event or the displaying event, but not both.

+ +
displaying + Dispatched by this NativeMenuItem object immediately before the + menu containing the item is displayed.flash.events.Event.DISPLAYINGflash.events.Event + Dispatched by this NativeMenuItem object immediately before the + menu containing the item is displayed. + +

The preparing event supersedes the displaying event and provides additional functionality. Listen for the + preparing event or the displaying event, but not both.

+ +
select + Dispatched whenever a menu item is selected by the user.flash.events.Event.SELECTflash.events.Event + Dispatched whenever a menu item is selected by the user. + +

A select event bubbles from this item to its containing menu and on up + through the parent menu chain to the root menu object. The target + property of the event object references this NativeMenuItem object; + the currentTarget property references the dispatching + object (either this NativeMenuItem or an ancestral NativeMenu object).

+ +

Note: If the window containing the menu is in fullscreen mode + (stage.displayState == StageDisplayState.FULL_SCREEN), + the NativeMenuItem object does not dispatch a select event + when the user enters a keyboard equivalent for a menu item.

+ +
NativeMenuItem + Creates a new NativeMenuItem object.labelStringThe display label for the item, or an empty string for separators. + isSeparatorBooleanfalseSet to true to create a separator; set to + false otherwise. + + + Creates a new NativeMenuItem object. + +

To create a menu command, set the label parameter to a + string containing the display label and set isSeparator + to false.

+ +

To create a submenu command, create a command item and then assign the + NativeMenu object for the submenu to the item's submenu + property. Add the item to the parent menu.

+ +

To create a separator, set the label parameter to an empty + string and set isSeparator to true.

+ +

Add and remove items from a menu using the NativeMenu addItem() + and removeItem() methods.

+ +
flash.display.NativeMenu.addSubmenu()
clone + Creates a copy of the NativeMenuItem object.flash.display:NativeMenuItem + Creates a copy of the NativeMenuItem object. + + toString + Returns a string containing all the properties of the NativeMenuItem object.A string containing all the properties of the Event object. + String + Returns a string containing all the properties of the NativeMenuItem object. + + checked + Controls whether this menu item displays a checkmark.Boolean + Controls whether this menu item displays a checkmark. + + data + An arbitrary data object associated with this menu item.Object + An arbitrary data object associated with this menu item. + +

You can assign any object to this property. The assigned object is + not used by the menu system, but is available to event handling code + (through the target property of the event object). + By default, the value of this property is null.

+ +
enabled + Controls whether this menu item is enabled.Boolean + Controls whether this menu item is enabled. + + isSeparator + Reports whether this item is a menu separator line.Boolean + Reports whether this item is a menu separator line. + +

Create a separator line by setting the isSeparator + parameter in the NativeMenuItem constructor to true.

+ +
keyEquivalentModifiers + The array of key codes for the key equivalent modifiers.Array + The array of key codes for the key equivalent modifiers. + +

Use the constants defined in the Keyboard class to specify the + modifier key codes. Valid modifier keys include:

+
  • Keyboard.ALTERNATE
  • Keyboard.COMMAND
  • Keyboard.CONTROL
+ +

If you do not assign any modifiers, then by default the Keyboard.CONTROL key is + assigned on Windows or Linux and the Keyboard.COMMAND key is assigned on Mac OS X. If you + do not want the key equivalent to include these modifiers, set this property to an empty array.

+ +

If you assign an uppercase letter to the keyEquivalent property, the Shift key is + used as a modifier automatically. Setting keyEquivalentModifier to an empty array + does not remove the Shift key as a modifier.

+ +
flash.ui.Keyboard
keyEquivalent + The key equivalent for this menu item.String + The key equivalent for this menu item. + +

Set the keyEquivalent with a lowercase letter to assign + a shortcut without a Shift-key modifier. Set with an uppercase letter + to assign a shortcut with the Shift-key modifier.

+ +

By default, a key equivalent modifier (Ctrl on Windows or Linux and + Command on Mac OS X) is included as part of the key equivalent. + If you want the key equivalent to be a key with no modifier, + set the keyEquivalentModifiers property to an + empty array.

+ +
label + The display string of this menu item.String + The display string of this menu item. + + menu + The menu that contains this item.flash.display:NativeMenu + The menu that contains this item. + + mnemonicIndex + The position of the mnemonic character in the menu item label.int + The position of the mnemonic character in the menu item label. + +

The character at the specified position is the mnemonic + character for the menu item. The index is zero-based, so the first + character has an index of 0.

+ +

This property is ignored on operating systems that do not use + menu mnemonics.

+ +
name + The name of this menu item.String + The name of this menu item. + +

The name value is not displayed and can be used as a + locale-independent identifier. A name is not assigned automatically.

+ +
submenu + The submenu associated with this menu item.flash.display:NativeMenu + The submenu associated with this menu item. + +

Assigning a NativeMenu object to this property changes the + appearance and behavior of the menu item. A submenu item displays + the submenu icon and no longer dispatches select events.

+ +

Note: Adding a menu as a submenu of itself (in a circular reference) + can cause an application to hang.

+ +
flash.display.NativeMenu.addSubmenu()
NativeMenu + The NativeMenu class contains methods and properties for defining native menus.flash.events:EventDispatcher + The NativeMenu class contains methods and properties for defining native menus. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the NativeMenu.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

A native menu is a menu that is controlled and drawn by the operating system rather than by your application. + AIR supports the following types of native menus:

+ +
  • Application menus are supported on OS X. Use the NativeApplication.supportsMenu property to test whether + application menus are supported on the host operating system. An application menu is displayed on the Menu bar at the top of the + Mac desktop. OS X provides a default menu for every application, but many of the menu commands are not functional. You can add + event listeners to the default items, replace individual menus and items, or even replace the default menu entirely. + Access the application menu object using the NativeApplication menu property.
  • Window menus are supported on Windows and Linux. Use the NativeWindow.supportsMenu property to + test whether window menus are supported on the host operating system. A window menu is displayed below the window title bar. The area + occupied by the menu is not part of the window stage. Applications cannot draw into this area. Assign a menu to a window using the + NativeWindow menu property.
  • Dock icon menus are supported on OS X. Use the NativeApplication.supportsDockIcon property to test whether + dock icons are supported on the host operating system. Items in a dock icon menu are displayed above the default items provided by + the operating system. The default items cannot be accessed by application code. Assign a menu to the menu property of + the application's DockIcon object.
  • System tray icon menus are supported on Windows and most Linux operating systems. Use the + NativeApplication.supportsSystemTrayIcon property to test whether system tray icons are supported on the host + operating system. A system tray icon menu is displayed in response to a right-click on the icon, in much the same fashion as + a context menu. Assign a menu to the menu property of the application's SystemTrayIcon object.
  • Context menus are supported on all operating systems. Context menus are displayed in response to a user interface event, + such as a right-click or a command-click on an InteractiveObject displayed in the application. The UI mechanism for showing the menu + varies by host operating system and hardware. Assign a menu to the contextMenu property of an + InteractiveObject. In AIR, a context menu can be created with either the NativeMenu class or the ContextMenu class. In + Flash Player, only the ContextMenu class can be used. ContextMenus in AIR do not have built-in items; a default context menu is + not displayed.
  • Pop-up menus are supported on all operating systems. Pop-up menus are functionally the same as context menus, but + are displayed using the menu display() method rather than as a response to a user interface event. A pop-up + menu is not attached to any other object. Simply create the native menu and call the display() method.
+ +

A menu object contains menu items. A menu item can represent a command, a submenu, or a separator line. + Add menu items to a menu using the addItem() or addItemAt() method. The display order of the menu items + matches the order of the items in the menu's items array.

+ +

To create a submenu, add a menu item to the parent menu object. Assign the menu object representing + the submenu to the submenu property of the matching menu item in the parent menu.

+ +

Note: The root menu of window and application menus must contain only submenu items; items + that do not represent submenus may not be displayed and are contrary to user expectation for + these types of menus.

+ +

Menus dispatch select events when a command item in the menu or one of its + submenus is selected. (Submenu and separator items are not selectable.) The + target property of the event object references the + selected item.

+ +

Menus dispatch preparing events just before the menu is displayed and when a key equivalent attached + to one of the items in the menu is pressed. You + can use this event to update the contents of the menu based on the current + state of the application.

+ +

Note: If you are using the Flex Framework, consider using the FlexNativeMenu class. + It is typically easier to define menus declaratively in MXML than it is to write ActionScript code to create the menu + structure item-by-item.

+ + + +
flash.display.InteractiveObject.contextMenuflash.display.NativeMenuItemflash.display.NativeWindow.menuflash.desktop.DockIconflash.desktop.SystemTrayIconflash.desktop.NativeApplication.menuflash.desktop.NativeApplication.iconmx.controls.FlexNativeMenupreparing + Dispatched by the NativeMenu object when a key equivalent is pressed and immediately before the menu is displayed.flash.events.Event.PREPARINGflash.events.Event + Dispatched by the NativeMenu object when a key equivalent is pressed and immediately before the menu is displayed. + +

Listen to this event to update the menu either before it is displayed, or when a key + equivalent is pressed by the user. The preparing event is dispatched before the key equivalent + is fully evaluated. You can enable, disable, add, or remove items from the menu in the preparing event handler + and those changes will be in effect when the key equivalent is processed. For example, if you remove or disable the + menu item assigned to the triggering key equivalent, then the sequence of events is effectively canceled + and no select event is dispatched. + A preparing event is also dispatched by the items in a menu.

+ +

The preparing event supersedes the displaying event and provides additional functionality. Listen for the + preparing event or the displaying event, but not both.

+ +
displaying + Dispatched by this NativeMenu object immediately before the + menu is displayed.flash.events.Event.DISPLAYINGflash.events.Event + Dispatched by this NativeMenu object immediately before the + menu is displayed. + +

Listen to this event to update the menu before it is displayed. + A displaying event is also dispatched by the items in a menu.

+ +

The preparing event supersedes the displaying event and provides additional functionality. Listen for the + preparing event or the displaying event, but not both.

+ +

Note: On Mac OS X, prior to AIR 2.6, menus and menu items dispatched a displaying event when the user pressed a key + equivalent. (This event was not dispatched for key equivalent interaction on other operating systems.) As of AIR 2.6, displaying + events are no longer dispatched when the user presses a key equivalent. Use the preparing event instead.

+ +
select + Dispatched by this NativeMenu object when one of its menu items or an item + in one of its descendant submenus is selected.flash.events.Event.SELECTflash.events.Event + Dispatched by this NativeMenu object when one of its menu items or an item + in one of its descendant submenus is selected. + +

A select event bubbles from a menu item to its containing menu and on up + through the parent menu chain to the root menu object. The target + property of the event object references the selected NativeMenuItem object; + the currentTarget property references this NativeMenu object.

+ +
NativeMenu + Creates a new NativeMenu object. + Creates a new NativeMenu object. + + addItemAt + Inserts a menu item at the specified position.If item is null. + ArgumentErrorArgumentErrorIf item is a member of another menu. + ArgumentErrorArgumentErrorIf the index is outside the bounds of the menu's + items array. + + RangeErrorRangeErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to insert. + indexintThe (zero-based) position in menu + at which to insert the menu item. + +

Note: Adding an item to a menu can cause an application to hang if the item's + submenu is set to the menu itself (causing a circular reference).

+ +
+ Inserts a menu item at the specified position. The position is indexed from the top. + Set the index parameter to zero to insert the item at the top of the menu. + All types of menus: window, application, system tray icon, dock icon, context, and pop-up, + index the menu position from the top. + +
addItem + Adds a menu item at the bottom of the menu.If item is null. + ArgumentErrorArgumentErrorIf item is a member of another menu. + ArgumentErrorArgumentErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to add at the bottom of the menu. + + Adds a menu item at the bottom of the menu. + +

When creating a context menu, you can add either NativeMenuItem or + ContextMenuItem objects. However, it is advisable to use only one type of object in a context + menu so that all items in the menu have the same properties.

+ +

Note: Adding an item to a menu can cause an application to hang if the item's + submenu is set to the menu itself (causing a circular reference).

+ +
addSubmenuAt + Adds a submenu to the menu by inserting a new menu item at the + specified position.The NativeMenuItem object created for the submenu. + flash.display:NativeMenuItemsubmenuflash.display:NativeMenuThe NativeMenu object that defines the submenu to be added. + indexintThe position in the items array of this + menu at which to insert the menu item to be added. + labelStringThe display label for the menu item to be added. + + + Adds a submenu to the menu by inserting a new menu item at the + specified position. + +

Calling the addSubMenuAt() method is equivalent to creating a new menu + item, inserting it at the desired position in the menu, and assigning + a NativeMenu object to the item's submenu property.

+ +

Note: Adding a menu as a submenu of itself (in a circular reference) + can cause an application to hang.

+ +
addSubmenu + Adds a submenu to the menu by inserting a new menu item.The NativeMenuItem object created for the submenu. + flash.display:NativeMenuItemsubmenuflash.display:NativeMenuThe NativeMenu object that defines the submenu to be added. + labelStringThe display label for the menu item to be added. + + + Adds a submenu to the menu by inserting a new menu item. + +

Calling the addSubMenu() method is equivalent to creating a new menu + item, adding it to the menu, and assigning a NativeMenu object to the + item's submenu property.

+ +

Note: Adding a menu as a submenu of itself (in a circular reference) + can cause an application to hang.

+ +
clone + + Creates a copy of the menu and all items.flash.display:NativeMenu + + Creates a copy of the menu and all items. + + containsItem + Reports whether this menu contains the specified menu item.true if item is in this menu. + + Booleanitemflash.display:NativeMenuItemThe NativeMenuItem object to look up. + + + Reports whether this menu contains the specified menu item. + + display + Pops up this menu at the specified location.stageflash.display:StageThe Stage object on which to display this menu. + + stageXNumberThe number of horizontal pixels, relative to the origin + of stage, at which to display this menu. + + stageYNumberThe number of vertical pixels, relative to the origin + of stage, at which to display this menu. + + + Pops up this menu at the specified location. + + getItemAt + Gets the menu item at the specified index.If index is outside the bounds of the menu's + items array. + + RangeErrorRangeErrorThe NativeMenuItem object at the specified position in the menu. + + flash.display:NativeMenuItemindexintThe (zero-based) position of the item to return. + + + Gets the menu item at the specified index. + + getItemByName + Gets the menu item with the specified name.The NativeMenuItem object with the specified name or + null, if no such item exists in the menu. + + flash.display:NativeMenuItemnameStringThe string to look up. + + Gets the menu item with the specified name. + +

Note: The name property of menu items is not assigned by + default.

+ +
getItemIndex + Gets the position of the specified item.The (zero-based) position of the specified item in this menu + or -1, if the item is not in this menu. + + intitemflash.display:NativeMenuItemThe NativeMenuItem object to look up. + + + Gets the position of the specified item. + + removeAllItems + Removes all items from the menu. + Removes all items from the menu. + + + + removeItemAt + Removes and returns the menu item at the specified index.If index is outside the bounds of + this menu's items array. + + RangeErrorRangeErrorThe NativeMenuItem object removed. + + flash.display:NativeMenuItemindexintThe (zero-based) position of the item to remove. + + + Removes and returns the menu item at the specified index. + + removeItem + Removes the specified menu item.If the item is not in this menu + + RangeErrorRangeErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe NativeMenuItem object to remove from this menu. + + + Removes the specified menu item. + + setItemIndex + Moves a menu item to the specified position.If index is outside the bounds of the + menu's items array. + + RangeErrorRangeErroritemflash.display:NativeMenuItemThe NativeMenuItem object to move. + indexintThe (zero-based) position in the menu to which to move the + item. + + + Moves a menu item to the specified position. If the item is not already in the menu, + calling this method adds the item to the menu. + + isSupported + Indicates whether any form of native menu is supported on the client system.Boolean + Indicates whether any form of native menu is supported on the client system. + + flash.display.NativeWindow.supportsMenuflash.desktop.NativeApplicationitems + The array of NativeMenuItem objects in this menu.Array + The array of NativeMenuItem objects in this menu. + +

The array is sorted in display order.

+ +

Note: This property is read-only in AIR 1.0. It became read/write in AIR 1.1.

+ +
numItems + The number of NativeMenuItem objects in this menu.int + The number of NativeMenuItem objects in this menu. + + parent + The parent menu.flash.display:NativeMenu + The parent menu. + +

The parent of the root (top-level) menu object is + null.

+ +
StageOrientation + The StageOrientation class defines constants enumerating the possible orientations of the stage and the device.The StageOrientation class provides values for the orientation property of the Stage + class and for other properties and methods where Stage orientation is referenced. + + Object + The StageOrientation class defines constants enumerating the possible orientations of the stage and the device. + + flash.display.Stage.orientationflash.display.Stage.setOrientation()flash.display.Stage.deviceOrientationflash.events.StageOrientationEvent.afterOrientationflash.events.StageOrientationEvent.beforeOrientationDEFAULT + Specifies that the stage is currently in the default orientation of the device (right-side up).defaultString + Specifies that the stage is currently in the default orientation of the device (right-side up). + + ROTATED_LEFT + Specifies that the stage is currently rotated left relative to the default orientation.rotatedLeftString + Specifies that the stage is currently rotated left relative to the default orientation. + +

Note: When the orientation of the device is rotated left, the orientation of the + stage must be rotated right in order to remain upright.

+ +
ROTATED_RIGHT + Specifies that the stage is currently rotated right relative to the default orientation.rotatedRightString + Specifies that the stage is currently rotated right relative to the default orientation. + +

Note: When the orientation of the device is rotated right, the orientation of the + stage must be rotated left in order to remain upright.

+ +
UNKNOWN + Specifies that the device has not determined an orientation.unknownString + Specifies that the device has not determined an orientation. This state can occur when + the device is lying flat on a table and also while the application is initializing. + + UPSIDE_DOWN + Specifies that the stage is currently upside down relative to the default orientation.upsideDownString + Specifies that the stage is currently upside down relative to the default orientation. + +
DisplayObjectContainer +The DisplayObjectContainer class is the base class for all objects that can serve as display object containers on +the display list.The abstract base class for all display objects that can contain child objects. + + flash.display:InteractiveObject +The DisplayObjectContainer class is the base class for all objects that can serve as display object containers on +the display list. The display list manages all objects displayed in the Flash runtimes. + Use the DisplayObjectContainer class to arrange the display objects in the display list. + Each DisplayObjectContainer object has its own child list for organizing the z-order of the objects. + The z-order is the front-to-back order that determines which object is drawn in front, which is behind, + and so on. + +

DisplayObject is an abstract base class; therefore, you cannot call DisplayObject directly. Invoking + new DisplayObject() throws an ArgumentError exception.

+ + The DisplayObjectContainer class is an abstract base class for all objects that can contain child objects. + It cannot be instantiated directly; calling the new DisplayObjectContainer() constructor + throws an ArgumentError exception. + +

For more information, see the "Display Programming" chapter of the ActionScript 3.0 Developer's Guide.

+ +
The following example uses the class DisplayObjectContainerExample to + create five orange squares in succession. This task is accomplished by performing the following steps: + +
  1. The constructor calls the configureAssets() method.
  2. The configureAssets() method creates child and + lastChild Sprite objects.
  3. A for loop creates the five orange squares and positions + them one after another.
  4. Each time a CustomSprite object is created, its constructor calls the draw() + method of the CustomSprite object, which creates a 50-by-50-pixel square + by calling the beginFill(), drawRect(), and endFill() + methods of the Graphics class. The addChild() method adds each square to the + display list.
+ + +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + + public class DisplayObjectContainerExample extends Sprite { + private var gutter:uint = 5; + private var childCount:uint = 5; + + public function DisplayObjectContainerExample() { + configureAssets(); + } + + private function configureAssets():void { + var child:Sprite = new CustomSprite(); + var lastChild:Sprite = child; + for (var i:uint = 1; i <= childCount; i++) { + child = new CustomSprite(); + child.x = lastChild.x + lastChild.width + gutter; + addChild(child); + lastChild = child; + } + } + } +} + +import flash.display.Sprite; + +class CustomSprite extends Sprite { + private var size:uint = 50; + private var bgColor:uint = 0xFFCC00; + + public function CustomSprite() { + draw(size, size); + } + + private function draw(w:uint, h:uint):void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, w, h); + graphics.endFill(); + } +} +
flash.display.DisplayObjectDisplayObjectContainer + Calling the new DisplayObjectContainer() constructor throws an + ArgumentError exception. + Calling the new DisplayObjectContainer() constructor throws an + ArgumentError exception. You can, however, call constructors for + the following subclasses of DisplayObjectContainer: + +
  • new Loader()
  • new Sprite()
  • new MovieClip()
+ +
addChildAt + Adds a child DisplayObject instance to this DisplayObjectContainer + instance.Throws if the index position does not exist in the child list. + RangeErrorRangeErrorThrows if the child is the same as the parent. Also throws if + the caller is a child (or grandchild etc.) of the child being added. + ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the + child parameter. + + flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this + DisplayObjectContainer instance. + + indexintThe index position to which the child is added. If you specify a + currently occupied index position, the child object that exists at that position and all + higher positions are moved up one position in the child list. + + Adds a child object to this DisplayObjectContainer instance. + + + Adds a child DisplayObject instance to this DisplayObjectContainer + instance. The child is added + at the index position specified. An index of 0 represents the back (bottom) + of the display list for this DisplayObjectContainer object. + +

For example, the following example shows three display objects, labeled a, b, and c, at + index positions 0, 2, and 1, respectively:

+ +

+ +

If you add a child object that already has a different display object container as + a parent, the object is removed from the child list of the other display object container.

+ +
The following example creates a container display object container and + adds a display objects circle1 to its display list. Then, by calling + container.addChildAt(circle2, 0), it adds the circle2 object to index position + zero (the back), and moves the circle1 object to index position 1: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); + +var circle1:Sprite = new Sprite(); +var circle2:Sprite = new Sprite(); + +container.addChild(circle1); +container.addChildAt(circle2, 0); + +trace(container.getChildAt(0) == circle2); // true +trace(container.getChildAt(1) == circle1); // true +
addChild()addedflash.events:EventDispatched when a display object is added to the display list. + Dispatched when a display object is added to the display list.
addChild + Adds a child DisplayObject instance to this DisplayObjectContainer instance.Throws if the child is the same as the parent. Also throws if + the caller is a child (or grandchild etc.) of the child being added. + ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the + child parameter. + + flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. + + Adds a child object to this DisplayObjectContainer instance. + + + Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added + to the front (top) of all other children in this DisplayObjectContainer instance. (To add a child to a + specific index position, use the addChildAt() method.) + +

If you add a child object that already has a different display object container as + a parent, the object is removed from the child list of the other display object container.

+

Note: The command stage.addChild() can cause problems with a published SWF file, + including security problems and conflicts with other loaded SWF files. There is only one Stage within a Flash runtime instance, + no matter how many SWF files you load into the runtime. So, generally, objects + should not be added to the Stage, directly, at all. The only object the Stage should + contain is the root object. Create a DisplayObjectContainer to contain all of the items on the + display list. Then, if necessary, add that DisplayObjectContainer instance to the Stage.

+ +
The following example sets up two Sprite objects named container1 and + container2. A Sprite is a type of display object container. The example calls the + addChild() method to set up the display hierarchy: container1 is a child of + container2, and two other display objects, circle1 and circle2, + are children of container1. The calls to the trace() method show the number + of children of each object. Note that grandchildren are not included in the numChildren count: + +import flash.display.Sprite; + +var container1:Sprite = new Sprite(); +var container2:Sprite = new Sprite(); + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x00CCFF); +circle2.graphics.drawCircle(80, 40, 40); + +container2.addChild(container1); +container1.addChild(circle1); +container1.addChild(circle2); + +trace(container1.numChildren); // 2 +trace(container2.numChildren); // 1 +trace(circle1.numChildren); // 0 +trace(circle2.numChildren); // 0 +
addChildAt()addedflash.events:EventDispatched when a display object is added to the display list. + Dispatched when a display object is added to the display list.
areInaccessibleObjectsUnderPoint + Indicates whether the security restrictions + would cause any display objects to be omitted from the list returned by calling + the DisplayObjectContainer.getObjectsUnderPoint() method + with the specified point point.true if the point contains child display objects with security restrictions. + + Booleanpointflash.geom:PointThe point under which to look. + + + Indicates whether the security restrictions + would cause any display objects to be omitted from the list returned by calling + the DisplayObjectContainer.getObjectsUnderPoint() method + with the specified point point. By default, content from one domain cannot + access objects from another domain unless they are permitted to do so with a call to the + Security.allowDomain() method. For more information, related to security, + see the Flash Player Developer Center Topic: + Security. + +

The point parameter is in the coordinate space of the Stage, + which may differ from the coordinate space of the display object container (unless the + display object container is the Stage). You can use the globalToLocal() and + the localToGlobal() methods to convert points between these coordinate + spaces.

+ +
The following code creates a display object container named container. + The next block of code uses a Loader object to load a JPEG file named "test.jpg" from a remote file server. + Note that the checkPolicyFile property of the LoaderContext object used as a parameter in the + load() method is set to false. Once the file is loaded, the code calls + the loaded() method, which in turn calls container.areInaccessibleObjectsUnderPoint(), + which returns a value of true because the loaded content is assumed to be from an + inaccessible domain: + +import flash.display.Sprite; +import flash.display.Loader; +import flash.system.LoaderContext; +import flash.net.URLRequest; +import flash.events.Event; +import flash.geom.Point; + +var container:Sprite = new Sprite(); + +var urlReq:URLRequest = new URLRequest("http://localhost/RemoteFile.swf"); +var ldr:Loader = new Loader(); +var context:LoaderContext = new LoaderContext(); +context.checkPolicyFile = false; +ldr.load(urlReq, context); + +ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded); +ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, urlNotFound); + +function loaded(event:Event):void { + var pt:Point = new Point(1, 1); + trace(container.areInaccessibleObjectsUnderPoint(pt)); // true +} + +function urlNotFound(event:Event):void { + trace("The URL was not found."); +} + This example assumes that the SWF file produced by this code is loaded from a different domain + than that of the JPEG file, and that the loaded JPEG file occupies the point (1, 1). +
flash.system.Security.allowDomain()getObjectsUnderPoint()DisplayObject.globalToLocal()DisplayObject.localToGlobal()
contains + Determines whether the specified display object is a child of the DisplayObjectContainer instance or + the instance itself.true if the child object is a child of the DisplayObjectContainer + or the container itself; otherwise false. + + + Booleanchildflash.display:DisplayObjectThe child object to test. + + + Determines whether the specified display object is a child of the DisplayObjectContainer instance or + the instance itself. + The search includes the entire display list including this DisplayObjectContainer instance. Grandchildren, + great-grandchildren, and so on each return true. + + The following example sets up a number of Sprite objects and adds some to the child list + of others. (A Sprite object is a type of display object container.) The relationship between various objects is + shown by calling the contains() method: + +import flash.display.Sprite; + +var sprite1:Sprite = new Sprite(); +var sprite2:Sprite = new Sprite(); +var sprite3:Sprite = new Sprite(); +var sprite4:Sprite = new Sprite(); + +sprite1.addChild(sprite2); +sprite2.addChild(sprite3); + +trace(sprite1.contains(sprite1)); // true +trace(sprite1.contains(sprite2)); // true +trace(sprite1.contains(sprite3)); // true +trace(sprite1.contains(sprite4)); // false +getChildAt + Returns the child display object instance that exists at the specified index.Throws if the index does not exist in the child list. + RangeErrorRangeErrorThis child display object belongs to a sandbox + to which you do not have access. You can avoid this situation by having + the child movie call Security.allowDomain(). + + SecurityErrorSecurityErrorThe child display object at the specified index position. + + flash.display:DisplayObjectindexintThe index position of the child object. + + Returns the child display object instance that exists at the specified index. + + The following example creates a display object container named container + and then adds a three display objects to the child list of the container object. The calls to the + getChildAt() method then reveal the positions of the child objects: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +var sprite2:Sprite = new Sprite(); +var sprite3:Sprite = new Sprite(); + +container.addChild(sprite1); +container.addChild(sprite2); +container.addChildAt(sprite3, 0); + +trace(container.getChildAt(0) == sprite3); // true +trace(container.getChildAt(1) == sprite1); // true +trace(container.getChildAt(2) == sprite2); // true +getChildByName()getChildByName + Returns the child display object that exists with the specified name.This child display object belongs to a sandbox + to which you do not have access. You can avoid this situation by having + the child movie call the Security.allowDomain() method. + + SecurityErrorSecurityErrorThe child display object with the specified name. + + flash.display:DisplayObjectnameStringThe name of the child to return. + + + Returns the child display object that exists with the specified name. + If more that one child display object has the specified name, + the method returns the first object in the child list. + +

The getChildAt() method is faster than the + getChildByName() method. The getChildAt() method accesses + a child from a cached array, whereas the getChildByName() method + has to traverse a linked list to access a child.

+ +
The following example creates a display object container named + container and then adds two child display objects to the container. + Then, the code calls the getChildByName() and getChildIndex() + methods to return the index position of the child of the container object that + has the name "sprite1". + +import flash.display.Sprite; +import flash.display.DisplayObject; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; + +container.addChild(sprite1); +container.addChild(sprite2); + +var target:DisplayObject = container.getChildByName("sprite1"); +trace(container.getChildIndex(target)); // 0 +
getChildAt()flash.display.DisplayObject.name
getChildIndex + Returns the index position of a child DisplayObject instance.Throws if the child parameter is not a child of this object. + + ArgumentErrorArgumentErrorThe index position of the child display object to identify. + + intchildflash.display:DisplayObjectThe DisplayObject instance to identify. + + Returns the index number of a child DisplayObject instance. + + + Returns the index position of a child DisplayObject instance. + + The following example creates a display object container named + container and then adds two child display objects to the container. + Then, the code calls the getChildByName() and getChildIndex() + methods to return the index position of the child of the container object that + has the name "sprite1". + +import flash.display.Sprite; +import flash.display.DisplayObject; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; + +container.addChild(sprite1); +container.addChild(sprite2); + +var target:DisplayObject = container.getChildByName("sprite1"); +trace(container.getChildIndex(target)); // 0 +getObjectsUnderPoint + Returns an array of objects that lie under the specified point and are children + (or grandchildren, and so on) of this DisplayObjectContainer instance.An array of objects that lie under the specified point and are children + (or grandchildren, and so on) of this DisplayObjectContainer instance. + + Arraypointflash.geom:PointThe point under which to look. + + + Returns an array of objects that lie under the specified point and are children + (or grandchildren, and so on) of this DisplayObjectContainer instance. Any child objects that + are inaccessible for security reasons are omitted from the returned array. To determine whether + this security restriction affects the returned array, call the + areInaccessibleObjectsUnderPoint() method. + +

The point parameter is in the coordinate space of the Stage, + which may differ from the coordinate space of the display object container (unless the + display object container is the Stage). You can use the globalToLocal() and + the localToGlobal() methods to convert points between these coordinate + spaces.

+ +
The following example creates a display object container named container + and then adds two overlapping child display objects to the container. Then the code calls the + getObjectsUnderPoint() twice — first using a point that touches only one object, + then using a point where the objects overlap — and the length of the return + Array shows the number of objects at each point in the container: + +import flash.display.Sprite; +import flash.geom.Point; + +var container:Sprite = new Sprite(); + +var square1:Sprite = new Sprite(); +square1.graphics.beginFill(0xFFCC00); +square1.graphics.drawRect(0, 0, 40, 40); + +var square2:Sprite = new Sprite(); +square2.graphics.beginFill(0x00CCFF); +square2.graphics.drawRect(20, 0, 30, 40); + +container.addChild(square1); +container.addChild(square2); + +var pt:Point = new Point(10, 20); +var objects:Array = container.getObjectsUnderPoint(pt); +trace(objects.length); // 1 + +pt = new Point(35, 20); +objects = container.getObjectsUnderPoint(pt); +trace(objects.length); // 2 +
areInaccessibleObjectsUnderPoint()DisplayObject.globalToLocal()DisplayObject.localToGlobal()
removeChildAt + Removes a child DisplayObject from the specified index position in the child list of + the DisplayObjectContainer.This child display object belongs to a sandbox + to which the calling object does not have access. You can avoid this situation by having + the child movie call the Security.allowDomain() method. + + SecurityErrorSecurityErrorThrows if the index does not exist in the child list. + + RangeErrorRangeErrorThe DisplayObject instance that was removed. + + flash.display:DisplayObjectindexintThe child index of the DisplayObject to remove. + + Removes a child display object, at the specified index position, from the + DisplayObjectContainer instance. + + + Removes a child DisplayObject from the specified index position in the child list of + the DisplayObjectContainer. The parent property of the removed child is set to + null, and the object is garbage collected if no other references to the child exist. The index + positions of any display objects above the child in the DisplayObjectContainer are decreased by 1. + +

The garbage collector reallocates unused memory space. When a variable or + object is no longer actively referenced or stored somewhere, the garbage collector sweeps + through and wipes out the memory space it used to occupy if no other references to it exist.

+ +
The following example creates a display object container named + container and then adds two child display objects to the container. + The code then shows that when you call the removeChildAt() method + to remove the child at the lowest index position (0), any other child object in the list + moves down one position: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; + +container.addChild(sprite1); +container.addChild(sprite2); + +trace(container.numChildren) // 2 +container.removeChildAt(0); +trace(container.numChildren) // 1 +trace(container.getChildAt(0).name); // sprite2 +
removeChild + Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance.Throws if the child parameter is not a child of this object. + + ArgumentErrorArgumentErrorThe DisplayObject instance that you pass in the + child parameter. + + flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to remove. + + Removes a child display object from the DisplayObjectContainer + instance. + + + Removes the specified child DisplayObject instance from the child list of the DisplayObjectContainer instance. + The parent property of the removed child is set to null + , and the object is garbage collected if no other + references to the child exist. The index positions of any display objects above the child in the + DisplayObjectContainer are decreased by 1. + +

The garbage collector reallocates unused memory space. When a variable + or object is no longer actively referenced or stored somewhere, the garbage collector sweeps + through and wipes out the memory space it used to occupy if no other references to it exist.

+ +
The following example creates a display object container named + container and then adds two child display objects to the container. + An event listener is added to the container object, so that when the + user clicks a child object of the container, the removeChild() method + removes the child clicked from the child list of the container: + + +import flash.display.DisplayObject; +import flash.display.Sprite; +import flash.events.MouseEvent; + +var container:Sprite = new Sprite(); +addChild(container); + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x00CCFF); +circle2.graphics.drawCircle(120, 40, 40); + +container.addChild(circle1); +container.addChild(circle2); + +container.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void { + container.removeChild(DisplayObject(event.target)); +} +
setChildIndex + Changes the position of an existing child in the display object container.Throws if the index does not exist in the child list. + RangeErrorRangeErrorThrows if the child parameter is not a child of this object. + ArgumentErrorArgumentErrorchildflash.display:DisplayObjectThe child DisplayObject instance for which you want to change + the index number. + + indexintThe resulting index number for the child display object. + + Changes the index number of an existing child. + + + Changes the position of an existing child in the display object container. + This affects the layering of child objects. For example, the following example shows three + display objects, labeled a, b, and c, at index positions 0, 1, and 2, respectively: + +

+ +

When you use the setChildIndex() method and specify an index position + that is already occupied, the only positions that change are those in between the display object's former and new position. + All others will stay the same. + If a child is moved to an index LOWER than its current index, all children in between will INCREASE by 1 for their index reference. + If a child is moved to an index HIGHER than its current index, all children in between will DECREASE by 1 for their index reference. + For example, if the display object container + in the previous example is named container, you can swap the position + of the display objects labeled a and b by calling the following code:

+ + container.setChildIndex(container.getChildAt(1), 0); + +

This code results in the following arrangement of objects:

+ +

+ +
The following example creates a display object container named + container and then adds three slightly overlapping child display + objects to the container. When the user clicks any of these objects, the + clicked() method calls the setChildIndex() + method to move the clicked object to the top-most position in the child list of + the container object: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var container:Sprite = new Sprite(); +addChild(container); + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFF0000); +circle1.graphics.drawCircle(40, 40, 40); +circle1.addEventListener(MouseEvent.CLICK, clicked); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x00FF00); +circle2.graphics.drawCircle(100, 40, 40); +circle2.addEventListener(MouseEvent.CLICK, clicked); + +var circle3:Sprite = new Sprite(); +circle3.graphics.beginFill(0x0000FF); +circle3.graphics.drawCircle(70, 80, 40); +circle3.addEventListener(MouseEvent.CLICK, clicked); + +container.addChild(circle1); +container.addChild(circle2); +container.addChild(circle3); +addChild(container); + +function clicked(event:MouseEvent):void { + var circle:Sprite = Sprite(event.target); + var topPosition:uint = container.numChildren - 1; + container.setChildIndex(circle, topPosition); +} +
addChildAt()getChildIndex()
swapChildrenAt + Swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the + child list.If either index does not exist in the child list. + + RangeErrorRangeErrorindex1intThe index position of the first child object. + + index2intThe index position of the second child object. + + + Swaps the z-order (front-to-back order) of the child objects at the two specified index positions in the + child list. All other child objects in the display object container remain in the same index positions. + + The following example creates a display object container named + container, then adds three child display objects to the container, + and then shows how a call to the swapChildrenAt() method rearranges + the child list of the display object container: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; +var sprite3:Sprite = new Sprite(); +sprite3.name = "sprite3"; + +container.addChild(sprite1); +container.addChild(sprite2); +container.addChild(sprite3); + +trace(container.getChildAt(0).name); // sprite1 +trace(container.getChildAt(1).name); // sprite2 +trace(container.getChildAt(2).name); // sprite3 + +container.swapChildrenAt(0, 2); + +trace(container.getChildAt(0).name); // sprite3 +trace(container.getChildAt(1).name); // sprite2 +trace(container.getChildAt(2).name); // sprite1 +swapChildren + Swaps the z-order (front-to-back order) of the two specified child objects.Throws if either child parameter is not a child of this object. + + + ArgumentErrorArgumentErrorchild1flash.display:DisplayObjectThe first child object. + + child2flash.display:DisplayObjectThe second child object. + + + Swaps the z-order (front-to-back order) of the two specified child objects. All other child + objects in the display object container remain in the same index positions. + + The following example creates a display object container named + container, then adds two child display objects to the container, + and then shows the effect of a call to the swapChildren() method: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); + +var sprite1:Sprite = new Sprite(); +sprite1.name = "sprite1"; +var sprite2:Sprite = new Sprite(); +sprite2.name = "sprite2"; + +container.addChild(sprite1); +container.addChild(sprite2); + +trace(container.getChildAt(0).name); // sprite1 +trace(container.getChildAt(1).name); // sprite2 + +container.swapChildren(sprite1, sprite2); + +trace(container.getChildAt(0).name); // sprite2 +trace(container.getChildAt(1).name); // sprite1 +mouseChildren + Determines whether or not the children of the object are mouse, or user input device, enabled.Boolean + Determines whether or not the children of the object are mouse, or user input device, enabled. + If an object is enabled, a user can interact with it by using a mouse or user input device. The default is true. + +

This property is useful when you create a button with an instance of the Sprite class + (instead of using the SimpleButton class). When you use a Sprite instance to create a button, + you can choose to decorate the button by using the addChild() method to add additional + Sprite instances. This process can cause unexpected behavior with mouse events because + the Sprite instances you add as children can become the target object of a mouse event + when you expect the parent instance to be the target object. To ensure that the parent + instance serves as the target objects for mouse events, you can set the + mouseChildren property of the parent instance to false.

+

No event is dispatched by setting this property. You must use the + addEventListener() method to create interactive functionality.

+ +
The following example sets up a Sprite object (a type of display object container) named + container and shows that when you set its mouseChildren property to + false, the target of a mouseClick event is the container + object, not any one of its child objects: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var container:Sprite = new Sprite(); +container.name = "container"; +addChild(container); + +var circle:Sprite = new Sprite(); +circle.name = "circle"; +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(40, 40, 40); + +container.addChild(circle); + +container.mouseChildren = false; + +container.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void { + trace(event.target.name); // container +} +
flash.display.Sprite.buttonModeflash.events.EventDispatcher.addEventListener()
numChildren + Returns the number of children of this object.int + Returns the number of children of this object. + + The following example sets up two Sprite objects named container1 and + container2. A Sprite is a type of display object container. The example calls the + addChild() method to set up the display hierarchy: container1 is a child of + container2, and two other display objects, circle1 and circle2, + are children of container1. The calls to the trace() method show the number + of children of each object. Note that grandchildren are not included in the numChildren count: + +import flash.display.Sprite; + +var container1:Sprite = new Sprite(); +var container2:Sprite = new Sprite(); + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x00CCFF); +circle2.graphics.drawCircle(80, 40, 40); + +container2.addChild(container1); +container1.addChild(circle1); +container1.addChild(circle2); + +trace(container1.numChildren); // 2 +trace(container2.numChildren); // 1 +trace(circle1.numChildren); // 0 +trace(circle2.numChildren); // 0 +tabChildren + Determines whether the children of the object are tab enabled.BooleanCalling this property of the Stage object + throws an exception. The Stage object does not implement this property. + + IllegalOperationErrorflash.errors:IllegalOperationError + Determines whether the children of the object are tab enabled. Enables or disables tabbing for the + children of the object. The default is true. +

Note: Do not use the tabChildren property with Flex. + Instead, use the mx.core.UIComponent.hasFocusableChildren property.

+ +
The following example creates a container1 display object container and + adds two display objects, circle1 and circle2, + to its child list. The example sets tabChildren to false for the children so it can + manage its own tab order using tabIndex: + +import flash.display.Sprite; + +var container:Sprite = new Sprite(); +container.tabChildren = false; + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); +circle1.tabIndex = 1; + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0x00CCFF); +circle2.graphics.drawCircle(120, 40, 40); +circle2.tabIndex = 0; + +container.addChild(circle1); +container.addChild(circle2); + To see the results of this example, compile and run the file. When you select one of the circles, + you can press the TAB key to switch the display object that has focus (indicated by a yellow highlight rectangle). +
textSnapshot + Returns a TextSnapshot object for this DisplayObjectContainer instance.flash.text:TextSnapshot + Returns a TextSnapshot object for this DisplayObjectContainer instance. + + The following example works only in the Flash authoring environment. Flex does not include any + ways of adding static text to a file. To prepare the Flash file for this example, add one or more static text fields + in the first frame of a movie. Then insert the following script into the first frame and run the file. The output + will be the static text that you added: + +trace(this.textSnapshot.getText(0, this.textSnapshot.charCount)); +flash.text.TextSnapshot
GraphicsGradientFill + Defines a gradient fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject + Defines a gradient fill. + +

+ Use a GraphicsGradientFill object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsGradientFill object is the equivalent of calling the Graphics.beginGradientFill() method. +

+ +
flash.display.Graphics.beginGradientFill()flash.display.Graphics.drawGraphicsData()GraphicsGradientFill + Creates a new GraphicsGradientFill object.typeStringlinearA value from the GradientType class that + specifies which gradient type to use: GradientType.LINEAR or + GradientType.RADIAL. + + colorsArraynullAn array of RGB hexadecimal color values used in the gradient; for example, + red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. + For each color, specify a corresponding value in the alphas and ratios parameters. + + alphasArraynullAn array of alpha values for the corresponding colors in the colors array; + valid values are 0 to 1. If the value is less than 0, 0 is used. If the value is + greater than 1, 1 is used. + + ratiosArraynullAn array of color distribution ratios; valid values are 0-255. This value + defines the percentage of the width where the color is sampled at 100%. The value 0 represents + the left position in the gradient box, and 255 represents the right position in the + gradient box. + + matrixnullA transformation matrix as defined by the + flash.geom.Matrix class. The flash.geom.Matrix class includes a + createGradientBox() method, which lets you conveniently set up + the matrix for use with the beginGradientFill() method. + + spreadMethodpadA value from the SpreadMethod class that + specifies which spread method to use, either: SpreadMethod.PAD, + SpreadMethod.REFLECT, or SpreadMethod.REPEAT. + + interpolationMethodStringrgbA value from the InterpolationMethod class that + specifies which value to use: InterpolationMethod.LINEAR_RGB or + InterpolationMethod.RGB + + focalPointRatioNumber0.0A number that controls the + location of the focal point of the gradient. A value of 0 sets the focal point in the center. A value of 1 + sets the focal point at one border of the gradient circle. A value of -1 sets the focal point + at the other border of the gradient circle. A value less than -1 or greater than + 1 is rounded to -1 or 1, respectively. + + + Creates a new GraphicsGradientFill object. + + flash.display.Graphics.beginGradientFill()flash.display.GradientTypeflash.geom.Matrixflash.display.SpreadMethodflash.display.InterpolationMethodalphas + An array of alpha values for the corresponding colors in the colors array.Array + An array of alpha values for the corresponding colors in the colors array. + Valid values are between 0 and 1. If the value is less than 0, 0 is used. If the value is + greater than 1, 1 is used. + colors + An array of RGB hexadecimal color values to use in the gradient.Array + An array of RGB hexadecimal color values to use in the gradient. For example, + red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. + For each color, specify a corresponding value in the alphas and ratios properties. + focalPointRatio + A number that controls the + location of the focal point of the gradient.Number + A number that controls the + location of the focal point of the gradient. A value of 0 sets the focal point in the center. A value of 1 + means that the focal point is at one border of the gradient circle.A value of -1 sets the focal point + at the other border of the gradient circle. A value of less than -1 or greater than + 1 is rounded to -1 or 1, respectively. For example, the following + shows a focalPointRatio set to 0.75: + +

+
matrix + A transformation matrix as defined by the + Matrix class.flash.geom:Matrix + A transformation matrix as defined by the + Matrix class. The flash.geom.Matrix class includes a + createGradientBox() method to set up + the matrix for use with the beginGradientFill() method. + + flash.geom.Matrix.createGradientBox()ratios + An array of color distribution ratios.Array + An array of color distribution ratios. Valid values are between 0 and 255. This value + defines the percentage of the width where the color is sampled at 100%. The value 0 represents + the left position in the gradient box, and the value 255 represents the right position in the + gradient box. + +

Note: This value represents positions in the gradient box, not the + coordinate space of the final gradient which can be wider or thinner than the gradient box. + Specify a value for corresponding to each value in the colors property.

+ +

For example, for a linear gradient that includes two colors (blue and green) the + following example illustrates the placement of the colors in the gradient based on different values + in the ratios array:

+ + ratiosGradient[0, 127][0, 255][127, 255] + +

The values in the array must increase sequentially; for example, + [0, 63, 127, 190, 255].

+
interpolationMethod + A value from the InterpolationMethod class that + specifies which value to use.String + A value from the InterpolationMethod class that + specifies which value to use. Valid values are: InterpolationMethod.LINEAR_RGB or + InterpolationMethod.RGB + +

For example, the following shows a simple linear gradient between two colors (with the spreadMethod + parameter set to SpreadMethod.REFLECT). The different interpolation methods change + the appearance as follows:

+ + InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB + +
flash.display.InterpolationMethod
spreadMethod + A value from the SpreadMethod class that + specifies which spread method to use.String + A value from the SpreadMethod class that + specifies which spread method to use. Valid values are: SpreadMethod.PAD, + SpreadMethod.REFLECT, or SpreadMethod.REPEAT. + +

For example, the following shows a simple linear gradient between two colors:

+ + + import flash.geom.* + import flash.display.* + var fillType:String = GradientType.LINEAR; + var colors:Array = [0xFF0000, 0x0000FF]; + var alphas:Array = [1, 1]; + var ratios:Array = [0x00, 0xFF]; + var matr:Matrix = new Matrix(); + matr.createGradientBox(20, 20, 0, 0, 0); + var spreadMethod:String = SpreadMethod.PAD; + this.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); + this.graphics.drawRect(0,0,100,100); + + +

This example uses SpreadMethod.PAD for the spread method, and + the gradient fill looks like the following:

+ +

+ +

If you use SpreadMethod.REFLECT for the spread method, the gradient fill + looks like the following:

+ +

+ +

If you use SpreadMethod.REPEAT for the spread method, the gradient fill + looks like the following:

+ +

+ +
flash.display.SpreadMethod
type + A value from the GradientType class that + specifies which gradient type to use.String + A value from the GradientType class that + specifies which gradient type to use. Values are GradientType.LINEAR or + GradientType.RADIAL. + + flash.display.GradientType
Sprite + The Sprite class is a basic display list building block: a display list node that can display + graphics and can also contain children.The basic display object for ActionScript created objects. + + + flash.display:DisplayObjectContainer + The Sprite class is a basic display list building block: a display list node that can display + graphics and can also contain children. + +

A Sprite object is similar to a movie clip, but does not have a timeline. Sprite is an + appropriate base class for objects that do not require timelines. For example, Sprite would be a + logical base class for user interface (UI) components that typically do not use the timeline.

+ +

The Sprite class is new in ActionScript 3.0. It provides an alternative to the functionality of + the MovieClip class, which retains all the functionality of previous ActionScript releases to + provide backward compatibility.

+ +
The following example uses the SpriteExample class to draw an + orange square on the stage, and then dispatches events whenever the user clicks or drags the + square. This task is accomplished by performing the following steps: +
  1. Declare the size property (100 x 100 pixels) and the background color + (orange) for later use in drawing the square.
  2. The constructor then creates a new child Sprite object and uses it to add + two event listeners and their associated methods: mouseDownHandler() and + mouseUpHandler().
  3. The child Sprite object is then passed to the + draw() method, which draws the orange square.
  4. The child is then placed on the display list by a call to the addChild() + method.
  5. The event listeners work as follows: + +
    • mouseDownHandler(): when the user clicks the Sprite object, + this method adds a mouseMove event listener, the mouseMoveHandler() method, + which processes the mouse moves. Then the startDrag() method is called, which + allows the Sprite object to be dragged.
    • mouseUpHandler(): when the mouse button is released, the mouseMove event listener + is removed and the stopDrag() method is called, which freezes the orange square in + place.
    • mouseMoveHandler: as long as the left mouse button is being held down, this + method instructs the player to continuously redraw the orange square.
    +
+ +

Note: Each of the event listener methods declares a local sprite + variable, which is assigned the target property of the event.

+ + + +package { + import flash.display.Sprite; + import flash.events.*; + + public class SpriteExample extends Sprite { + private var size:uint = 100; + private var bgColor:uint = 0xFFCC00; + + public function SpriteExample() { + var child:Sprite = new Sprite(); + child.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + child.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + draw(child); + addChild(child); + } + + private function mouseDownHandler(event:MouseEvent):void { + trace("mouseDownHandler"); + var sprite:Sprite = Sprite(event.target); + sprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + sprite.startDrag(); + } + + private function mouseUpHandler(event:MouseEvent):void { + trace("mouseUpHandler"); + var sprite:Sprite = Sprite(event.target); + sprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + sprite.stopDrag(); + } + + private function mouseMoveHandler(event:MouseEvent):void { + trace("mouseMoveHandler"); + event.updateAfterEvent(); + } + + private function draw(sprite:Sprite):void { + sprite.graphics.beginFill(bgColor); + sprite.graphics.drawRect(0, 0, size, size); + sprite.graphics.endFill(); + } + } +} +
Sprite + Creates a new Sprite instance. + Creates a new Sprite instance. After you create the Sprite instance, call the + DisplayObjectContainer.addChild() or DisplayObjectContainer.addChildAt() + method to add the Sprite to a parent DisplayObjectContainer. + + startDrag + Lets the user drag the specified sprite.lockCenterBooleanfalseSpecifies whether the draggable sprite is locked to the center of + the pointer position (true), or locked to the point where the user first clicked the + sprite (false). + + boundsflash.geom:RectanglenullValue relative to the coordinates of the Sprite's parent that specify a constraint + rectangle for the Sprite. + + + Lets the user drag the specified sprite. The sprite remains draggable until explicitly + stopped through a call to the Sprite.stopDrag() method, or until + another sprite is made draggable. Only one sprite is draggable at a time. +

Three-dimensional display objects follow the pointer and + Sprite.startDrag() moves the object within + the three-dimensional plane defined by the display object. Or, if the display object is a two-dimensional object + and the child of a three-dimensional object, the two-dimensional object + moves within the three dimensional plane defined by the three-dimensional parent object.

+ +
The following example creates a circle sprite and two target + sprites. The startDrag() method is called on the circle sprite when the user + positions the cursor over the sprite and presses the mouse button, and the stopDrag() method + is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse + button, the mouseRelease() method is called, which in turn traces the name + of the dropTarget object — the one to which the user dragged the + circle sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(0, 0, 40); + +var target1:Sprite = new Sprite(); +target1.graphics.beginFill(0xCCFF00); +target1.graphics.drawRect(0, 0, 100, 100); +target1.name = "target1"; + +var target2:Sprite = new Sprite(); +target2.graphics.beginFill(0xCCFF00); +target2.graphics.drawRect(0, 200, 100, 100); +target2.name = "target2"; + +addChild(target1); +addChild(target2); +addChild(circle); + +circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) + +function mouseDown(event:MouseEvent):void { + circle.startDrag(); +} +circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); + +function mouseReleased(event:MouseEvent):void { + circle.stopDrag(); + trace(circle.dropTarget.name); +} +
dropTargetstopDrag()
startTouchDrag + Lets the user drag the specified sprite on a touch-enabled device.touchPointIDintAn integer to assign to the touch point. + lockCenterBooleanfalseSpecifies whether the draggable sprite is locked to the center of + the pointer position (true), or locked to the point where the user first clicked the + sprite (false). + + boundsflash.geom:RectanglenullValue relative to the coordinates of the Sprite's parent that specify a constraint + rectangle for the Sprite. + + + Lets the user drag the specified sprite on a touch-enabled device. The sprite remains draggable until explicitly + stopped through a call to the Sprite.stopTouchDrag() method, or until + another sprite is made draggable. Only one sprite is draggable at a time. +

Three-dimensional display objects follow the pointer and + Sprite.startTouchDrag() moves the object within + the three-dimensional plane defined by the display object. Or, if the display object is a two-dimensional object + and the child of a three-dimensional object, the two-dimensional object + moves within the three dimensional plane defined by the three-dimensional parent object.

+ +
The following example shows functions using startTouchDrag and stopTouchDrag to handle the touchBegin and touchEnd events. + The value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(e:TouchEvent) { + e.target.startTouchDrag(e.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } +function onTouchEnd(e:TouchEvent) { + e.target.stopTouchDrag(e.touchPointID); + trace("touch end"); +} +
dropTargetstopTouchDrag()flash.ui.Multitouchflash.events.TouchEvent
stopDrag + Ends the startDrag() method. + Ends the startDrag() method. A sprite that was made draggable with the + startDrag() method remains draggable until a + stopDrag() method is added, or until another + sprite becomes draggable. Only one sprite is draggable at a time. + + The following example creates a circle sprite and two target + sprites. The startDrag() method is called on the circle sprite when the user + positions the cursor over the sprite and presses the mouse button, and the stopDrag() method + is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse + button, the mouseRelease() method is called, which in turn traces the name + of the dropTarget object — the one to which the user dragged the + circle sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(0, 0, 40); + +var target1:Sprite = new Sprite(); +target1.graphics.beginFill(0xCCFF00); +target1.graphics.drawRect(0, 0, 100, 100); +target1.name = "target1"; + +var target2:Sprite = new Sprite(); +target2.graphics.beginFill(0xCCFF00); +target2.graphics.drawRect(0, 200, 100, 100); +target2.name = "target2"; + +addChild(target1); +addChild(target2); +addChild(circle); + +circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) + +function mouseDown(event:MouseEvent):void { + circle.startDrag(); +} +circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); + +function mouseReleased(event:MouseEvent):void { + circle.stopDrag(); + trace(circle.dropTarget.name); +} +dropTargetstartDrag()stopTouchDrag + Ends the startTouchDrag() method, for use with touch-enabled devices.touchPointIDintThe integer assigned to the touch point in the startTouchDrag method. + + Ends the startTouchDrag() method, for use with touch-enabled devices. A sprite that was made draggable with the + startTouchDrag() method remains draggable until a + stopTouchDrag() method is added, or until another + sprite becomes draggable. Only one sprite is draggable at a time. + The following example shows functions using startTouchDrag and stopTouchDrag to handle the touchBegin and touchEnd events. + The value for touchPointID is the value assigned to the event object. The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(e:TouchEvent) { + e.target.startTouchDrag(e.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } +function onTouchEnd(e:TouchEvent) { + e.target.stopTouchDrag(e.touchPointID); + trace("touch end"); +} +dropTargetstartTouchDrag()flash.ui.Multitouchflash.events.TouchEventbuttonMode + Specifies the button mode of this sprite.BooleanSpecifies the button mode of this sprite. + + + Specifies the button mode of this sprite. If true, this + sprite behaves as a button, which means that it triggers the display + of the hand cursor when the pointer passes over the sprite and can + receive a click event if the enter or space keys are pressed + when the sprite has focus. You can suppress the display of the hand cursor + by setting the useHandCursor property to false, + in which case the pointer is displayed. + +

Although it is better to use the SimpleButton class to create buttons, + you can use the buttonMode property to give a sprite + some button-like functionality. To include a sprite in the tab order, + set the tabEnabled property (inherited from the + InteractiveObject class and false by default) to + true. Additionally, consider whether you want + the children of your sprite to be user input enabled. Most buttons + do not enable user input interactivity for their child objects because + it confuses the event flow. To disable user input interactivity for all child + objects, you must set the mouseChildren property (inherited + from the DisplayObjectContainer class) to false.

+ +

If you use the buttonMode property with the MovieClip class (which is a + subclass of the Sprite class), your button might have some added + functionality. If you include frames labeled _up, _over, and _down, + Flash Player provides automatic state changes (functionality + similar to that provided in previous versions of ActionScript for movie + clips used as buttons). These automatic state changes are + not available for sprites, which have no timeline, and thus no frames + to label.

+ +
The following example creates two sprites and sets the buttonMode + property to true for one and false for the other. When you compile + and run the application, both sprites respond to mouse events, but only the one in which + buttonMode is set to true uses the hand cursor and is included + in the tab order: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); +circle1.buttonMode = true; +circle1.addEventListener(MouseEvent.CLICK, clicked); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0xFFCC00); +circle2.graphics.drawCircle(120, 40, 40); +circle2.buttonMode = false; +circle2.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void { + trace ("Click!"); +} + +addChild(circle1); +addChild(circle2); +
SimpleButtonSprite.useHandCursorInteractiveObject.tabEnabledDisplayObjectContainer.mouseChildren
dropTarget + Specifies the display object over which the sprite is being dragged, or on + which the sprite was dropped.flash.display:DisplayObjectSpecifies the DisplayObject over which the sprite is being dragged, or on which the + sprite was dropped. + + + + Specifies the display object over which the sprite is being dragged, or on + which the sprite was dropped. + + The following example creates a circle sprite and two target + sprites. The startDrag() method is called on the circle sprite when the user + positions the cursor over the sprite and presses the mouse button, and the stopDrag() method + is called when the user releases the mouse button. This lets the user drag the sprite. On release of the mouse + button, the mouseRelease() method is called, which in turn traces the name + of the dropTarget object — the one to which the user dragged the + circle sprite: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(0, 0, 40); + +var target1:Sprite = new Sprite(); +target1.graphics.beginFill(0xCCFF00); +target1.graphics.drawRect(0, 0, 100, 100); +target1.name = "target1"; + +var target2:Sprite = new Sprite(); +target2.graphics.beginFill(0xCCFF00); +target2.graphics.drawRect(0, 200, 100, 100); +target2.name = "target2"; + +addChild(target1); +addChild(target2); +addChild(circle); + +circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown) + +function mouseDown(event:MouseEvent):void { + circle.startDrag(); +} +circle.addEventListener(MouseEvent.MOUSE_UP, mouseReleased); + +function mouseReleased(event:MouseEvent):void { + circle.stopDrag(); + trace(circle.dropTarget.name); +} +startDrag()stopDrag()graphics + Specifies the Graphics object that belongs to this sprite where vector + drawing commands can occur.flash.display:GraphicsSpecifies a Graphics object. + + + + Specifies the Graphics object that belongs to this sprite where vector + drawing commands can occur. + + The following example creates a circle sprite and uses its + graphics property to draw a circle with a yellow (0xFFCC00) fill: + +import flash.display.Sprite; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(40, 40, 40); +addChild(circle); +hitArea + Designates another sprite to serve as the hit area for a sprite.flash.display:Sprite + Designates another sprite to serve as the hit area for a sprite. If the hitArea + property does not exist or the value is null or undefined, the + sprite itself is used as the hit area. The value of the hitArea property can + be a reference to a Sprite object. + +

You can change the hitArea property at any time; the modified sprite immediately + uses the new hit area behavior. The sprite designated as the hit area does not need to be + visible; its graphical shape, although not visible, is still detected as the hit area.

+ +

Note: You must set to false the mouseEnabled + property of the sprite designated as the hit area. Otherwise, your sprite button might + not work because the sprite designated as the hit area receives the user input events instead + of your sprite button.

+ +
The following example creates a circle sprite and a square + sprite. The square sprite is the hitArea for the circle sprite. + So when the user clicks the square sprite, the circle sprite dispatches + a click event: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle:Sprite = new Sprite(); +circle.graphics.beginFill(0xFFCC00); +circle.graphics.drawCircle(0, 0, 40); + +var square:Sprite = new Sprite(); +square.graphics.beginFill(0xCCFF00); +square.graphics.drawRect(200, 0, 100, 100); + +circle.hitArea = square; +square.mouseEnabled = false; + +circle.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void{ + trace(event.target == circle); // true + trace(event.target == square); // false +} + +addChild(circle); +addChild(square); +
soundTransform + Controls sound within this sprite.flash.media:SoundTransform + Controls sound within this sprite. + +

Note: This property does not affect HTML content in an HTMLControl object (in Adobe AIR).

+ +
The following example creates a sprite named container + and adds a Loader object to its child list. The Loader object loads a SWF file. + When the user clicks the link in the tf text field true, the + mute() method sets the volume property of the + soundTransform property of the container sprite: + +import flash.display.Sprite; +import flash.display.Loader; +import flash.events.IOErrorEvent; +import flash.events.MouseEvent; +import flash.net.URLRequest; +import flash.text.TextField; +import flash.media.SoundTransform; + +var container:Sprite = new Sprite(); +addChild(container); + +var ldr:Loader = new Loader; +var urlReq:URLRequest = new URLRequest("SoundPlayer.swf"); +ldr.load(urlReq); + +container.addChild(ldr); +ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, urlNotFound); + +var tf:TextField = new TextField(); +tf.htmlText = "<a href = 'event:Mute'>Mute / Unmute</a>"; +addChild(tf); + +var mySoundTransform:SoundTransform = new SoundTransform(); +mySoundTransform.volume = 1; + +tf.addEventListener(MouseEvent.CLICK, mute); + +function mute(event:MouseEvent):void { + if (mySoundTransform.volume == 0) { + mySoundTransform.volume = 1; + } else { + mySoundTransform.volume = 0; + } + container.soundTransform = mySoundTransform; +} + +function urlNotFound(event:IOErrorEvent):void { + trace("The URL was not found."); +} +
flash.media.SoundTransform
useHandCursor + A Boolean value that indicates whether the pointing hand (hand cursor) appears when the pointer rolls + over a sprite in which the buttonMode property is set to true.BooleanA Boolean value that indicates whether the pointing hand (hand cursor) appears when the + pointer rolls over a sprite in which the buttonMode property is set to true. + + + A Boolean value that indicates whether the pointing hand (hand cursor) appears when the pointer rolls + over a sprite in which the buttonMode property is set to true. + The default value of the useHandCursor property is true. + If useHandCursor is set to true, the pointing hand used for buttons + appears when the pointer rolls over a button sprite. If useHandCursor is + false, the arrow pointer is used instead. + +

You can change the useHandCursor property at any time; the modified sprite + immediately takes on the new cursor appearance.

+ +

Note: In Flex or Flash Builder, if your sprite has child sprites, you might want to + set the mouseChildren property to false. For example, if you want a hand + cursor to appear over a Flex <mx:Label> control, set the useHandCursor and + buttonMode properties to true, and the mouseChildren property + to false.

+ +
The following example creates two sprites and sets the buttonMode + property to true for both, yet it sets the useHandCursor + property to true for one and false for the other. When you compile + and run the application, both sprites respond as buttons (and are included in the tab order), but + only the one in which useHandCursor is set to true uses the hand cursor: + +import flash.display.Sprite; +import flash.events.MouseEvent; + +var circle1:Sprite = new Sprite(); +circle1.graphics.beginFill(0xFFCC00); +circle1.graphics.drawCircle(40, 40, 40); +circle1.buttonMode = true; +circle1.useHandCursor = true; +circle1.addEventListener(MouseEvent.CLICK, clicked); + +var circle2:Sprite = new Sprite(); +circle2.graphics.beginFill(0xFFCC00); +circle2.graphics.drawCircle(120, 40, 40); +circle2.buttonMode = true; +circle2.useHandCursor = false; +circle2.addEventListener(MouseEvent.CLICK, clicked); + +function clicked(event:MouseEvent):void { + trace ("Click!"); +} + +addChild(circle1); +addChild(circle2); +
buttonModeDisplayObjectContainer.mouseChildren
GraphicsBitmapFill + Defines a bitmap fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject + Defines a bitmap fill. The bitmap can be smoothed, repeated or tiled to fill + the area; or manipulated using a transformation matrix. +

+ Use a GraphicsBitmapFill object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsBitmapFill object is the equivalent of calling the Graphics.beginBitmapFill() method. +

+ +
flash.display.Graphics.drawGraphicsData()flash.display.Graphics.beginBitmapFill()GraphicsBitmapFill + Creates a new GraphicsBitmapFill object.bitmapDataflash.display:BitmapDatanullA transparent or opaque bitmap image that contains the bits to display. + + matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you use to + define transformations on the bitmap. + + repeatBooleantrueIf true, the bitmap image repeats in a tiled pattern. If + false, the bitmap image does not repeat, and the edges of the bitmap are + used for any fill area that extends beyond the bitmap. + + smoothBooleanfalseIf false, upscaled bitmap images are rendered using a + nearest-neighbor algorithm and appear pixelated. If true, upscaled + bitmap images are rendered using a bilinear algorithm. Rendering that uses the nearest-neighbor + algorithm is usually faster. + + + Creates a new GraphicsBitmapFill object. + + flash.display.Graphics.beginBitmapFill()bitmapData + A transparent or opaque bitmap image.flash.display:BitmapData + A transparent or opaque bitmap image. + + flash.display.BitmapDatamatrix + A matrix object (of the flash.geom.Matrix class) that + defines transformations on the bitmap.flash.geom:Matrix + A matrix object (of the flash.geom.Matrix class) that + defines transformations on the bitmap. For example, the following matrix + rotates a bitmap by 45 degrees (pi/4 radians): + + + matrix = new flash.geom.Matrix(); + matrix.rotate(Math.PI / 4); + + + flash.geom.Matrixrepeat + Specifies whether to repeat the bitmap image in a tiled pattern.Boolean + Specifies whether to repeat the bitmap image in a tiled pattern. + +

+ If true, the bitmap image repeats in a tiled pattern. If + false, the bitmap image does not repeat, and the outermost pixels along + the edges of the bitmap are used for any fill area that extends beyond the bounds of the bitmap.

+ +

For example, consider the following bitmap (a 20 x 20-pixel checkerboard pattern):

+ +

+ +

When repeat is set to true (as in the following example), the bitmap fill + repeats the bitmap:

+ +

+ +

When repeat is set to false, the bitmap fill uses the edge + pixels for the fill area outside the bitmap:

+ +

+
smooth + Specifies whether to apply a smoothing algorithm to the bitmap image.Boolean + Specifies whether to apply a smoothing algorithm to the bitmap image. +

+ If false, upscaled bitmap images are rendered by using a + nearest-neighbor algorithm and look pixelated. If true, upscaled + bitmap images are rendered by using a bilinear algorithm. Rendering by using the nearest + neighbor algorithm is usually faster. +

+
GraphicsStroke + Defines a line style or stroke.flash.display:IGraphicsStrokeflash.display:IGraphicsDataObject + Defines a line style or stroke. + +

+ Use a GraphicsStroke object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsStroke object is the equivalent of calling one of the methods of the Graphics + class that sets the line style, such as the Graphics.lineStyle() method, the + Graphics.lineBitmapStyle() method, or the Graphics.lineGradientStyle() + method. +

+ +
flash.display.Graphics.lineStyle()flash.display.Graphics.lineBitmapStyle()flash.display.Graphics.lineGradientStyle()flash.display.Graphics.drawGraphicsData()GraphicsStroke + Creates a new GraphicsStroke object.thicknessNumberunknownAn integer that indicates the thickness of the line in + points; valid values are 0-255. If a number is not specified, or if the + parameter is undefined, a line is not drawn. If a value of less than 0 is passed, + the default is 0. The value 0 indicates hairline thickness; the maximum thickness + is 255. If a value greater than 255 is passed, the default is 255. + + pixelHintingBooleanfalseA Boolean value that specifies whether to hint strokes + to full pixels. This affects both the position of anchors of a curve and the line stroke size + itself. With pixelHinting set to true, Flash Player hints line widths + to full pixel widths. With pixelHinting set to false, disjoints can + appear for curves and straight lines. For example, the following illustrations show how + Flash Player renders two rounded rectangles that are identical, except that the + pixelHinting parameter used in the lineStyle() method is set + differently (the images are scaled by 200%, to emphasize the difference): + +

+ +

If a value is not supplied, the line does not use pixel hinting.

+ +
scaleModeStringnormalA value from the LineScaleMode class that + specifies which scale mode to use: + +
  • + LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled + (the default). +
  • + LineScaleMode.NONE—Never scale the line thickness. +
  • + LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left + is scaled vertically only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
  • + LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left + is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
+ + +
capsStringnoneA value from the CapsStyle class that specifies the type of caps at the end + of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. + If a value is not indicated, Flash uses round caps. +

For example, the following illustrations show the different capsStyle + settings. For each setting, the illustration shows a blue line with a thickness of 30 (for + which the capsStyle applies), and a superimposed black line with a thickness of 1 + (for which no capsStyle applies): +

+

+ +
jointsStringroundA value from the JointStyle class that specifies the type of joint appearance + used at angles. Valid + values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. + If a value is not indicated, Flash uses round joints. + +

For example, the following illustrations show the different joints + settings. For each setting, the illustration shows an angled blue line with a thickness of + 30 (for which the jointStyle applies), and a superimposed angled black line with a + thickness of 1 (for which no jointStyle applies): +

+ +

+ +

Note: For joints set to JointStyle.MITER, + you can use the miterLimit parameter to limit the length of the miter.

+ +
miterLimitNumber3.0A number that indicates the limit at which a miter is cut off. + Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). + This value is only used if the jointStyle + is set to "miter". The + miterLimit value represents the length that a miter can extend beyond the point + at which the lines meet to form a joint. The value expresses a factor of the line + thickness. For example, with a miterLimit factor of 2.5 and a + thickness of 10 pixels, the miter is cut off at 25 pixels. + +

For example, consider the following angled lines, each drawn with a thickness + of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference + lines showing the meeting points of the joints:

+ +

+ +

Notice that a given miterLimit value has a specific maximum angle + for which the miter is cut off. The following table lists some examples:

+ + miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees +
fillflash.display:IGraphicsFillnullAn IGraphicsFill instance containing data for filling a stroke. An IGraphicsFill + instance can represent a series of fill commands. + +
+ Creates a new GraphicsStroke object. +
flash.display.LineScaleModeflash.display.CapsStyleflash.display.JointStyleflash.display.IGraphicsFill
fill + Specifies the instance containing data for filling a stroke.flash.display:IGraphicsFill + Specifies the instance containing data for filling a stroke. An IGraphicsFill + instance can represent a series of fill commands. + + flash.display.IGraphicsFillmiterLimit + Indicates the limit at which a miter is cut off.Number + Indicates the limit at which a miter is cut off. + Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). + This value is only used if the jointStyle + is set to "miter". The + miterLimit value represents the length that a miter can extend beyond the point + at which the lines meet to form a joint. The value expresses a factor of the line + thickness. For example, with a miterLimit factor of 2.5 and a + thickness of 10 pixels, the miter is cut off at 25 pixels. + +

For example, consider the following angled lines, each drawn with a thickness + of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference + lines showing the meeting points of the joints:

+ +

+ +

Notice that a given miterLimit value has a specific maximum angle + for which the miter is cut off. The following table lists some examples:

+ + miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees + +
pixelHinting + Specifies whether to hint strokes + to full pixels.Boolean + Specifies whether to hint strokes + to full pixels. This affects both the position of anchors of a curve and the line stroke size + itself. With pixelHinting set to true, Flash Player hints line widths + to full pixel widths. With pixelHinting set to false, disjoints can + appear for curves and straight lines. For example, the following illustrations show how + Flash Player renders two rounded rectangles that are identical, except that the + pixelHinting parameter used in the lineStyle() method is set + differently (the images are scaled by 200%, to emphasize the difference): + +

+ +
thickness + Indicates the thickness of the line in + points; valid values are 0-255.Number + Indicates the thickness of the line in + points; valid values are 0-255. If a number is not specified, or if the + parameter is undefined, a line is not drawn. If a value of less than 0 is passed, + the default is 0. The value 0 indicates hairline thickness; the maximum thickness + is 255. If a value greater than 255 is passed, the default is 255. + + caps + Specifies the type of caps at the end + of lines.String + Specifies the type of caps at the end + of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. + If a value is not indicated, Flash uses round caps. +

For example, the following illustrations show the different capsStyle + settings. For each setting, the illustration shows a blue line with a thickness of 30 (for + which the capsStyle applies), and a superimposed black line with a thickness of 1 + (for which no capsStyle applies): +

+

+ +
flash.display.CapsStyle
joints + Specifies the type of joint appearance + used at angles.String + Specifies the type of joint appearance + used at angles. Valid + values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. + If a value is not indicated, Flash uses round joints. + +

For example, the following illustrations show the different joints + settings. For each setting, the illustration shows an angled blue line with a thickness of + 30 (for which the jointStyle applies), and a superimposed angled black line with a + thickness of 1 (for which no jointStyle applies): +

+ +

+ +

Note: For joints set to JointStyle.MITER, + you can use the miterLimit parameter to limit the length of the miter.

+ +
flash.display.JointStyle
scaleMode + Specifies the stroke thickness scaling.String + Specifies the stroke thickness scaling. Valid values are: + +
  • + LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled + (the default). +
  • + LineScaleMode.NONE—Never scale the line thickness. +
  • + LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left + is scaled vertically only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
  • + LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left + is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
+ +
flash.display.LineScaleMode
GraphicsEndFill + Indicates the end of a graphics fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject + Indicates the end of a graphics fill. Use a GraphicsEndFill object with the Graphics.drawGraphicsData() method. + +

+ Drawing a GraphicsEndFill object is the equivalent of calling the Graphics.endFill() method. +

+ +
flash.display.Graphics.drawGraphicsData()flash.display.Graphics.endFill()GraphicsEndFill + Creates an object to use with the Graphics.drawGraphicsData() method to end + the fill, explicitly. + Creates an object to use with the Graphics.drawGraphicsData() method to end + the fill, explicitly. + + + flash.display.Graphics.drawGraphicsData()flash.display.Graphics.endFill()
ShaderPrecision + This class defines the constants that represent the possible values for + the Shader class's precisionHint property.Object + This class defines the constants that represent the possible values for + the Shader class's precisionHint property. Each constant + represents one of the precision modes for executing shader operations. + +

The precision mode selection affects the following shader operations. + These operations are faster on an Intel processor + with the SSE instruction set:

+ +
  • sin(x)
  • cos(x)
  • tan(x)
  • asin(x)
  • acos(x)
  • atan(x)
  • atan(x, y)
  • exp(x)
  • exp2(x)
  • log(x)
  • log2(x)
  • pow(x, y)
  • reciprocal(x)
  • sqrt(x)
+ +
flash.display.Shader.precisionHintFAST + Represents fast precision mode.fastString + Represents fast precision mode. + +

Fast precision mode is designed for + maximum performance but does not work consistently on different platforms + and individual CPU configurations. In many cases, this level of precision + is sufficient to create graphic effects without visible artifacts.

+ +

It is usually faster to use fast precision mode than to use lookup tables.

+ +
flash.display.Shader.precisionHint
FULL + Represents full precision mode.fullString + Represents full precision mode. + +

In full precision mode, the shader computes all math + operations to the full width of the IEEE 32-bit floating standard. This mode provides + consistent behavior on all platforms. In this mode, some math operations such + as trigonometric and exponential functions can be slow.

+ +
flash.display.Shader.precisionHint
BlendMode +A class that provides constant values for visual blend mode effects.Object +A class that provides constant values for visual blend mode effects. These constants are used in the following: + +
  • The blendMode property of the flash.display.DisplayObject class.
  • The blendMode parameter of the draw() method of the + flash.display.BitmapData class
+ +
flash.display.DisplayObject.blendModeflash.display.BitmapData.draw()ADD +Adds the values of the constituent colors of the display object to the colors of its background, applying a +ceiling of 0xFF.addString +Adds the values of the constituent colors of the display object to the colors of its background, applying a +ceiling of 0xFF. This setting is commonly used for animating a lightening dissolve between +two objects. + +

For example, if the display object has a pixel with an RGB value of 0xAAA633, and the background +pixel has an RGB value of 0xDD2200, the resulting RGB value for the displayed pixel is +0xFFC833 (because 0xAA + 0xDD > 0xFF, 0xA6 + 0x22 = 0xC8, and 0x33 + 0x00 = 0x33).

+
ALPHA +Applies the alpha value of each pixel of the display object to the background.alphaString +Applies the alpha value of each pixel of the display object to the background. +This requires the blendMode property of the parent display object be set to +flash.display.BlendMode.LAYER. + +

Not supported under GPU rendering.

+ +
DARKEN +Selects the darker of the constituent colors of the display object and the colors of the background (the +colors with the smaller values).darkenString +Selects the darker of the constituent colors of the display object and the colors of the background (the +colors with the smaller values). This setting is commonly used for superimposing type. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background +pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is +0xDDCC00 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

+ +

Not supported under GPU rendering.

+ +
DIFFERENCE +Compares the constituent colors of the display object with the colors of its background, and subtracts +the darker of the values of the two constituent colors from the lighter value.differenceString +Compares the constituent colors of the display object with the colors of its background, and subtracts +the darker of the values of the two constituent colors from the lighter value. This setting is commonly +used for more vibrant colors. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background +pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is +0x222C33 (because 0xFF - 0xDD = 0x22, 0xF8 - 0xCC = 0x2C, and 0x33 - 0x00 = 0x33).

+
ERASE +Erases the background based on the alpha value of the display object.eraseString +Erases the background based on the alpha value of the display object. This process requires +that the blendMode property of the parent display object be set to +flash.display.BlendMode.LAYER. + +

Not supported under GPU rendering.

+ +
HARDLIGHT +Adjusts the color of each pixel based on the darkness of the display object.hardlightString +Adjusts the color of each pixel based on the darkness of the display object. +If the display object is lighter than 50% gray, the display object and background colors are +screened, which results in a lighter color. If the display object is darker than 50% gray, +the colors are multiplied, which results in a darker color. +This setting is commonly used for shading effects. + +

Not supported under GPU rendering.

+ +
INVERT +Inverts the background.invertString +Inverts the background. +LAYER +Forces the creation of a transparency group for the display object.layerString +Forces the creation of a transparency group for the display object. This means that the display +object is precomposed in a temporary buffer before it is processed further. The precomposition is done +automatically if the display object is precached by means of bitmap caching or if the display object is +a display object container that has at least one child object with a blendMode +setting other than "normal". + +

Not supported under GPU rendering.

+ +
LIGHTEN +Selects the lighter of the constituent colors of the display object and the colors of the background (the +colors with the larger values).lightenString +Selects the lighter of the constituent colors of the display object and the colors of the background (the +colors with the larger values). This setting is commonly used for superimposing type. + +

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background +pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is +0xFFF833 (because 0xFF > 0xDD, 0xCC < 0xF8, and 0x33 > 0x00 = 33).

+ +

Not supported under GPU rendering.

+ +
MULTIPLY +Multiplies the values of the display object constituent colors by the constituent colors of +the background color, and normalizes by dividing by 0xFF, +resulting in darker colors.multiplyString +Multiplies the values of the display object constituent colors by the constituent colors of +the background color, and normalizes by dividing by 0xFF, +resulting in darker colors. This setting is commonly used for shadows and depth effects. + +

For example, if a constituent color (such as red) of one pixel in the display object and the +corresponding color of the pixel in the background both have the value 0x88, the multiplied +result is 0x4840. Dividing by 0xFF yields a value of 0x48 for that constituent color, +which is a darker shade than the color of the display object or the color of the background.

+
NORMAL +The display object appears in front of the background.normalString +The display object appears in front of the background. Pixel values of the display object +override the pixel values of the background. Where the display object is transparent, the +background is visible. + +OVERLAY +Adjusts the color of each pixel based on the darkness of the background.overlayString +Adjusts the color of each pixel based on the darkness of the background. +If the background is lighter than 50% gray, the display object and background colors are +screened, which results in a lighter color. If the background is darker than 50% gray, +the colors are multiplied, which results in a darker color. +This setting is commonly used for shading effects. + +

Not supported under GPU rendering.

+ +
SCREEN +Multiplies the complement (inverse) of the display object color by the complement of the background +color, resulting in a bleaching effect.screenString +Multiplies the complement (inverse) of the display object color by the complement of the background +color, resulting in a bleaching effect. This setting is commonly used for highlights or to remove black +areas of the display object. +SHADER +Uses a shader to define the blend between objects.shaderString +Uses a shader to define the blend between objects. + +

Setting the blendShader property to a Shader instance +automatically sets the display object's blendMode property to +BlendMode.SHADER. If the blendMode property is set to +BlendMode.SHADER without first setting the blendShader property, +the blendMode property is set to BlendMode.NORMAL instead. +If the blendShader property is set (which sets the +blendMode property to BlendMode.SHADER), then later the value of the +blendMode property is changed, the blend mode can be reset to use the blend +shader simply by setting the blendMode property to BlendMode.SHADER. +The blendShader property does not need to be set again except to change the +shader that's used to define the blend mode.

+ +

Not supported under GPU rendering.

+ + +
flash.display.DisplayObject.blendModeflash.display.DisplayObject.blendShaderflash.display.Shader
SUBTRACT +Subtracts the values of the constituent colors in the display object from the values of the background +color, applying a floor of 0.subtractString +Subtracts the values of the constituent colors in the display object from the values of the background +color, applying a floor of 0. This setting is commonly used for animating a darkening dissolve between +two objects. + +

For example, if the display object has a pixel with an RGB value of 0xAA2233, and the background +pixel has an RGB value of 0xDDA600, the resulting RGB value for the displayed pixel is +0x338400 (because 0xDD - 0xAA = 0x33, 0xA6 - 0x22 = 0x84, and 0x00 - 0x33 < 0x00).

+
Graphics + The Graphics class contains a set of methods that you can use to create a vector shape.Object + The Graphics class contains a set of methods that you can use to create a vector shape. + Display objects that support drawing include Sprite and Shape objects. + Each of these classes includes a graphics property that is a Graphics object. + The following are among those helper functions provided for ease of use: + drawRect(), drawRoundRect(), + drawCircle(), and drawEllipse(). + +

You cannot create a Graphics object directly from ActionScript code. + If you call new Graphics(), an exception is thrown.

+ +

The Graphics class is final; it cannot be subclassed.

+ + +
The following example uses the GraphicsExample class to draw a circle, + a rounded rectangle, and a square. This task is accomplished by using the following steps: +
  1. Declare a size property for later use in determining the size of each shape.
  2. Declare properties that set the background color to orange, the border color to + dark gray, the border size to 0 pixels, the corner radius to 9 pixels, and set the space + between the stage edge and the other objects to be 5 pixels.
  3. Use the properties declared in the preceding steps along with the built in methods of the + Graphics class to draw the circle, rounded rectangle, and square at coordinates x = 0, y = 0.
  4. Redraw each of the shapes along the top of the stage, starting at x = 5, y = 5, with + a 5-pixel spacing between shapes.
+ + +package { + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Shape; + import flash.display.Sprite; + + public class GraphicsExample extends Sprite { + private var size:uint = 80; + private var bgColor:uint = 0xFFCC00; + private var borderColor:uint = 0x666666; + private var borderSize:uint = 0; + private var cornerRadius:uint = 9; + private var gutter:uint = 5; + + public function GraphicsExample() { + doDrawCircle(); + doDrawRoundRect(); + doDrawRect(); + refreshLayout(); + } + + private function refreshLayout():void { + var ln:uint = numChildren; + var child:DisplayObject; + var lastChild:DisplayObject = getChildAt(0); + lastChild.x = gutter; + lastChild.y = gutter; + for (var i:uint = 1; i < ln; i++) { + child = getChildAt(i); + child.x = gutter + lastChild.x + lastChild.width; + child.y = gutter; + lastChild = child; + } + } + + private function doDrawCircle():void { + var child:Shape = new Shape(); + var halfSize:uint = Math.round(size / 2); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawCircle(halfSize, halfSize, halfSize); + child.graphics.endFill(); + addChild(child); + } + + private function doDrawRoundRect():void { + var child:Shape = new Shape(); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawRoundRect(0, 0, size, size, cornerRadius); + child.graphics.endFill(); + addChild(child); + } + + private function doDrawRect():void { + var child:Shape = new Shape(); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + addChild(child); + } + } +} +
beginBitmapFill + Fills a drawing area with a bitmap image.bitmapflash.display:BitmapDataA transparent or opaque bitmap image that contains the bits to be displayed. + + matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to + define transformations on the bitmap. For example, you can use the following matrix + to rotate a bitmap by 45 degrees (pi/4 radians): + + + matrix = new flash.geom.Matrix(); + matrix.rotate(Math.PI / 4); + + + repeatBooleantrueIf true, the bitmap image repeats in a tiled pattern. If + false, the bitmap image does not repeat, and the edges of the bitmap are + used for any fill area that extends beyond the bitmap. + +

For example, consider the following bitmap (a 20 x 20-pixel checkerboard pattern):

+ +

+ +

When repeat is set to true (as in the following example), the bitmap fill + repeats the bitmap:

+ +

+ +

When repeat is set to false, the bitmap fill uses the edge + pixels for the fill area outside the bitmap:

+ +

+ + +
smoothBooleanfalseIf false, upscaled bitmap images are rendered by using a + nearest-neighbor algorithm and look pixelated. If true, upscaled + bitmap images are rendered by using a bilinear algorithm. Rendering by using the nearest + neighbor algorithm is faster. + + Begins a bitmap filled shape. + +
+ Fills a drawing area with a bitmap image. The bitmap can be repeated or tiled to fill + the area. The fill remains in effect until you call the beginFill(), + beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. + Calling the clear() method clears the fill. + +

The application renders the fill whenever three or more points are drawn, or when + the endFill() method is called.

+ +
The following example uses an image (image1.jpg) that is rotated and repeated to fill in a rectangle. + +
  1. The image file (image1.jpg) is loaded using the Loader and URLRequest objects. + Here the file is in the same directory as the SWF file. The SWF file needs to be compiled with Local Playback + Security set to Access Local Files Only.
  2. When the image is loaded (Event is complete), the drawImage() method is called. + The ioErrorHandler() method writes a trace comment if the image was not loaded properly.
  3. In drawImage() method, a BitmapData object is instantiated and its width and height + are set to the image (image1.jpg). Then the source image is drawn into the BitmapData + object. Next, a rectangle is drawn in the mySprite Sprite object and the BitmapData object is used to + fill it. Using a Matrix object, the beginBitmapFill() method rotates the image 45 degrees, + then it begins filling the rectangle with the image until it is finished.
+ +package { + import flash.display.Sprite; + import flash.display.BitmapData; + import flash.display.Loader; + import flash.net.URLRequest; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.geom.Matrix; + + public class Graphics_beginBitmapFillExample extends Sprite { + + private var url:String = "image1.jpg"; + private var loader:Loader = new Loader(); + + public function Graphics_beginBitmapFillExample() { + + var request:URLRequest = new URLRequest(url); + + loader.load(request); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function drawImage(event:Event):void { + + var mySprite:Sprite = new Sprite(); + var myBitmap:BitmapData = new BitmapData(loader.width, loader.height, false); + + myBitmap.draw(loader, new Matrix()); + + var matrix:Matrix = new Matrix(); + matrix.rotate(Math.PI/4); + + mySprite.graphics.beginBitmapFill(myBitmap, matrix, true); + mySprite.graphics.drawRect(100, 50, 200, 90); + mySprite.graphics.endFill(); + + addChild(mySprite); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load image: " + url); + } + } +} +
endFill()beginFill()beginGradientFill()
beginFill + Specifies a simple one-color fill that subsequent calls to other + Graphics methods (such as lineTo() or drawCircle()) use when drawing.coloruintThe color of the fill (0xRRGGBB). + alphaNumber1.0The alpha value of the fill (0.0 to 1.0). + + Specifies a single-color fill. + + + Specifies a simple one-color fill that subsequent calls to other + Graphics methods (such as lineTo() or drawCircle()) use when drawing. + The fill remains in effect until you call the beginFill(), + beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. + Calling the clear() method clears the fill. + +

The application renders the fill whenever three or more points are drawn, or when + the endFill() method is called.

+ +
Please see the example at the end of this + class for an illustration of how to use this method. + +
endFill()beginBitmapFill()beginGradientFill()
beginGradientFill + Specifies a gradient fill used by subsequent calls to other + Graphics methods (such as lineTo() or drawCircle()) for the object.If the type parameter is not valid. + + ArgumentErrorArgumentErrortypeStringA value from the GradientType class that + specifies which gradient type to use: GradientType.LINEAR or + GradientType.RADIAL. + + colorsArrayAn array of RGB hexadecimal color values used in the gradient; for example, + red is 0xFF0000, blue is 0x0000FF, and so on. You can specify up to 15 colors. + For each color, specify a corresponding value in the alphas and ratios parameters. + + alphasArrayAn array of alpha values for the corresponding colors in the colors array; + valid values are 0 to 1. If the value is less than 0, the default is 0. If the value is + greater than 1, the default is 1. + + ratiosArrayAn array of color distribution ratios; valid values are 0-255. This value + defines the percentage of the width where the color is sampled at 100%. The value 0 represents + the left position in the gradient box, and 255 represents the right position in the + gradient box. + +

Note: This value represents positions in the gradient box, not the + coordinate space of the final gradient, which can be wider or thinner than the gradient box. + Specify a value for each value in the colors parameter.

+ +

For example, for a linear gradient that includes two colors, blue and green, the + following example illustrates the placement of the colors in the gradient based on different values + in the ratios array:

+ + ratiosGradient[0, 127][0, 255][127, 255] + +

The values in the array must increase sequentially; for example, + [0, 63, 127, 190, 255].

+ +
matrixflash.geom:MatrixnullA transformation matrix as defined by the + flash.geom.Matrix class. The flash.geom.Matrix class includes a + createGradientBox() method, which lets you conveniently set up + the matrix for use with the beginGradientFill() method. + + spreadMethodStringpadA value from the SpreadMethod class that + specifies which spread method to use, either: SpreadMethod.PAD, + SpreadMethod.REFLECT, or SpreadMethod.REPEAT. + +

For example, consider a simple linear gradient between two colors:

+ + + import flash.geom.* + import flash.display.* + var fillType:String = GradientType.LINEAR; + var colors:Array = [0xFF0000, 0x0000FF]; + var alphas:Array = [1, 1]; + var ratios:Array = [0x00, 0xFF]; + var matr:Matrix = new Matrix(); + matr.createGradientBox(20, 20, 0, 0, 0); + var spreadMethod:String = SpreadMethod.PAD; + this.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); + this.graphics.drawRect(0,0,100,100); + + +

This example uses SpreadMethod.PAD for the spread method, and + the gradient fill looks like the following:

+ +

+ +

If you use SpreadMethod.REFLECT for the spread method, the gradient fill + looks like the following:

+ +

+ +

If you use SpreadMethod.REPEAT for the spread method, the gradient fill + looks like the following:

+ +

+ +
interpolationMethodStringrgbA value from the InterpolationMethod class that + specifies which value to use: InterpolationMethod.LINEAR_RGB or + InterpolationMethod.RGB + +

For example, consider a simple linear gradient between two colors (with the spreadMethod + parameter set to SpreadMethod.REFLECT). The different interpolation methods affect + the appearance as follows:

+ + InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB + +
focalPointRatioNumber0A number that controls the + location of the focal point of the gradient. 0 means that the focal point is in the center. 1 + means that the focal point is at one border of the gradient circle. -1 means that the focal point + is at the other border of the gradient circle. A value less than -1 or greater than + 1 is rounded to -1 or 1. For example, the following example + shows a focalPointRatio set to 0.75: + +

+ +
Specifies a gradient fill. + +
+ Specifies a gradient fill used by subsequent calls to other + Graphics methods (such as lineTo() or drawCircle()) for the object. + The fill remains in effect until you call the beginFill(), + beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. + Calling the clear() method clears the fill. + +

The application renders the fill whenever three or more points are drawn, or when + the endFill() method is called.

+ +
endFill()beginFill()beginBitmapFill()flash.geom.Matrix.createGradientBox()flash.display.GradientTypeflash.display.SpreadMethod
beginShaderFill + Specifies a shader fill used by subsequent calls to other Graphics methods + (such as lineTo() or drawCircle()) for the object.When the shader output type is not compatible with this operation + (the shader must specify a pixel3 or pixel4 + output). + + ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. + + ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as + an input and the width + and height properties aren't specified for the + ShaderInput, or the specified values don't match the amount of + data in the input object. See the ShaderInput.input + property for more information. + + ArgumentErrorArgumentErrorshaderflash.display:ShaderThe shader to use for the fill. This Shader instance is not required to + specify an image input. However, if an image input is specified in the shader, the input + must be provided manually. To specify the input, set the input property + of the corresponding ShaderInput + property of the Shader.data property. + +

When you pass a Shader instance as an argument the shader is copied internally. The + drawing fill operation uses that internal copy, not a reference to the original shader. Any changes + made to the shader, such as changing a parameter value, input, or bytecode, are not applied + to the copied shader that's used for the fill.

+ +
matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to + define transformations on the shader. For example, you can use the following matrix + to rotate a shader by 45 degrees (pi/4 radians): + + + matrix = new flash.geom.Matrix(); + matrix.rotate(Math.PI / 4); + + +

The coordinates received in the shader are based on the matrix that is specified + for the matrix parameter. For a default (null) matrix, the + coordinates in the shader are local pixel coordinates which can be used to sample an + input.

+ +
Specifies a shader fill. + +
+ Specifies a shader fill used by subsequent calls to other Graphics methods + (such as lineTo() or drawCircle()) for the object. + The fill remains in effect until you call the beginFill(), + beginBitmapFill(), beginGradientFill(), or beginShaderFill() method. + Calling the clear() method clears the fill. + +

The application renders the fill whenever three or more points are drawn, or when + the endFill() method is called.

+ +

Shader fills are not supported under GPU rendering; filled areas will be colored cyan.

+ +
endFill()beginFill()beginBitmapFill()beginGradientFill()flash.display.ShaderInput
clear + Clears the graphics that were drawn to this Graphics object, and resets fill and + line style settings. + Clears the graphics that were drawn to this Graphics object, and resets fill and + line style settings. + + copyFrom + Copies all of drawing commands from the source Graphics object into the + calling Graphics object.sourceGraphicsflash.display:GraphicsThe Graphics object from which to copy the drawing commands. + + + Copies all of drawing commands from the source Graphics object into the + calling Graphics object. + + curveTo + Draws a curve using the current line style from the current drawing position + to (anchorX, anchorY) and using the control point that (controlX, + controlY) specifies.controlXNumberA number that specifies the horizontal position of the control + point relative to the registration point of the parent display object. + controlYNumberA number that specifies the vertical position of the control + point relative to the registration point of the parent display object. + anchorXNumberA number that specifies the horizontal position of the next anchor + point relative to the registration point of the parent display object. + anchorYNumberA number that specifies the vertical position of the next anchor + point relative to the registration point of the parent display object. + + Draws a curve from the current drawing position + to (anchorX, anchorY) using the control point specified by (controlX, controlY). + + + + + Draws a curve using the current line style from the current drawing position + to (anchorX, anchorY) and using the control point that (controlX, + controlY) specifies. The current drawing position is then set to + (anchorX, anchorY). If the movie clip in which you are + drawing contains content created with the Flash drawing tools, calls to the + curveTo() method are drawn underneath this content. If you call the + curveTo() method before any calls to the moveTo() method, + the default of the current drawing position is (0, 0). If any of the parameters are + missing, this method fails and the current drawing position is not changed. + +

The curve drawn is a quadratic Bezier curve. Quadratic Bezier curves + consist of two anchor points and one control point. The curve interpolates the two anchor + points and curves toward the control point.

+ +

+ +
The following example draws a green circular object with a width and height of 100 + pixels, 250 pixels to the right from the registration point (0, 0) of Sprite display object. +

Draw four curves to produce a circle and fill it green.

+ +

Note that due to the nature of the quadratic Bezier equation, this is not a perfect circle. + The best way to draw a circle is to use the Graphics class's drawCircle() method.

+ +package { + import flash.display.Sprite; + import flash.display.Shape; + + public class Graphics_curveToExample1 extends Sprite + { + public function Graphics_curveToExample1():void + { + var roundObject:Shape = new Shape(); + + roundObject.graphics.beginFill(0x00FF00); + roundObject.graphics.moveTo(250, 0); + roundObject.graphics.curveTo(300, 0, 300, 50); + roundObject.graphics.curveTo(300, 100, 250, 100); + roundObject.graphics.curveTo(200, 100, 200, 50); + roundObject.graphics.curveTo(200, 0, 250, 0); + roundObject.graphics.endFill(); + + this.addChild(roundObject); + } + } +} +
The following example draws a new moon using curveTo() method. + +

Two curve lines of 1 pixel are drawn and the space in between is filled white. The moveTo() + method is used to position the current drawing position to coordinates (100, 100). The first curve moves the drawing + position to (100, 200), its destination point. The second curve returns the position back to + the starting position (100, 100), its destination point. The horizontal control points determine + the different curve sizes.

+ + +package { + import flash.display.Sprite; + import flash.display.Shape; + + public class Graphics_curveToExample2 extends Sprite + { + public function Graphics_curveToExample2() { + var newMoon:Shape = new Shape(); + + newMoon.graphics.lineStyle(1, 0); + newMoon.graphics.beginFill(0xFFFFFF); + newMoon.graphics.moveTo(100, 100); + newMoon.graphics.curveTo(30, 150, 100, 200); + newMoon.graphics.curveTo(50, 150, 100, 100); + graphics.endFill(); + + this.addChild(newMoon); + } + } +} +
drawCircle + Draws a circle.xNumberThe x location of the center of the circle relative to the + registration point of the parent display object (in pixels). + + yNumberThe y location of the center of the circle relative to the + registration point of the parent display object (in pixels). + + radiusNumberThe radius of the circle (in pixels). + + Draws a circle. + + + Draws a circle. Set the line style, fill, or both before + you call the drawCircle() method, by calling the linestyle(), + lineGradientStyle(), beginFill(), beginGradientFill(), + or beginBitmapFill() method. + + Please see the example at the end of this + class for an illustration of how to use this method. + + drawEllipse()lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawEllipse + Draws an ellipse.xNumberThe x location of the top-left of the bounding-box of the ellipse relative to the + registration point of the parent display object (in pixels). + + yNumberThe y location of the top left of the bounding-box of the ellipse relative to the + registration point of the parent display object (in pixels). + + widthNumberThe width of the ellipse (in pixels). + + heightNumberThe height of the ellipse (in pixels). + + Draws an ellipse. + + + Draws an ellipse. Set the line style, fill, or both before + you call the drawEllipse() method, by calling the linestyle(), + lineGradientStyle(), beginFill(), beginGradientFill(), + or beginBitmapFill() method. + + The following example uses the function drawEgg() to draw three different sized eggs + (three sizes of ellipses), depending on the eggSize parameter. +
  1. The constructor calls the function drawEgg() and passes the horizontal and vertical parameters for + where the egg should be drawn, plus the type of egg (eggSize). (The height and width of the + eggs (the ellipses) can be used to decide where to display them.)
  2. Function drawEgg() draws the different size ellipses and fills them white using + beginFill() method. There is no advance error handling written for his function.
+ + +package { + import flash.display.Sprite; + import flash.display.Shape; + + public class Graphics_drawEllipseExample extends Sprite + { + public static const SMALL:uint = 0; + public static const MEDIUM:uint = 1; + public static const LARGE:uint = 2; + + public function Graphics_drawEllipseExample() + { + drawEgg(SMALL, 0, 100); + drawEgg(MEDIUM, 100, 60); + drawEgg(LARGE, 250, 35); + } + + public function drawEgg(eggSize:uint, x:Number, y:Number):void { + + var myEgg:Shape = new Shape(); + + myEgg.graphics.beginFill(0xFFFFFF); + myEgg.graphics.lineStyle(1); + + switch(eggSize) { + case SMALL: + myEgg.graphics.drawEllipse(x, y, 60, 70); + break; + case MEDIUM: + myEgg.graphics.drawEllipse(x, y, 120, 150); + break; + case LARGE: + myEgg.graphics.drawEllipse(x, y, 150, 200); + break; + default: + trace ("Wrong size! There is no egg."); + break; + } + + myEgg.graphics.endFill(); + + this.addChild(myEgg); + } + } +} +
drawCircle()lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()
drawGraphicsData + Submits a series of IGraphicsData instances for drawing.graphicsDataA Vector containing graphics objects, each of which much implement the IGraphicsData interface. + + + Submits a series of IGraphicsData instances for drawing. This method accepts a Vector containing objects + including paths, fills, and strokes + that implement the IGraphicsData interface. A + Vector of IGraphicsData instances can refer to a part of a shape, or a complex fully defined + set of data for rendering a complete shape. + + +

+ Graphics paths can contain other graphics paths. If the graphicsData Vector + includes a path, that path and all its sub-paths are rendered during this operation. +

+ +
The following example creates a GraphicsGradientFill object to establish the fill properties + for a square. Then, the example creates a GraphicsStroke object (for the line thickness) class and a GraphicsSolidFill + object (for the line color) to set the properties for the border line of the square. The example then creates a + GraphicsPath object to contain the values for drawing the shape. All of these objects are stored in an IGraphicsData object, + and passed to the drawGraphicsData() command to render the shape. + +package{ + import flash.display.*; + import flash.geom.*; + + public class DrawGraphicsDataExample extends Sprite { + + public function DrawGraphicsDataExample(){ + + // establish the fill properties + var myFill:GraphicsGradientFill = new GraphicsGradientFill(); + myFill.colors = [0xEEFFEE, 0x0000FF]; + myFill.matrix = new Matrix(); + myFill.matrix.createGradientBox(100, 100, 0); + + // establish the stroke properties + var myStroke:GraphicsStroke = new GraphicsStroke(2); + myStroke.fill = new GraphicsSolidFill(0x000000); + + // establish the path properties + var myPath:GraphicsPath = new GraphicsPath(new Vector.<int>(), new Vector.<Number>()); + myPath.commands.push(1,2,2,2,2); + myPath.data.push(10,10, 10,100, 100,100, 100,10, 10,10); + + // populate the IGraphicsData Vector array + var myDrawing:Vector.<IGraphicsData> = new Vector.<IGraphicsData>(); + myDrawing.push(myFill, myStroke, myPath); + + // render the drawing + graphics.drawGraphicsData(myDrawing); + } + } +} +
flash.display.IGraphicsDataflash.display.GraphicsBitmapFillflash.display.GraphicsEndFillflash.display.GraphicsGradientFillflash.display.GraphicsPathflash.display.GraphicsShaderFillflash.display.GraphicsSolidFillflash.display.GraphicsStrokeflash.display.GraphicsTrianglePath
drawPath + Submits a series of commands for drawing.commandsA Vector of integers representing commands defined by the GraphicsPathCommand class. The + GraphicsPathCommand class maps commands to numeric identifiers for this vector array. + dataA Vector of Numbers where each pair of numbers is treated as a coordinate location (an x, y pair). + The x- and y-coordinate value pairs are not Point objects; the data vector is + a series of numbers where each group of two numbers represents a coordinate location. + windingStringevenOddSpecifies the winding rule using a value defined in the GraphicsPathWinding class. + + + Submits a series of commands for drawing. The drawPath() method uses vector arrays to consolidate + individual moveTo(), lineTo(), and curveTo() drawing commands + into a single call. The drawPath() method parameters combine drawing commands with x- and y-coordinate + value pairs and a drawing direction. The drawing commands are values from the GraphicsPathCommand class. The + x- and y-coordinate value pairs are Numbers in an array where each pair defines a coordinate location. The drawing + direction is a value from the GraphicsPathWinding class. + +

+ Generally, drawings render faster with drawPath() than with + a series of individual lineTo() and curveTo() methods. +

+ +

+ The drawPath() method uses a uses a floating computation so rotation and scaling + of shapes is more accurate and gives better results. However, curves submitted using the + drawPath() method can have small sub-pixel alignment errors when used in conjunction + with the lineTo() and curveTo() methods. +

+ +

+ The drawPath() method also uses slightly different rules for filling and drawing lines. + They are: +

+ +
  • When a fill is applied to rendering a path: +
    • A sub-path of less than 3 points is not rendered. (But note that the stroke rendering will + still occur, consistent with the rules for strokes below.)
    • A sub-path that isn't closed (the end point is not equal to the begin point) is implicitly + closed.
    +
  • When a stroke is applied to rendering a path: +
    • The sub-paths can be composed of any number of points.
    • The sub-path is never implicitly closed.
    +
+ +
The following example populates two Vector objects, then passes them to the + drawPath() method to render a blue star. The first Vector, star_commands, contains a series of + integers representing drawing commands from the flash.display.GraphicsPathCommand class, + where the value 1 is a MoveTo() command and the value 2 is a LineTo() + command. The second Vector, star_coord, contains 5 sets of x- and y-coordinate pairs. + The drawPath() method matches the commands with the positions to draw a star. + +package{ + import flash.display.*; + + public class DrawPathExample extends Sprite { + + public function DrawPathExample(){ + + var star_commands:Vector.<int> = new Vector.<int>(5, true); + + star_commands[0] = 1; + star_commands[1] = 2; + star_commands[2] = 2; + star_commands[3] = 2; + star_commands[4] = 2; + + var star_coord:Vector.<Number> = new Vector.<Number>(10, true); + star_coord[0] = 66; //x + star_coord[1] = 10; //y + star_coord[2] = 23; + star_coord[3] = 127; + star_coord[4] = 122; + star_coord[5] = 50; + star_coord[6] = 10; + star_coord[7] = 49; + star_coord[8] = 109; + star_coord[9] = 127; + + + graphics.beginFill(0x003366); + graphics.drawPath(star_commands, star_coord); + + } + + } +} + + In the above example, each command and coordinate pair is assigned individually to show their position in the array, + but they can be assigned in a single statement. The following example draws the same star by assigning the values for each array in a single + push() statement: + +package{ + import flash.display.*; + + public class DrawPathExample extends Sprite { + public function DrawPathExample(){ + var star_commands:Vector.<int> = new Vector.<int>(); + star_commands.push(1, 2, 2, 2, 2); + + var star_coord:Vector.<Number> = new Vector.<Number>(); + star_coord.push(66,10, 23,127, 122,50, 10,49, 109,127); + + graphics.beginFill(0x003366); + graphics.drawPath(star_commands, star_coord); + } + } +} + + + Note: By default, the drawPath() method uses the even-odd winding type. So, + the center of the star is not filled. Specify the non-zero winding type for the third parameter + and it fills the center of the star: + + graphics.drawPath(star_commands, star_coord, GraphicsPathWinding.NON_ZERO); + + +
flash.display.GraphicsPathCommandflash.display.GraphicsPathWinding
drawRect + Draws a rectangle.If the width or height parameters + are not a number (Number.NaN). + + ArgumentErrorArgumentErrorxNumberA number indicating the horizontal position relative to the + registration point of the parent display object (in pixels). + + yNumberA number indicating the vertical position relative to the + registration point of the parent display object (in pixels). + + widthNumberThe width of the rectangle (in pixels). + + heightNumberThe height of the rectangle (in pixels). + + Draws a round rectangle. + + + Draws a rectangle. Set the line style, fill, or both before + you call the drawRect() method, by calling the linestyle(), + lineGradientStyle(), beginFill(), beginGradientFill(), + or beginBitmapFill() method. + + The following example shows how you can draw shapes in ActionScript 3.0. + Example provided by + ActionScriptExamples.com. + +var movieClip:MovieClip = new MovieClip(); +movieClip.graphics.beginFill(0xFF0000); +movieClip.graphics.drawRect(0, 0, 100, 80); +movieClip.graphics.endFill(); +movieClip.x = 10; +movieClip.y = 10; +addChild(movieClip); +lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawRoundRect()drawRoundRect + Draws a rounded rectangle.If the width, height, ellipseWidth + or ellipseHeight parameters are not a number (Number.NaN). + + ArgumentErrorArgumentErrorxNumberA number indicating the horizontal position relative to the + registration point of the parent display object (in pixels). + + yNumberA number indicating the vertical position relative to the + registration point of the parent display object (in pixels). + + widthNumberThe width of the round rectangle (in pixels). + + heightNumberThe height of the round rectangle (in pixels). + + ellipseWidthNumberThe width of the ellipse used to draw the rounded corners (in pixels). + + ellipseHeightNumberunknownThe height of the ellipse used to draw the rounded corners (in pixels). + Optional; if no value is specified, the default value matches that provided for the + ellipseWidth parameter. + + Draws a round rectangle. + + + Draws a rounded rectangle. Set the line style, fill, or both before + you call the drawRoundRect() method, by calling the linestyle(), + lineGradientStyle(), beginFill(), beginGradientFill(), or + beginBitmapFill() method. + + Please see the example at the end of this + class for an illustration of how to use this method. + + lineStyle()lineGradientStyle()beginFill()beginGradientFill()beginBitmapFill()drawRect()drawTriangles + Renders a set of triangles, typically to distort bitmaps and give them a three-dimensional appearance.verticesA Vector of Numbers where each pair of numbers is treated as a coordinate location (an x, y pair). The + vertices parameter is required. + + indicesnullA Vector of integers or indexes, where every three indexes define a triangle. If the indexes parameter + is null then every three vertices (six x,y pairs in the vertices Vector) defines a triangle. + Otherwise each index refers to a vertex, which is a pair of numbers in the vertices Vector. + For example indexes[1] refers to (vertices[2], vertices[3]). + The indexes parameter is optional, but indexes generally reduce the amount of data submitted + and the amount of data computed. + + uvtDatanullA Vector of normalized coordinates used to apply texture mapping. + Each coordinate refers to a point on the bitmap used for the fill. + You must have one UV or one UVT coordinate per vertex. + In UV coordinates, (0,0) is the upper left of the bitmap, and (1,1) is the lower right of the bitmap. +

If the length of this vector is twice the length of the vertices vector then normalized + coordinates are used without perspective correction.

+

If the length of this vector is three times the length of the vertices vector then the + third coordinate is interpreted as 't' (the distance from the eye to the texture in eye space). + This helps the rendering engine correctly apply perspective when mapping textures in three dimensions.

+

If the uvtData parameter is null, then normal fill rules (and any fill type) apply.

+ +
cullingStringnoneSpecifies whether to render triangles that face in a specified direction. This parameter prevents + the rendering of triangles that cannot be seen in the current view. + This parameter can be set to any value defined by the TriangleCulling class. + +
+ Renders a set of triangles, typically to distort bitmaps and give them a three-dimensional appearance. The + drawTriangles() method maps either the current fill, or a bitmap fill, to the + triangle faces using a set of (u,v) coordinates. +

+ Any type of fill can be used, but if the fill has a transform matrix that + transform matrix is ignored. +

+ +

+ A uvtData parameter improves texture mapping when a bitmap fill is used. +

+ +
flash.display.TriangleCullingflash.display.GraphicsTrianglePath
endFill + Applies a fill to the lines and curves that were added since the last call to the + beginFill(), beginGradientFill(), or + beginBitmapFill() method.Applies a fill to the lines and curves. + + Applies a fill to the lines and curves that were added since the last call to the + beginFill(), beginGradientFill(), or + beginBitmapFill() method. Flash uses the fill that was specified in the previous + call to the beginFill(), beginGradientFill(), or beginBitmapFill() + method. If the current drawing position does not equal the previous position specified in a + moveTo() method and a fill is defined, the path is closed with a line and then + filled. + + beginFill()beginBitmapFill()beginGradientFill()lineBitmapStyle + Specifies a bitmap to use for the line stroke when drawing lines.bitmapflash.display:BitmapDataThe bitmap to use for the line stroke. + + matrixflash.geom:MatrixnullAn optional transformation matrix as defined by the flash.geom.Matrix class. + The matrix can be used to scale or otherwise manipulate the bitmap before + applying it to the line style. + + repeatBooleantrueWhether to repeat the bitmap in a tiled fashion. + + smoothBooleanfalseWhether smoothing should be applied to the bitmap. + + + Specifies a bitmap to use for the line stroke when drawing lines. + +

The bitmap line style is used for subsequent calls to Graphics + methods such as the lineTo() method or the drawCircle() method. + The line style remains in effect until you call the lineStyle() or + lineGradientStyle() methods, or the lineBitmapStyle() method + again with different parameters.

+ +

You can call the lineBitmapStyle() method in the middle of drawing a path + to specify different styles for different line segments within a path.

+ +

Call the lineStyle() method before you call the + lineBitmapStyle() method to enable a stroke, or else the value of the line style + is undefined.

+ +

Calls to the clear() method set the line style back to undefined. +

+ +
lineStyle()lineGradientStyle()flash.geom.Matrix
lineGradientStyle + Specifies a gradient to use for the stroke when drawing lines.typeStringA value from the GradientType class that + specifies which gradient type to use, either GradientType.LINEAR or GradientType.RADIAL. + + colorsArrayAn array of RGB hex color values to be used in the gradient (for example, + red is 0xFF0000, blue is 0x0000FF, and so on). + + alphasArrayAn array of alpha values for the corresponding colors in the colors array; + valid values are 0 to 1. If the value is less than 0, the default is 0. If the value is + greater than 1, the default is 1. + + ratiosArrayAn array of color distribution ratios; valid values are from 0 to 255. This value + defines the percentage of the width where the color is sampled at 100%. The value 0 represents + the left position in the gradient box, and 255 represents the right position in the + gradient box. This value represents positions in the gradient box, not the + coordinate space of the final gradient, which can be wider or thinner than the gradient box. + Specify a value for each value in the colors parameter. + +

For example, for a linear gradient that includes two colors, blue and green, the + following figure illustrates the placement of the colors in the gradient based on different values + in the ratios array:

+ + ratiosGradient[0, 127][0, 255][127, 255] + +

The values in the array must increase, sequentially; for example, + [0, 63, 127, 190, 255].

+ + +
matrixflash.geom:MatrixnullA transformation matrix as defined by the + flash.geom.Matrix class. The flash.geom.Matrix class includes a + createGradientBox() method, which lets you conveniently set up + the matrix for use with the lineGradientStyle() method. + + spreadMethodStringpadA value from the SpreadMethod class that + specifies which spread method to use: + +

+ SpreadMethod.PADSpreadMethod.REFLECTSpreadMethod.REPEAT +

+ +
interpolationMethodStringrgbA value from the InterpolationMethod class that + specifies which value to use. For example, consider a simple linear gradient between two colors (with the spreadMethod + parameter set to SpreadMethod.REFLECT). The different interpolation methods affect + the appearance as follows: + +

+ InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB +

+ +
focalPointRatioNumber0A number that controls the location of the focal + point of the gradient. The value 0 means the focal point is in the center. The value 1 means the focal + point is at one border of the gradient circle. The value -1 means that the focal point is + at the other border of the gradient circle. Values less than -1 or greater than 1 are + rounded to -1 or 1. The following image shows a gradient with a + focalPointRatio of -0.75: + +

+ +
+ Specifies a gradient to use for the stroke when drawing lines. + +

The gradient line style is used for subsequent calls to Graphics + methods such as the lineTo() methods or the drawCircle() method. + The line style remains in effect until you call the lineStyle() or + lineBitmapStyle() methods, or the lineGradientStyle() method + again with different parameters.

+ +

You can call the lineGradientStyle() method in the middle of drawing a path + to specify different styles for different line segments within a path.

+ +

Call the lineStyle() method before you call the + lineGradientStyle() method to enable a stroke, or else the value of the line style + is undefined.

+ +

Calls to the clear() method set the line style back to undefined. +

+ +
The following example draws a rectangle and a circle that use + a gradient stroke from red to green to blue. + +

The method createGradientBox() from the Matrix class is used to define the + gradient box to 200 width and 40 height. The thickness of line is set to 5 pixels. Thickness of the stroke + must be defined for lineGradientStyle() method. The gradient is set to linear. Colors for the + gradient are set to red, green, and blue. Transparency (alpha value) for the colors is set to 1 (opaque). + The distribution of gradient is even, where the colors are sampled at 100% at 0 (left-hand position in the + gradient box), 128 (middle in the box) and 255 (right-hand position in the box). The width of the rectangle + encompasses all the spectrum of the gradient, while the circle encompasses 50% from the middle of the spectrum.

+ + +package { + import flash.display.Sprite; + import flash.display.Shape; + import flash.geom.Matrix; + import flash.display.GradientType; + + public class Graphics_lineGradientStyleExample extends Sprite + { + public function Graphics_lineGradientStyleExample() + { + var myShape:Shape = new Shape(); + var gradientBoxMatrix:Matrix = new Matrix(); + + gradientBoxMatrix.createGradientBox(200, 40, 0, 0, 0); + + myShape.graphics.lineStyle(5); + + myShape.graphics.lineGradientStyle(GradientType.LINEAR, [0xFF0000, + 0x00FF00, 0x0000FF], [1, 1, 1], [0, 128, 255], gradientBoxMatrix); + + myShape.graphics.drawRect(0, 0, 200, 40); + myShape.graphics.drawCircle(100, 120, 50); + + this.addChild(myShape); + + } + } +} +
lineStyle()lineBitmapStyle()flash.geom.Matrix.createGradientBox()flash.display.GradientTypeflash.display.SpreadMethod
lineShaderStyle + Specifies a shader to use for the line stroke when drawing lines.shaderflash.display:ShaderThe shader to use for the line stroke. + + matrixflash.geom:MatrixnullAn optional transformation matrix as defined by the flash.geom.Matrix class. + The matrix can be used to scale or otherwise manipulate the bitmap before + applying it to the line style. + + + Specifies a shader to use for the line stroke when drawing lines. + +

The shader line style is used for subsequent calls to Graphics + methods such as the lineTo() method or the drawCircle() method. + The line style remains in effect until you call the lineStyle() or + lineGradientStyle() methods, or the lineBitmapStyle() method + again with different parameters.

+ +

You can call the lineShaderStyle() method in the middle of drawing a path + to specify different styles for different line segments within a path.

+ +

Call the lineStyle() method before you call the + lineShaderStyle() method to enable a stroke, or else the value of the line style + is undefined.

+ +

Calls to the clear() method set the line style back to undefined. +

+ +
lineStyle()lineBitmapStyle()flash.geom.Matrix
lineStyle + Specifies a line style used for subsequent calls to + Graphics methods such as the lineTo() method or the drawCircle() method.thicknessNumberunknownAn integer that indicates the thickness of the line in + points; valid values are 0-255. If a number is not specified, or if the + parameter is undefined, a line is not drawn. If a value of less than 0 is passed, + the default is 0. The value 0 indicates hairline thickness; the maximum thickness + is 255. If a value greater than 255 is passed, the default is 255. + + coloruint0A hexadecimal color value of the line; for example, red is 0xFF0000, blue is + 0x0000FF, and so on. If a value is not indicated, the default is 0x000000 (black). Optional. + + + alphaNumber1.0A number that indicates the alpha value of the color of the line; + valid values are 0 to 1. If a value is not indicated, the default is 1 (solid). If + the value is less than 0, the default is 0. If the value is greater than 1, the default is 1. + + + pixelHintingBooleanfalse(Not supported in Flash Lite 4) A Boolean value that specifies whether to hint strokes + to full pixels. This affects both the position of anchors of a curve and the line stroke size + itself. With pixelHinting set to true, line widths are adjusted + to full pixel widths. With pixelHinting set to false, disjoints can + appear for curves and straight lines. For example, the following illustrations show how + Flash Player or Adobe AIR renders two rounded rectangles that are identical, except that the + pixelHinting parameter used in the lineStyle() method is set + differently (the images are scaled by 200%, to emphasize the difference): + +

+ +

If a value is not supplied, the line does not use pixel hinting.

+ +
scaleModeStringnormal(Not supported in Flash Lite 4) A value from the LineScaleMode class that + specifies which scale mode to use: + +
  • + LineScaleMode.NORMAL—Always scale the line thickness when the object is scaled + (the default). +
  • + LineScaleMode.NONE—Never scale the line thickness. +
  • + LineScaleMode.VERTICAL—Do not scale the line thickness if the object is scaled vertically + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left + is scaled vertically only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
  • + LineScaleMode.HORIZONTAL—Do not scale the line thickness if the object is scaled horizontally + only. For example, consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left + is scaled horizontally only, and the circle on the right is scaled both vertically and horizontally: + +

    + +
+ + +
capsStringnull(Not supported in Flash Lite 4) A value from the CapsStyle class that specifies the type of caps at the end + of lines. Valid values are: CapsStyle.NONE, CapsStyle.ROUND, and CapsStyle.SQUARE. + If a value is not indicated, Flash uses round caps. +

For example, the following illustrations show the different capsStyle + settings. For each setting, the illustration shows a blue line with a thickness of 30 (for + which the capsStyle applies), and a superimposed black line with a thickness of 1 + (for which no capsStyle applies): +

+

+ +
jointsStringnull(Not supported in Flash Lite 4) A value from the JointStyle class that specifies the type of joint appearance + used at angles. Valid + values are: JointStyle.BEVEL, JointStyle.MITER, and JointStyle.ROUND. + If a value is not indicated, Flash uses round joints. + +

For example, the following illustrations show the different joints + settings. For each setting, the illustration shows an angled blue line with a thickness of + 30 (for which the jointStyle applies), and a superimposed angled black line with a + thickness of 1 (for which no jointStyle applies): +

+ +

+ +

Note: For joints set to JointStyle.MITER, + you can use the miterLimit parameter to limit the length of the miter.

+ +
miterLimitNumber3(Not supported in Flash Lite 4) A number that indicates the limit at which a miter is cut off. + Valid values range from 1 to 255 (and values outside that range are rounded to 1 or 255). + This value is only used if the jointStyle + is set to "miter". The + miterLimit value represents the length that a miter can extend beyond the point + at which the lines meet to form a joint. The value expresses a factor of the line + thickness. For example, with a miterLimit factor of 2.5 and a + thickness of 10 pixels, the miter is cut off at 25 pixels. + +

For example, consider the following angled lines, each drawn with a thickness + of 20, but with miterLimit set to 1, 2, and 4. Superimposed are black reference + lines showing the meeting points of the joints:

+ +

+ +

Notice that a given miterLimit value has a specific maximum angle + for which the miter is cut off. The following table lists some examples:

+ + miterLimit value:Angles smaller than this are cut off:1.41490 degrees260 degrees430 degrees815 degrees + +
Specifies a line style that Flash uses for drawing lines. + + +
+ Specifies a line style used for subsequent calls to + Graphics methods such as the lineTo() method or the drawCircle() method. + The line style remains in effect until you call the lineGradientStyle() + method, the lineBitmapStyle() method, or the lineStyle() method with different parameters. + +

You can call the lineStyle() method in the middle of drawing a path to specify different + styles for different line segments within the path.

+ +

Note: Calls to the clear() method set the line style back to + undefined.

+ +

Note: Flash Lite 4 supports only the first three parameters (thickness, color, and alpha).

+ +
Please see the lineTo() or moveTo() + method's example for illustrations of how to use the getStyle() method. + +
lineBitmapStyle()lineGradientStyle()LineScaleModeCapsStyleJointStyle
lineTo + Draws a line using the current line style from the current drawing position to (x, y); + the current drawing position is then set to (x, y).xNumberA number that indicates the horizontal position relative to the + registration point of the parent display object (in pixels). + + yNumberA number that indicates the vertical position relative to the + registration point of the parent display object (in pixels). + + + Draws a line from the current drawing position to (x, y). + + + Draws a line using the current line style from the current drawing position to (x, y); + the current drawing position is then set to (x, y). + If the display object in which you are drawing contains content that was created with + the Flash drawing tools, calls to the lineTo() method are drawn underneath the content. If + you call lineTo() before any calls to the moveTo() method, the + default position for the current drawing is (0, 0). If any of the parameters are missing, this + method fails and the current drawing position is not changed. + + The following example draws a trapezoid using lineTo() method, starting at + pixels (100, 100). +

The line thickness is set to 10 pixels, color is gold and opaque, caps at the end of lines + is set to none (since all lines are jointed), and the joint between the lines is set to + MITER with miter limit set to 10, to have sharp, pointed corners.

+ +package { + import flash.display.Sprite; + import flash.display.LineScaleMode; + import flash.display.CapsStyle; + import flash.display.JointStyle; + import flash.display.Shape; + + + public class Graphics_lineToExample extends Sprite { + + public function Graphics_lineToExample() { + + var trapezoid:Shape = new Shape(); + + trapezoid.graphics.lineStyle(10, 0xFFD700, 1, false, LineScaleMode.VERTICAL, + CapsStyle.NONE, JointStyle.MITER, 10); + + trapezoid.graphics.moveTo(100, 100); + + trapezoid.graphics.lineTo(120, 50); + trapezoid.graphics.lineTo(200, 50); + trapezoid.graphics.lineTo(220, 100); + trapezoid.graphics.lineTo(100, 100); + + this.addChild(trapezoid); + } + } +} +
moveTo + Moves the current drawing position to (x, y).xNumberA number that indicates the horizontal position relative to the + registration point of the parent display object (in pixels). + + yNumberA number that indicates the vertical position relative to the + registration point of the parent display object (in pixels). + + Moves the current drawing position to (x, y). + + + Moves the current drawing position to (x, y). If any of the parameters + are missing, this method fails and the current drawing position is not changed. + + The following example draws a dashed line of three pixels thickness + using moveTo() and lineTo() methods. + +

Using the lineStyle() method, the line thickness is set to 3 pixels. It is also set not + to scale. Color is set to red with 25 percent opacity. The CapsStyle property is set to + square (the default is round).

+ +

Since Graphics_moveToExample is an instance of the Sprite class, it has access + to all the Graphics class methods. The Graphics class methods can be used to directly draw on the + Graphic_moveToExample Sprite object. However, not putting the vector drawing object in a + Shape limits the way they can be managed, moved, or changed.

+ + +package { + import flash.display.Sprite; + import flash.display.CapsStyle; + import flash.display.LineScaleMode; + + public class Graphics_moveToExample extends Sprite + { + public function Graphics_moveToExample() { + + graphics.lineStyle(3, 0x990000, 0.25, false, + LineScaleMode.NONE, CapsStyle.SQUARE); + + graphics.moveTo(10, 20); + graphics.lineTo(20, 20); + graphics.moveTo(30, 20); + graphics.lineTo(50, 20); + graphics.moveTo(60, 20); + graphics.lineTo(80, 20); + graphics.moveTo(90, 20); + graphics.lineTo(110, 20); + graphics.moveTo(120, 20); + graphics.lineTo(130, 20); + } + } +} +
NativeWindowType + The NativeWindowType class defines constants for the type property of the + NativeWindowInitOptions object used to create a native window.Defines constants for the supported window types. + Object + The NativeWindowType class defines constants for the type property of the + NativeWindowInitOptions object used to create a native window. + +

Note: The type value is specified when a window is + created and cannot be changed.

+ +
flash.display.NativeWindowflash.display.NativeWindowInitOptionsLIGHTWEIGHT + A minimal window.lightweightString + A minimal window. + + NORMAL + A typical window.normalString + A typical window. + + UTILITY + A utility window.utilityString + A utility window. + +
StageAspectRatio + The StageAspectRatio class provides values for the Stage.setAspectRatio() method.Object + The StageAspectRatio class provides values for the Stage.setAspectRatio() method. + + flash.display.Stage.setAspectRatio()LANDSCAPE + Specifies a device orientation that presents a landscape UI + + landscapeString + Specifies a device orientation that presents a landscape UI + + PORTRAIT + Specifies a device orientation that presents a portrait UI + + portraitString + Specifies a device orientation that presents a portrait UI + + Screen + The Screen class provides information about the display screens available to this application.flash.events:EventDispatcher + The Screen class provides information about the display screens available to this application. + +

Screens are independent desktop areas within a possibly larger + "virtual desktop." The origin of the virtual desktop is the top-left corner + of the operating-system-designated main screen. Thus, the coordinates for the + bounds of an individual display screen may be negative. There may also be areas + of the virtual desktop that are not within any of the display screens.

+ +

The Screen class includes static class members for accessing the available + screen objects and instance members for accessing the properties of an + individual screen. Screen information should not be cached since + it can be changed by a user at any time.

+ +

Note that there is not necessarily a one-to-one correspondance between + screens and the physical monitors attached to a computer. For example, two monitors + may display the same screen.

+ +

You cannot instantiate the Screen class directly. Calls to + the new Screen() constructor throw an + ArgumentError exception.

+ +
The following example defines a DockingWindow class + to create a window that docks to the sides of the screen. + This task is accomplished by performing the following steps: + +
  1. Responding to keyboard events to determine the side of the screen on which to + dock.
  2. Accessing the static Screen class method getScreensForRectangle() + to get the Screen object for the screen upon which the window is currently + displayed.
  3. Resetting the window bounds based on the screen dimensions.
  4. Redrawing the window content based on the new window dimensions.
+ +

Note, this class is intended to be used as the root class of an AIR application + with the settings SystemChrome="none" and + transparent="true". To use this class in a window with system + chrome, you must take the chrome thickness and the minimum width of + the window into account when calculating window location and size.

+ + +package +{ + import flash.display.Screen; + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.KeyboardEvent; + import flash.geom.Rectangle; + import flash.ui.Keyboard; + + public class DockingWindow extends Sprite + { + private const dockedWidth:uint = 80; + private const dockedHeight:uint = 80; + + public function DockingWindow():void{ + stage.align = StageAlign.TOP_LEFT; + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.addEventListener(KeyboardEvent.KEY_DOWN,onKey); + dockLeft(); + } + + private function onKey(event:KeyboardEvent):void{ + switch(event.keyCode){ + case Keyboard.LEFT : + dockLeft(); + break; + case Keyboard.RIGHT : + dockRight(); + break; + case Keyboard.UP : + dockTop(); + break; + case Keyboard.DOWN : + dockBottom(); + break; + case Keyboard.SPACE : + stage.nativeWindow.close(); + } + } + + public function dockLeft():void{ + var screen:Screen = getCurrentScreen(); + stage.nativeWindow.x = screen.visibleBounds.left; + stage.nativeWindow.y = screen.visibleBounds.top; + stage.nativeWindow.height = screen.visibleBounds.height; + stage.stageWidth = dockedWidth; + drawContent(); + } + + public function dockRight():void{ + var screen:Screen = getCurrentScreen(); + stage.nativeWindow.x = screen.visibleBounds.width - dockedWidth; + stage.nativeWindow.y = screen.visibleBounds.top; + stage.stageWidth = dockedWidth; + stage.nativeWindow.height = screen.visibleBounds.height; + drawContent(); + } + + public function dockTop():void{ + var screen:Screen = getCurrentScreen(); + stage.nativeWindow.x = screen.visibleBounds.left; + stage.nativeWindow.y = screen.visibleBounds.top; + stage.nativeWindow.width = screen.visibleBounds.width; + stage.stageHeight = dockedHeight; + drawContent(); + } + + public function dockBottom():void{ + var screen:Screen = getCurrentScreen(); + stage.nativeWindow.x = screen.visibleBounds.left; + stage.nativeWindow.y = screen.visibleBounds.height - dockedHeight; + stage.nativeWindow.width = screen.visibleBounds.width; + stage.stageHeight = dockedHeight; + drawContent(); + } + + private function getCurrentScreen():Screen{ + return Screen.getScreensForRectangle(stage.nativeWindow.bounds)[0]; + } + + private function drawContent():void{ + const size:int = 60; + const pad:int = 10; + var numHSquares:int = Math.floor(stage.stageWidth/(size + pad)); + var numVSquares:int = Math.floor(stage.stageHeight/(size + pad)); + with (graphics){ + clear(); + lineStyle(1); + beginFill(0x3462d5,.7); + for(var i:int = 0; i < numHSquares; i++){ + for(var j:int = 0; j < numVSquares; j++){ + drawRect((i * (size + pad)) + pad, (j * (size + pad)) + pad, size, size); + } + } + endFill(); + } + } + } +} +
getScreensForRectangle + Returns the (possibly empty) set of screens that intersect + the provided rectangle.An array of Screen objects containing the screens that contain any + part of the area defined by the rect parameter. + + Arrayrectflash.geom:RectangleA rectangle with coordinates relative to the origin of + the virtual desktop, which is the top-left corner of the primary + screen. + + + Returns the (possibly empty) set of screens that intersect + the provided rectangle. + + The following example shows how to get the array of screens containing + at least part of a given rectangle: + +import flash.display.Screen; +import flash.geom.Rectangle; + +var rect:Rectangle = new Rectangle(-200, 100, 1000, 600); +var intersectedScreens:Array = Screen.getScreensForRectangle(rect); +bounds + The bounds of this screen.flash.geom:Rectangle + The bounds of this screen. + +

The screen location is relative to the virtual desktop.

+ +

On Linux systems that use certain window managers, this property returns + the desktop bounds, not the screen's visible bounds.

+ +
The following example shows how to get the bounds of a screen + (in this case, the primary display screen): + +import flash.display.Screen; +import flash.geom.Rectangle; + +var mainScreen:Screen = Screen.mainScreen; +var screenBounds:Rectangle = mainScreen.bounds; +
colorDepth + The color depth of this screen (expressed in number of bits).int + The color depth of this screen (expressed in number of bits). + + The following example shows how to get the color depth of a screen + (in this case, the primary display screen): + + +var mainScreen:Screen = Screen.mainScreen; +var colors:uint = mainScreen.colorDepth; +mainScreen + The primary display.flash.display:Screen + The primary display. + + The following example shows how to get the Screen object representing the + "main" screen of this computer: + + +var primaryScreen:Screen = Screen.mainScreen; +screens + The array of the currently available screens.Array + The array of the currently available screens. + +

Modifying the returned array has no effect on + the available screens.

+ +
The following example shows how to get the array containing the available screens: + + +var screenArray:Array = Screen.screens; +
visibleBounds + The bounds of the area on this screen in which windows can be visible.flash.geom:Rectangle + The bounds of the area on this screen in which windows can be visible. + +

The visibleBounds of a screen excludes the task bar + (and other docked desk bars) on Windows, and excludes the + menu bar and, depending on system settings, the dock on Mac OS X. + On some Linux configurations, it is not possible to determine the visible bounds. + In these cases, the visibleBounds property returns the same + value as the screenBounds property.

+ +
The following example shows how to get the usable bounds of a screen + (in this case, the primary display screen): + +import flash.display.Screen; +import flash.geom.Rectangle; + +var mainScreen:Screen = Screen.mainScreen; +var screenBounds:Rectangle = mainScreen.visibleBounds; +
NativeWindowDisplayState + The NativeWindowDisplayState class defines constants for the names of the window display states.Object + The NativeWindowDisplayState class defines constants for the names of the window display states. + +

Note: The fullscreen modes are set using the Stage object displayState property, + not the window displaySate.

+ +
flash.display.Stage.displayStateflash.display.StageDisplayStateMAXIMIZED + The maximized display state.maximizedString + The maximized display state. + + MINIMIZED + The minimized display state.minimizedString + The minimized display state. + + NORMAL + The normal display state.normalString + The normal display state. + +
Bitmap + The Bitmap class represents display objects that represent bitmap images.Represents display objects that derive from images. + + flash.display:DisplayObject + The Bitmap class represents display objects that represent bitmap images. These can be images + that you load with the flash.display.Loader class, or they can be images that you create with + the Bitmap() constructor. + +

The Bitmap() constructor allows you to create a Bitmap object that + contains a reference to a BitmapData object. After you create a Bitmap object, use the + addChild() or addChildAt() method of the parent DisplayObjectContainer + instance to place the bitmap on the display list.

+ +

A Bitmap object can share its BitmapData reference among several Bitmap objects, + independent of translation or rotation properties. Because you can create multiple Bitmap + objects that reference the same BitmapData object, multiple display objects can use the + same complex BitmapData object without incurring the memory overhead of a BitmapData + object for each display object instance.

+ +

A BitmapData object can be drawn to the screen by a Bitmap object in one of two ways: + by using the vector renderer as a fill-bitmap shape, or by using a faster pixel-copying routine. + The pixel-copying routine is substantially faster than the vector renderer, but the Bitmap object + must meet certain conditions to use it:

+ +
  • No stretching, rotation, or skewing can be applied to the Bitmap object.
  • No color transform can be applied to the Bitmap object.
  • No blend mode can be applied to the Bitmap object.
  • No clipping can be done through mask layers or setMask() methods.
  • The image itself cannot be a mask.
  • The destination coordinates must be on a whole pixel boundary.
+ +

If you load a Bitmap object from a domain other than that of the Loader object used to + load the image, and there is no URL policy file that permits access to the domain of + the Loader object, then a script in that domain cannot access the Bitmap + object or its properties and methods. For more information, see the Flash Player Developer Center Topic: + Security.

+ +

Note: The Bitmap class is not a subclass of the InteractiveObject class, so + it cannot dispatch mouse events. However, you can use the addEventListener() method + of the display object container that contains the Bitmap object.

+ +
The following example uses the BitmapExample class to load the + "Image.gif" image into a DisplayObject in the default location (x = 0, y = 0). A copy + of Image.gif is then placed to the right of the original, which has new colors applied to pixels + that pass a test using the threshold() method. + This task is accomplished using the following steps: +
  1. A property url is created, which is the location and name of the image file
  2. The class constructor calls the configureAssets() method, which, in turn, calls the + completeHandler() method.
  3. configureAssets() creates a Loader object, which then instantiates an event listener, + which is dispatched when completeHandler() completes the image manipulation.
  4. Next, the buildChild() method creates a new instance of a URLRequest object, + request, with url passed so the file name and location are known.
  5. The request object is passed to the loader.load() method, which loads the image + into memory via a display object.
  6. The image is then placed on the display list, which promptly displays the image on screen at + coordinates x = 0, y = 0.
  7. The completeHandler() method then performs the following tasks: +
    1. Creates a second Loader object, along with a Bitmap object, which is initialized with the + Loader object.
    2. Creates a second Bitmap object, duplicate, which in turn calls the + duplicateImage() method, which creates a duplicate of the original image.
    3. Creates a BitmapData object, which is assigned to the duplicate object's + BitmapData object.
    4. Creates a new Rectangle object initialized with the same coordinates, width, and height + as the original image.
    5. Creates a new Point object, which defaults to x = 0, y = 0.
    6. Creates the following variables: +
      • operation: applies the new color when the threshold + value is >= the original.
      • threshold: the value against which each pixel is compared is set to + light gray with an alpha of 0xCC.
      • color: the color that the pixels will be set to that pass the threshold + test, which is solid yellow in this case.
      • mask: set to the exact opposite of color, (transparent blue).
      • copySource: set to false, indicating that the pixel values are not copied + in the event the threshold value does not pass. This value has no meaning because + the image is duplicated and only pixels that pass the threshold test are changed.
    7. Calls the threshold() method by using the preceding variables. The resulting threshold + equation is as follows: if (current pixel Value & 0x000000FF) >= + (0xCCCCCCCC & 0x000000FF) then set pixel to 0xFFFFFF00.
+

Notes: +

  • You will need to compile the SWF file with "Local playback security" set to "Access local files only". +
  • This example requires that a file named Image.gif be placed in the same directory as your SWF file. +
  • It is recommended that you use an image up to 80 pixels wide.
+

+ + +package { + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.*; + import flash.geom.Point; + import flash.geom.Rectangle; + import flash.net.URLRequest; + + public class BitmapExample extends Sprite { + private var url:String = "Image.gif"; + private var size:uint = 80; + + public function BitmapExample() { + configureAssets(); + } + + private function configureAssets():void { + var loader:Loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + + var request:URLRequest = new URLRequest(url); + loader.x = size * numChildren; + loader.load(request); + addChild(loader); + } + + private function duplicateImage(original:Bitmap):Bitmap { + var image:Bitmap = new Bitmap(original.bitmapData.clone()); + image.x = size * numChildren; + addChild(image); + return image; + } + + private function completeHandler(event:Event):void { + var loader:Loader = Loader(event.target.loader); + var image:Bitmap = Bitmap(loader.content); + + var duplicate:Bitmap = duplicateImage(image); + var bitmapData:BitmapData = duplicate.bitmapData; + var sourceRect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height); + var destPoint:Point = new Point(); + var operation:String = ">="; + var threshold:uint = 0xCCCCCCCC; + var color:uint = 0xFFFFFF00; + var mask:uint = 0x000000FF; + var copySource:Boolean = true; + + bitmapData.threshold(bitmapData, + sourceRect, + destPoint, + operation, + threshold, + color, + mask, + copySource); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load image: " + url); + } + } +} +
flash.display.Loaderflash.display.BitmapDataBitmap + Initializes a Bitmap object to refer to the specified BitmapData object.bitmapDataflash.display:BitmapDatanullThe BitmapData object being referenced. + + pixelSnappingStringautoWhether or not the Bitmap object is snapped to the nearest pixel. + + smoothingBooleanfalseWhether or not the bitmap is smoothed when scaled. For example, the + following examples show the same bitmap scaled by a factor of 3, with + smoothing set to false (left) and true (right): + +

+ +

+
+ Initializes a Bitmap object to refer to the specified BitmapData object. + + The following example shows how you can dynamically load an image at runtime using the ActionScript 3.0 Loader class and then copy the image's pixels into four separate Bitmap object instances on the display list by using the Loader instance's content property and bitmapData properties. + Example provided by + ActionScriptExamples.com. + +const IMAGE_URL:String = "http://www.helpexamples.com/flash/images/logo.png"; + +var ldr:Loader = new Loader(); +ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, ldr_complete); +ldr.load(new URLRequest(IMAGE_URL)); + +var bitmap1:Bitmap; +var bitmap2:Bitmap; +var bitmap3:Bitmap; +var bitmap4:Bitmap; + +function ldr_complete(evt:Event):void { + var bmp:Bitmap = ldr.content as Bitmap; + + bitmap1 = new Bitmap(bmp.bitmapData); + bitmap1.x = 100; + bitmap1.y = 100; + bitmap1.rotation = 0; + addChild(bitmap1); + + bitmap2 = new Bitmap(bmp.bitmapData); + bitmap2.x = 200; + bitmap2.y = 100; + bitmap2.rotation = 90; + addChild(bitmap2); + + bitmap3 = new Bitmap(bmp.bitmapData); + bitmap3.x = 300; + bitmap3.y = 100; + bitmap3.rotation = 180; + addChild(bitmap3); + + bitmap4 = new Bitmap(bmp.bitmapData); + bitmap4.x = 400; + bitmap4.y = 100; + bitmap4.rotation = 270; + addChild(bitmap4); +} +
bitmapData + The BitmapData object being referenced.flash.display:BitmapData + The BitmapData object being referenced. + pixelSnapping + Controls whether or not the Bitmap object is snapped to the nearest pixel.String + Controls whether or not the Bitmap object is snapped to the nearest pixel. The PixelSnapping + class includes possible values: + +
  • PixelSnapping.NEVER—No pixel snapping occurs.
  • PixelSnapping.ALWAYS—The image is always snapped to the nearest + pixel, independent of transformation.
  • PixelSnapping.AUTO—The image is snapped + to the nearest pixel if it is drawn with no rotation + or skew and it is drawn at a scale factor of 99.9% to 100.1%. If these conditions are satisfied, + the bitmap image is drawn at 100% scale, snapped to the nearest pixel. Internally, this value allows the image + to be drawn as fast as possible using the vector renderer.
+
smoothing + Controls whether or not the bitmap is smoothed when scaled.Boolean + Controls whether or not the bitmap is smoothed when scaled. If true, the bitmap is + smoothed when scaled. If false, the bitmap is not smoothed when scaled. +
Scene + The Scene class includes properties for identifying the name, labels, and number of frames + in a scene.Object + The Scene class includes properties for identifying the name, labels, and number of frames + in a scene. A Scene object instance is created in Flash Professional, not by + writing ActionScript code. + The MovieClip class includes a currentScene property, which is + a Scene object that identifies the scene in which the playhead is located in the + timeline of the MovieClip instance. The scenes property of the + MovieClip class is an array of Scene objects. Also, the gotoAndPlay() + and gotoAndStop() methods of the MovieClip class use Scene objects as + parameters. + + MovieClip.currentSceneMovieClip.scenesMovieClip.gotoAndPlay()MovieClip.gotoAndStop()labels + An array of FrameLabel objects for the scene.Array + An array of FrameLabel objects for the scene. Each FrameLabel object contains + a frame property, which specifies the frame number corresponding to the + label, and a name property. + + FrameLabelname + The name of the scene.String + The name of the scene. + numFrames + The number of frames in the scene.int + The number of frames in the scene. + StageDisplayState +The StageDisplayState class provides values for the Stage.displayState property.Object +The StageDisplayState class provides values for the Stage.displayState property. + +flash.display.Stage.displayStateFULL_SCREEN_INTERACTIVE +Specifies that the Stage is in full-screen mode with keyboard interactivity enabled.fullScreenInteractiveString +Specifies that the Stage is in full-screen mode with keyboard interactivity enabled. +Only AIR applications support this capability. + +FULL_SCREEN +Specifies that the Stage is in full-screen mode.fullScreenString +Specifies that the Stage is in full-screen mode. Keyboard interactivity is disabled in this mode. + +NORMAL +Specifies that the Stage is in normal mode.normalString +Specifies that the Stage is in normal mode. + +ShaderData + A ShaderData object contains properties representing any parameters and + inputs for a shader kernel, as well as properties containing any metadata + specified for the shader.Object + A ShaderData object contains properties representing any parameters and + inputs for a shader kernel, as well as properties containing any metadata + specified for the shader. + +

These properties are added to the ShaderData object when it is created. The properties' + names match the names specified in the shader's source code. The data type of each + property varies according to what aspect of the shader the property represents. The + properties that represent shader parameters are ShaderParameter instances, the properties + that represent input images are ShaderInput instances, and the properties that represent + shader metadata are instances of the ActionScript class corresponding to their data type + (for example, a String instance for textual metadata and a uint for uint metadata).

+ +

For example, consider this shader, which is defined with one input image (src), + two parameters (size and radius), and three metadata values + (nameSpace, version, and description):

+ + + <languageVersion : 1.0;> + + kernel DoNothing + < + namespace: "Adobe::Example"; + vendor: "Adobe examples"; + version: 1; + description: "A shader that does nothing, but does it well."; + > + { + input image4 src; + + output pixel4 dst; + + parameter float2 size + < + description: "The size of the image to which the kernel is applied"; + minValue: float2(0.0, 0.0); + maxValue: float2(100.0, 100.0); + defaultValue: float2(50.0, 50.0); + >; + + parameter float radius + < + description: "The radius of the effect"; + minValue: 0.0; + maxValue: 50.0; + defaultValue: 25.0; + >; + + void evaluatePixel() + { + float2 one = (radius / radius) ∗ (size / size); + dst = sampleNearest(src, outCoord()); + } + } + + +

If you create a Shader instance by loading the byte code for this shader, the ShaderData + instance in its data property contains these properties:

+ + PropertyData typeValuenameString"DoNothing"nameSpaceString"Adobe::Example"versionString"1"descriptionString"A shader that does nothing, but does it well."srcShaderInput[A ShaderInput instance]sizeShaderParameter[A ShaderParameter instance, with properties for the parameter metadata]radiusShaderParameter[A ShaderParameter instance, with properties for the parameter metadata] + +

Note that any input image or parameter that is defined in the shader source code + but not used in the shader's evaluatePixel() function is removed when the + shader is compiled to byte code. In that case, there is no corresponding ShaderInput + or ShaderParameter instance added as a property of the ShaderData instance.

+ +

Generally, developer code does not create a ShaderData instance. + A ShaderData instance containing data, parameters, and inputs + for a shader is available as the Shader instance's data + property.

+ +
The following example loads a shader and enumerates the ShaderData instance + in its data property to display the input, parameters, and metadata properties of + the shader. + +

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same + directory as the output directory for the application.

+ + +// +// Source code for the shader: +// +<languageVersion : 1.0;> + +kernel DoNothing +< + namespace: "Adobe::Example"; + vendor: "Adobe examples"; + version: 1; + description: "A shader that does nothing, but does it well."; +> +{ + input image4 src; + + output pixel4 dst; + + parameter float2 size + < + description: "The size of the image to which the shader is applied"; + minValue: float2(0.0, 0.0); + maxValue: float2(100.0, 100.0); + defaultValue: float2(50.0, 50.0); + >; + + parameter float radius + < + description: "The radius of the effect"; + minValue: float(0.0); + maxValue: float(50.0); + defaultValue: float(25.0); + >; + + void evaluatePixel() + { + float2 one = (radius / radius) * (size / size); + dst = sampleNearest(src, outCoord()); + } +} + +// +// ActionScript source code: +// +package { + import flash.display.Shader; + import flash.display.Sprite; + import flash.events.Event; + import flash.net.URLLoader; + import flash.net.URLLoaderDataFormat; + import flash.net.URLRequest; + + public class ShaderDataExample extends Sprite { + + private var loader:URLLoader; + + public function ShaderDataExample() { + loader = new URLLoader(); + loader.dataFormat = URLLoaderDataFormat.BINARY; + loader.addEventListener(Event.COMPLETE, loadCompleteHandler); + loader.load(new URLRequest("donothing.pbj")); + } + + private function loadCompleteHandler(event:Event):void { + var shader:Shader = new Shader(); + shader.byteCode = loader.data; + + for (var p:String in shader.data) { + trace(p, ":", shader.data[p]); + for (var d:String in shader.data[p]) { + trace("\t", d, ":", shader.data[p][d]); + } + } + } + } +} +
flash.display.Shader.dataflash.display.ShaderInputflash.display.ShaderParameterShaderData + Creates a ShaderData instance.byteCodeflash.utils:ByteArrayThe shader's byte code. + + + Creates a ShaderData instance. Generally, developer code does not call + the ShaderData constructor directly. A ShaderData instance containing + data, parameters, and inputs for a Shader instance is accessed using + its data property. + + flash.display.Shader.data
ShaderJob + A ShaderJob instance is used to execute a shader operation in stand-alone mode.flash.events:EventDispatcher + A ShaderJob instance is used to execute a shader operation in stand-alone mode. + The shader operation executes and returns its result data. It is up to the + developer to determine how to use the result. + +

There are two primary reasons for using a shader in stand-alone mode:

+ +
  • Processing non-image data: Using a ShaderJob instance you have control + over input values and over how the shader result is used. The shader can + return the result as binary data or number data instead of image data.
  • Background processing: Some shaders are complex and require a notable + amount of time to execute. Executing a complex shader in the main + execution of an application could slow down other parts of the application + such as user interaction or updating the screen. Using a ShaderJob instance, + you can execute the shader in the background. + When the shader is executed in this way, the shader operation runs separate + from the main execution of the application.
+ +

The shader property (or constructor parameter) specifies the + Shader instance representing the shader that is used for the operation. You + provide any parameter or input that the shader expects using the + associated ShaderParameter or ShaderInput instance.

+ +

Before execution a ShaderJob operation, you provide an object into which the + result is written, by setting it as the value of the target property. + When the shader operation completes the result is written into the target object.

+ +

To begin a background shader operation, + call the start() method. When the operation finishes the result is + written into the target object. At that point the ShaderJob + instance dispatches a complete + event, notifying listeners that the result is available.

+ +

To execute a shader synchronously (that is, not running in the background), call + the start() method and pass true as an argument. The shader + runs in the main execution thread and your code pauses until the operation completes. When + it finishes the result is written into the target object. At that point + the application continues running at the next line of code.

+ +
ShaderShaderInputShaderParameterShaderEventcomplete + Dispatched when a ShaderJob that executes asynchronously finishes processing + the data using the shader.flash.events.ShaderEvent.COMPLETEflash.events.ShaderEvent + Dispatched when a ShaderJob that executes asynchronously finishes processing + the data using the shader. A ShaderJob instance executes asynchronously when the + start() method is called with a false value for the + waitForCompletion parameter. + + ShaderJob + + shaderflash.display:ShadernullThe shader to use for the operation. + + targetObjectnullThe object into which the result of the shader operation + is written. This argument must be a BitmapData, ByteArray, or + Vector.<Number> instance. + + widthint0The width of the result data in the target if it is + a ByteArray or Vector.<Number> instance. The size of the + ByteArray or Vector.<Number> instance is enlarged + if necessary and existing data is overwritten. + + heightint0The height of the result data in the target if it is + a ByteArray or Vector.<Number> instance. The size of the + ByteArray or Vector.<Number> instance is enlarged + if necessary and existing data is overwritten. + + + + cancel + Cancels the currently running shader operation. + Cancels the currently running shader operation. Any result data that is already + computed is discarded. The complete event is not dispatched. + +

Calling cancel() multiple times has no additional effect.

+ +
start + Starts a shader operation in synchronous or asynchronous mode, according to the + value of the waitForCompletion parameter.When the target property is null or is not + a BitmapData, ByteArray, or Vector.<Number> instance. + + ArgumentErrorArgumentErrorWhen the shader specifies an image input that isn't provided. + + ArgumentErrorArgumentErrorWhen a ByteArray or Vector.<Number> instance is used as + an input and the width + and height properties aren't specified for the + ShaderInput, or the specified values don't match the amount of + data in the input object. See the ShaderInput.input + property for more information. + + ArgumentErrorArgumentErrorwaitForCompletionBooleanfalseSpecifies whether to execute the shader in the background + (false, the default) or in the main program + execution (true). + + + Starts a shader operation in synchronous or asynchronous mode, according to the + value of the waitForCompletion parameter. + +

In asynchronous mode (when waitForCompletion + is false), which is the default, the + ShaderJob execution runs in the background. The shader operation does not affect the + responsiveness of the display or other operations. In asynchronous mode the start() + call returns immediately and the program continues with the next line of code. When the asynchronous + shader operation finishes, the result is available and the complete + event is dispatched.

+ +

Only one background ShaderJob operation + executes at a time. Shader operations are held in a queue until they execute. + If you call the start() method while a shader + operation is executing, the additional operation is added to the end of the queue. + Later, when its turn comes, it executes.

+ +

To execute a shader operation in synchronous mode, call start() with a + true value for the waitForCompletion parameter (the only parameter). + Your code pauses at the point where start() is called until the shader operation + completes. At that point the result is available and execution continues with the next line + of code.

+ +

When you call the start() method the Shader instance in the shader + property is copied internally. The + shader operation uses that internal copy, not a reference to the original shader. Any changes + made to the shader, such as changing a parameter value, input, or bytecode, are not applied + to the copied shader that's used for the shader processing. To incorporate shader changes + into the shader processing, call the cancel() method + (if necessary) and call the start() method again to restart the shader processing.

+ +

While a shader operation is executing, the target object's value + is not changed. When the operation finishes (and the complete + event is dispatched in asynchronous mode) the entire result is written to the + target object at one time. If the target object is a + BitmapData instance and its dispose() method is called + before the operation finishes, the complete event is still + dispatched in asynchronous mode. However, the result data is not + written to the BitmapData object because it is in a disposed state.

+ +
completeflash.events:ShaderEventDispatched when the operation finishes, if the + start() method is called with a + waitForCompletion argument of true. + + Dispatched when the operation finishes, if the + start() method is called with a + waitForCompletion argument of true.
height + The height of the result data in the target if it is + a ByteArray or Vector.&lt;Number&gt; instance.int + The height of the result data in the target if it is + a ByteArray or Vector.<Number> instance. The size of the + ByteArray or Vector.<Number> instance is enlarged + if necessary and existing data is overwritten. + + progress + The progress of a running shader.Number + The progress of a running shader. This property is a value from 0 through 1. + Zero is the initial value (0% complete). One indicates that the shader + has completed its operation. + +

If the cancel() method is called this property becomes + undefined, and its value cannot be used reliably until the + shader operation starts again.

+ +
shader + The shader that's used for the operation.flash.display:Shader + The shader that's used for the operation. Any input or parameter that the + shader expects must be provided using the ShaderInput or ShaderParameter + property of the Shader instance's data property. An input must + be provided using its corresponding ShaderInput even if it is the same as + the target object. + +

To process a ByteArray containing a linear array of data (as opposed to + image data) set the corresponding ShaderInput instance's height + to 1 and width to the number of 32-bit floating-point values in + the ByteArray. In that case, the input in the shader must be defined with + the image1 data type.

+ +
flash.display.ShaderDataflash.display.ShaderInputflash.display.ShaderParameter
target + The object into which the result of the shader operation is written.Object + The object into which the result of the shader operation is written. + This object must be a BitmapData, ByteArray, or Vector.<Number> instance. + + width + The width of the result data in the target if it is + a ByteArray or Vector.&lt;Number&gt; instance.int + The width of the result data in the target if it is + a ByteArray or Vector.<Number> instance. The size of the + ByteArray or Vector.<Number> instance is enlarged + if necessary and existing data is overwritten. + +
NativeWindowSystemChrome + The NativeWindowSystemChrome class defines constants for the systemChrome + property of the NativeWindowInitOptions object used to create a native window.Defines constants representing the supported types of window chrome. + + Object + The NativeWindowSystemChrome class defines constants for the systemChrome + property of the NativeWindowInitOptions object used to create a native window. + +

System chrome refers to the operating system-specific elements of a window + such as a title bar, minimize, maximize, and close buttons.

+ +

Note: The type of system chrome used is specified when a window is + created and cannot be changed.

+ +
flash.display.NativeWindowflash.display.NativeWindowInitOptionsALTERNATE + Reserved for future use.alternateString + Reserved for future use. + +

Do not use.

+ +
NONE + No system chrome.noneString + No system chrome. + + STANDARD + The standard chrome for the host operating system.standardString + The standard chrome for the host operating system. + +

Use this setting to emulate the look and feel of the native operating system.

+ +
IGraphicsStroke + This interface is used to define objects that can be used as stroke parameters in the flash.display.Graphics + methods and drawing classes. + This interface is used to define objects that can be used as stroke parameters in the flash.display.Graphics + methods and drawing classes. Use the implementor classes of this interface to + create and manage stroke property data, and to reuse the same data for different instances. + flash.display.Graphics.drawGraphicsData()SimpleButton + The SimpleButton class lets you control all instances of button symbols in a SWF + file.The SimpleButton class lets you control all instances of button symbols + in a SWF file. + + flash.display:InteractiveObject + The SimpleButton class lets you control all instances of button symbols in a SWF + file. + +

In Flash Professional, you can give a button an instance name in the + Property inspector. SimpleButton instance names are displayed in the Movie + Explorer and in the Insert Target Path dialog box in the Actions + panel. After you create an instance of a button in Flash Professional, you can + use the methods and properties of the SimpleButton class to manipulate buttons + with ActionScript.

+ +

In ActionScript 3.0, you use the new SimpleButton() constructor to create a + SimpleButton instance.

+ +

The SimpleButton class inherits from the InteractiveObject class.

+ +
The following example uses the SimpleButtonExample class, which in + turn uses the CustomSimpleButton class, and this class then instantiates four + ButtonDisplayState objects. The result is a button that is created in the shape of + a square, whose background color changes based on the mouse state by overriding instance properties of + the SimpleButton class. This is accomplished by performing the following steps: +
  1. In the SimpleButtonExample() constructor, a new CustomSimpleButton object of type + SimpleButton, called button, is created, which calls the CustomSimpleButton constructor + method. The button object is the added to the display list. The button's color and size are + determined in the steps that follow.
  2. In the CustomSimpleButton class, instance properties are declared that are later used + to control the size and background color of button, based on the state it is in (orange + in the normal state, dark yellow in the mouse over state, an light blue in the mouse down state). + In all of the button's states, the size of the square is set to 80 pixels by using the + size property.
  3. The constructor function for the CustomSimpleButton class sets the + downState, overState, upState, + hitTestState, and useHandCursor properties with + four instances of the ButtonDisplayState class.
  4. In the ButtonDisplayState class, the constructor sets the value of the + square's size and background color and calls the draw() method.
  5. The draw() method redraws the square with the size and background color set in + the constructor based on the button's state.
+ +package { + import flash.display.Sprite; + + public class SimpleButtonExample extends Sprite { + public function SimpleButtonExample() { + var button:CustomSimpleButton = new CustomSimpleButton(); + addChild(button); + } + } +} + +import flash.display.DisplayObject; +import flash.display.Shape; +import flash.display.SimpleButton; + +class CustomSimpleButton extends SimpleButton { + private var upColor:uint = 0xFFCC00; + private var overColor:uint = 0xCCFF00; + private var downColor:uint = 0x00CCFF; + private var size:uint = 80; + + public function CustomSimpleButton() { + downState = new ButtonDisplayState(downColor, size); + overState = new ButtonDisplayState(overColor, size); + upState = new ButtonDisplayState(upColor, size); + hitTestState = new ButtonDisplayState(upColor, size * 2); + hitTestState.x = -(size / 4); + hitTestState.y = hitTestState.x; + useHandCursor = true; + } +} + +class ButtonDisplayState extends Shape { + private var bgColor:uint; + private var size:uint; + + public function ButtonDisplayState(bgColor:uint, size:uint) { + this.bgColor = bgColor; + this.size = size; + draw(); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, size, size); + graphics.endFill(); + } +} +
InteractiveObject classSimpleButton + Creates a new SimpleButton instance.upStateflash.display:DisplayObjectnullThe initial value for the SimpleButton up state. + overStateflash.display:DisplayObjectnullThe initial value for the SimpleButton over state. + downStateflash.display:DisplayObjectnullThe initial value for the SimpleButton down state. + hitTestStateflash.display:DisplayObjectnullThe initial value for the SimpleButton hitTest state. + + Creates a new SimpleButton instance. + + + Creates a new SimpleButton instance. Any or all of the display objects that represent + the various button states can be set as parameters in the constructor. + + downState + Specifies a display object that is used as the visual + object for the button "Down" state &#8212;the state that the button is in when the user + selects the hitTestState object.flash.display:DisplayObjectSpecifies a DisplayObject value used for the + button "Down" state. + + + Specifies a display object that is used as the visual + object for the button "Down" state —the state that the button is in when the user + selects the hitTestState object. + + hitTestStateoverStateupStateenabled + A Boolean value that specifies whether a button is enabled.BooleanSpecifies whether a button is enabled (true) or disabled (false). + + + A Boolean value that specifies whether a button is enabled. When a + button is disabled (the enabled property is set to false), + the button is visible but cannot be clicked. The default value is + true. This property is useful if you want to + disable part of your navigation; for example, you might want to disable a + button in the currently displayed page so that it can't be clicked and + the page cannot be reloaded. + +

Note: To prevent mouseClicks on a button, set both the enabled + and mouseEnabled properties to false.

+ +
hitTestState + Specifies a display object that is used as the hit testing object for the button.flash.display:DisplayObject + Specifies a display object that is used as the hit testing object for the button. For a basic button, set the + hitTestState property to the same display object as the overState + property. If you do not set the hitTestState property, the SimpleButton + is inactive — it does not respond to user input events. + + downStateoverStateupStateoverState + Specifies a display object that is used as the visual + object for the button over state &#8212; the state that the button is in when + the pointer is positioned over the button.flash.display:DisplayObjectSpecifies a DisplayObject value used for the + button "Over" state. + + + Specifies a display object that is used as the visual + object for the button over state — the state that the button is in when + the pointer is positioned over the button. + + downStatehitTestStateupStatesoundTransform + The SoundTransform object assigned to this button.flash.media:SoundTransform + The SoundTransform object assigned to this button. A SoundTransform object + includes properties for setting volume, panning, left speaker assignment, and right + speaker assignment. This SoundTransform object applies to all states of the button. + This SoundTransform object affects only embedded sounds. + + flash.media.SoundTransformtrackAsMenu + Indicates whether other display objects that are SimpleButton or MovieClip objects can receive + user input release events.Boolean + Indicates whether other display objects that are SimpleButton or MovieClip objects can receive + user input release events. The trackAsMenu property lets you create menus. You + can set the trackAsMenu property on any SimpleButton or MovieClip object. + If the trackAsMenu property does not exist, the default behavior is + false. + +

You can change the trackAsMenu property at any time; the + modified button immediately takes on the new behavior.

+ +
upState + Specifies a display object that is used as the visual + object for the button up state &#8212; the state that the button is in when + the pointer is not positioned over the button.flash.display:DisplayObjectSpecifies a DisplayObject value used for the + button "Up" state. + + + Specifies a display object that is used as the visual + object for the button up state — the state that the button is in when + the pointer is not positioned over the button. + + downStatehitTestStateoverStateuseHandCursor + A Boolean value that, when set to true, indicates whether + the hand cursor is shown when the pointer rolls over a button.BooleanDisplays a pointing hand cursor when set to true. + + + A Boolean value that, when set to true, indicates whether + the hand cursor is shown when the pointer rolls over a button. + If this property is set to false, the arrow pointer cursor is displayed + instead. The default is true. + +

You can change the useHandCursor property at any time; + the modified button immediately uses the new cursor behavior.

+ +
TriangleCulling + Defines codes for culling algorithms that determine which triangles not to render when drawing triangle paths.Object + Defines codes for culling algorithms that determine which triangles not to render when drawing triangle paths. + +

+ The terms POSITIVE and NEGATIVE refer to the sign of a triangle's normal along the z-axis. + The normal is a 3D vector that is perpendicular to the surface of the triangle. +

+ +

+ A triangle whose vertices 0, 1, and 2 are arranged in a clockwise order has a positive normal value. That is, + its normal points in a positive z-axis direction, away from the current view point. + When the TriangleCulling.POSITIVE algorithm is used, triangles with positive normals + are not rendered. Another term for this is backface culling. +

+ +

+ A triangle whose vertices are arranged in a counter-clockwise order has a negative normal value. That is, + its normal points in a negative z-axis direction, toward the current view point. + When the TriangleCulling.NEGATIVE algorithm is used, triangles with negative normals will not + be rendered. +

+ +
flash.display.Graphics.drawTriangles()flash.display.GraphicsTrianglePathIntroduction to 3D Vectors3D Backface CullingNEGATIVE + Specifies culling of all triangles facing toward the current view point.negativeString + Specifies culling of all triangles facing toward the current view point. + NONE + Specifies no culling.noneString + Specifies no culling. All triangles in the path are rendered. + POSITIVE + Specifies culling of all triangles facing away from the current view point.positiveString + Specifies culling of all triangles facing away from the current view point. + This is also known as backface culling. +
NativeWindow + The NativeWindow class provides an interface for creating and controlling native desktop windows.flash.events:EventDispatcher + The NativeWindow class provides an interface for creating and controlling native desktop windows. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time on desktop devices using the NativeWindow.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

A reference to the NativeWindow instance is returned by the window constructor. + A reference to a NativeWindow instance can also be accessed using the stage.nativeWindow + property of any display object on that window's stage: +

+ +
var window:NativeWindow = displayObject.stage.nativeWindow;
+ + + +

The properties of a NativeWindow instance can only be accessed by application + content. If non-application content attempts to access the NativeWindow object, a + security error will be thrown.

+ +

Content can be added to a window using the + DisplayObjectContainer methods of the Stage object such as addChild().

+ +

You cannot not add Flex components directly to the display list of a + NativeWindow instance. Instead, use the Flex mx:WindowedApplication + and mx:Window components to create your windows and add the other Flex + components as children of those objects. You can add Flex-based SWF content directly + to a NativeWindow window as long as the SWF file is loaded into its own + application domain and is application content. +

+ +

To create a root HTML window for displaying HTML content it is typically + easier to create the window with HTMLLoader.createRootWindow(). + Windows created in this way will have an HTMLLoader object added automatically. + (From JavaScript code, you can also use the JavaScript + window.open() function. However, this method gives you less control + over the window appearance and behavior.)

+ +

+ The following operations on NativeWindow objects are asynchronous: close(), + maximize(), minimize(), restore(), and bounds changes. + An application can detect when these operations have completed by listening + for the appropriate events. +

+ +

+ If the NativeApplication.autoExit property is true, which is the default, + the application will close when its last window is closed (and all close event + handlers have returned). + If autoExit is false, then NativeApplication.nativeApplication.exit() + must be called to terminate the application. +

+

+ NativeWindow objects will not be garbage collected after the window constructor has been called + and before close() + has been called. It is the responsibility of the application to close its own windows. +

+ +
flash.display.Stage.nativeWindowflash.display.NativeWindowInitOptionsflash.desktop.NativeApplicationflash.system.ApplicationDomainflash.html.HTMLLoader.createRootWindow()deactivate + Dispatched by this NativeWindow object after the window has been deactivated.flash.events.Event.DEACTIVATEflash.events.Event + Dispatched by this NativeWindow object after the window has been deactivated. + + activate + Dispatched by this NativeWindow object after the window has been activated.flash.events.Event.ACTIVATEflash.events.Event + Dispatched by this NativeWindow object after the window has been activated. + + close + Dispatched by this NativeWindow object after the window has been closed.flash.events.Event.CLOSEflash.events.Event + Dispatched by this NativeWindow object after the window has been closed. + + closing + Dispatched by this NativeWindow object immediately before the window is to be closed.flash.events.Event.CLOSINGflash.events.Event + Dispatched by this NativeWindow object immediately before the window is to be closed. + This event can be canceled to prevent the window from being closed. + + displayStateChange + Dispatched by this NativeWindow object after the window's displayState property has changed.flash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGEflash.events.NativeWindowDisplayStateEvent + Dispatched by this NativeWindow object after the window's displayState property has changed. + +

Do not resize the window or change its display state in the displayStateChange + event handler.

+ +
displayStateChanging + Dispatched by this NativeWindow object immediately before the window changes its display state.flash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGINGflash.events.NativeWindowDisplayStateEvent + Dispatched by this NativeWindow object immediately before the window changes its display state. + This event can be canceled to prevent the change. + + The following example demonstrates how to cancel a displayStateChanging event. + +function displayStateChanging_handler(displayStateEvent:NativeWindowDisplayStateEvent):void +{ + //shouldStopStateChange is an application-defined Boolean indicating + //that display state changes should be canceled + if (displayStateEvent.type == NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING + && shouldStopStateChange) + { + displayStateEvent.preventDefault(); + } +} +resize + Dispatched by this NativeWindow object after the window has been resized.flash.events.NativeWindowBoundsEvent.RESIZEflash.events.NativeWindowBoundsEvent + Dispatched by this NativeWindow object after the window has been resized. + + A resize event is dispatched whenever the size (width or height properties) of the window + changes, which can occur because of a system-controlled window resize; minimizing, maximizing, + or restoring the window; or changing the window size by setting the width, + height, or bounds properties. + + NativeWindow resize events are dispatched during system-controled resize loops. In contrast, + Stage object resize events are dispatched when the Stage is ready for drawing. + + Stage resize eventresizing + Dispatched by this NativeWindow object immediately before the window is to be resized on + the desktop.flash.events.NativeWindowBoundsEvent.RESIZINGflash.events.NativeWindowBoundsEvent + Dispatched by this NativeWindow object immediately before the window is to be resized on + the desktop. This event can be canceled to prevent or modify the resize. + + The following example demonstrates how to cancel a resizing event. + +function boundsChanging_handler(boundsEvent:NativeWindowBoundsEvent):void +{ + //shouldStopResize is an application-defined Boolean indicating + //that resize operations should be canceled + if (boundsEvent.type == NativeWindowBoundsEvent.RESIZING && shouldStopResize) + { + boundsEvent.preventDefault(); + } +} +move + Dispatched by this NativeWindow object after the window has been moved on the desktop.flash.events.NativeWindowBoundsEvent.MOVEflash.events.NativeWindowBoundsEvent + Dispatched by this NativeWindow object after the window has been moved on the desktop. +

+ A move event is dispatched whenever the origin (x or y properties) of the window + changes, which can occur because of a system-controlled window move; minimizing, maximizing, + or restoring the window; or changing the window location by setting the x, + y, or bounds properties. +

+

Note: Avoid actions that may open simultaneous operating system dialogs boxes + in the handler functions for both the moving and move events + of a NativeWindow object. This may occur, for example, if both handler functions throw an error. + If it does occur, the second dialog box opened will not + register mouse clicks and must be closed using the keyboard.

+ +
moving + Dispatched by the NativeWindow object immediately before the window is to be moved on + the desktop.flash.events.NativeWindowBoundsEvent.MOVINGflash.events.NativeWindowBoundsEvent + Dispatched by the NativeWindow object immediately before the window is to be moved on + the desktop. This event can be canceled to prevent or modify the move. + +

Note: Avoid actions that may open simultaneous operating system dialogs boxes + in the handler functions for both the moving and move events + of a NativeWindow object. This may occur, for example, if both handler functions throw an error. + If it does occur, the second dialog box opened will not + register mouse clicks and must be closed using the keyboard.

+ +
NativeWindow + Creates a new NativeWindow instance and a corresponding operating system window.If the initOptions parameter is invalid. + + IllegalOperationErrorflash.errors:IllegalOperationErrorinitOptionsflash.display:NativeWindowInitOptionsAn object containing the initialization properties for this window. + + Creates a new NativeWindow instance and a corresponding operating system window. +

+ The settings defined in the initOptions parameter cannot be changed after the + window is created. Invalid initOptions settings will cause an illegal operation error + to be thrown. Settings that are valid but not available on the current system will not throw an exception. + The window capabilities specific to the current operating system can be + detected, if desired, using the static NativeWindow members + such as systemMaxSize. +

+ +

The default window size is determined by the operating system, and windows are created in an invisible state. + To prevent changes to the window from being visible, do not change the + window visible property to true or call activate() until the + window changes are finished.

+ +
The following example creates and activates a new NativeWindow instance: + +import flash.display.NativeWindowInitOptions; +import flash.display.NativeWindowSystemChrome; +import flash.display.NativeWindowType; +import flash.display.NativeWindow; +import flash.display.StageAlign; +import flash.display.StageScaleMode; +import flash.geom.Rectangle; + +var windowOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); +windowOptions.systemChrome = NativeWindowSystemChrome.STANDARD; +windowOptions.type = NativeWindowType.NORMAL; + +var newWindow:NativeWindow = new NativeWindow(windowOptions); +newWindow.stage.scaleMode = StageScaleMode.NO_SCALE; +newWindow.stage.align = StageAlign.TOP_LEFT; +newWindow.bounds = new Rectangle(100, 100, 800, 800); + +newWindow.activate(); +
flash.display.NativeWindowInitOptionsflash.html.HTMLLoader.createRootWindow()
activate + Activates this window. + Activates this window. + +

Activating a window will:

+
  • Make the window visible
  • Bring the window to the front
  • Give the window keyboard and mouse focus
+ +

On Linux, activate() is an asynchronous operation.

+ +

The NativeWindow object dispatches an activate event on all platforms.

+ +
The following examples show how to activate a window. + +

With a reference to a display object on the window stage:

+ +displayObject.stage.nativeWindow.activate(); +
With a reference to an instance of the NativeWindow class: + +windowObj.activate(); + From JavaScript in an HTML page rendered in the window + (where window is the global JavaScript window object): + +window.nativeWindow.activate(); +
visibleorderToFront()
close + Closes this window. + Closes this window. + +

A close event is dispatched as soon as the close operation is complete. + A closing event will not be dispatched. If cancellation of the close operation should + be allowed, dispatch a closing event and check whether any registered listeners cancel + the default behavior before calling the close() method. +

+

When a window is closed, any windows that it owns are also closed. The owned windows + do not dispatch closing events.

+

+ If display object instances that are currently in the window are not referenced elsewhere + they will be garbage collected and destroyed, except on the initial application window + created by AIR. To allow display objects on the initial window to be garbage collected, + remove them from the window stage. +

+

+ After being closed, the NativeWindow object is still a valid reference, but accessing most + properties and methods will throw an illegal operation error. +

+

+ Closed windows cannot be reopened. If the window is already closed, no action is taken and + no events are dispatched. +

+ +

Note: to hide a window without closing it, set the window's visible property to + false. +

+ +
The following examples show how to close a window: + +

With a reference to the NativeWindow instance (windowObj):

+ +windowObj.close(); + +
With a reference to a display object on the window stage: + +displayObj.stage.nativeWindow.close(); + From a JavaScript routine running in an HTMLLoader object + (or HTML root window): + +window.close(); //overriddable in HTMLHost + Or: + +window.nativeWindow.close(); //not overriddable + + The following example illustrates how to allow cancellation of a close operation + (where windowObj is the NativeWindow instance to be closed): + +public function closeCommand():Boolean{ + var closeEvent:Event = new Event(Event.CLOSING,true,true); + windowObj.dispatchEvent(closeEvent); + if(!closeEvent.isDefaultPrevented()){ + windowObj.close(); + return true; + } else { + return false; + } +} + The following example illustrates how to close a window from a + JavaScript routine running in an HTMLLoader object (or HTML root window), while + allowing the operation to be canceled: + +<script src="AIRAliases.js" type="text/javascript"></script> +<script type="text/javascript"> + var dirtyData = false; + function closeWindow(){ + var closingEvent = new air.Event(air.Event.CLOSING,true,true); + window.nativeWindow.dispatchEvent(closingEvent); + if(!closingEvent.isDefaultPrevented()){ + window.nativeWindow.close(); + //or use: window.close(); + return true; + } else { + return false; + } + } + + function onClosing(event){ + if(dirtyData){ + event.preventDefault(); + //Save data... + } + } + + window.nativeWindow.addEventListener(air.Event.CLOSING,onClosing); +</script> +
flash.display.NativeWindow.closedflash.html.HTMLLoaderflash.html.HTMLHost
globalToScreen + Converts a point in pixel coordinates relative to the origin of the window stage + (a global point in terms of the display list), to a point on the virtual desktop.The specified global point relative to the desktop. + + flash.geom:PointglobalPointflash.geom:PointThe point on the stage to convert to a point on the screen. + + Converts a point in pixel coordinates relative to the origin of the window stage + (a global point in terms of the display list), to a point on the virtual desktop. + +

Virtual desktop coordinates are relative to the upper, lefthand corner of the primary + monitor.

+ +
flash.display.Screen
listOwnedWindows + Returns a list of the NativeWindow objects that are owned by this window.an Vector.<NativeWindow> object containing zero or more NativeWindow objects that + are owned by this instance. + + + Returns a list of the NativeWindow objects that are owned by this window. + +

You cannot change ownership of NativeWindows by adding or removing objects from + the returned vector. Window ownership cannot be changed after a window is created.

+ +
flash.display.NativeWindowInitOptions.owner
maximize + Maximizes this window.If this method is called after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Maximizes this window. +

+ Calling maximize() method dispatches a displayStateChange + event, and, if applicable, a move and a resize event. + Whereas system chrome will dispatch a displayStateChanging event + that can be canceled when a maximize command is initiated by a user, your maximize + logic must implement this behavior, if desired. +

+

+ The maximize() method executes asynchronously. To detect the completion + of the state change, listen for the displayStateChange event. If the window + is already maximized, no action is taken and no events are dispatched.

+ +

OS behavior notes:

+
  • On operating systems, such as Mac OS X, in which maximizing + a window does not also prevent resizing, calling maximize() will zoom the window + to fill the screen, but will not prevent subsequent resizing of the window. + Resizing a zoomed window will also restore the display state.
  • On some operating systems, such as Mac OS X, as well as on some Linux window managers, + maximizing a window will not expand the window beyond + the width and height specified in the maxSize property. On others, the window will expand + to fill the screen even if the screen is larger than the maxSize.
  • Some Linux window managers do not allow utility windows to be maximized.
+ +
+ The following example illustrates how to allow cancelation of a maximize operation: + +public function maximizeWindow(nativeWin:NativeWindow):Boolean{ + if(nativeWin.displayState != NativeWindowDisplayState.MAXIMIZED){ + var beforeState:String = nativeWin.displayState; + var afterState:String = NativeWindowDisplayState.MAXIMIZED; + var displayStateEvent:NativeWindowDisplayStateEvent = + new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + nativeWin.dispatchEvent(displayStateEvent); + if(!displayStateEvent.isDefaultPrevented()){ + nativeWin.maximize(); + return true; + } else { + return false; + } + } + return false; +} + + The following example illustrates how to allow cancelation of a maximize operation + from a JavaScript routine running in an HTMLLoader object on the window (or an HTML window): + +function maximizeWindow(nativeWin){ + if(nativeWin.displayState != air.NativeWindowDisplayState.MAXIMIZED){ + var beforeState = nativeWin.displayState; + var afterState = air.NativeWindowDisplayState.MAXIMIZED; + var displayStateEvent = + new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + nativeWin.dispatchEvent(displayStateEvent); + if(!displayStateEvent.isDefaultPrevented()){ + nativeWin.maximize(); + return true; + } else { + return false; + } + } + return false; +} +
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
minimize + Minimizes this window.If this method is called after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Minimizes this window. +

+ Calling minimize() dispatches a displayStateChange event, + and, if applicable, a move and a resize event. + Whereas system chrome will dispatch a displayStateChanging event + that can be canceled when a minimize command is initiated by a user, + calling minimize() directly does not. Your minimize logic may + implement this behavior, if desired. +

+ +

The minimize() method executes asynchronously. To detect the completion + of the state change, listen for the displayStateChange event, which is dispatched on all platforms. + If the window is already minimized, no action is taken and no events are dispatched.

+ +

Any windows owned by this window are hidden when it is minimized. The owned windows do not dispatch + displayStateChanging or displayStateChange events.

+ +

Notes:

+
  • On Windows, minimizing an invisible window (visible == false), will make the + window visible.
  • Some Linux window managers + do not allow utility windows to be minimized.
+
The following example illustrates how to allow cancelation of a call to + minimize() by dispatching a displayStateChanging event: + +public function minimizeWindow(nativeWin:NativeWindow):Boolean{ + if(nativeWin.displayState != NativeWindowDisplayState.MINIMIZED){ + var beforeState:String = nativeWin.displayState; + var afterState:String = NativeWindowDisplayState.MINIMIZED; + var displayStateEvent:NativeWindowDisplayStateEvent = + new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + nativeWin.dispatchEvent(displayStateEvent); + if(!displayStateEvent.isDefaultPrevented()){ + nativeWin.minimize(); + return true; + } else { + return false; + } + } + return false; +} + The following example illustrates how to allow cancelation of a call to + minimize() in JavaScript running in an HTMLLoader object (or HTML window): + +function minimizeWindow(){ + if(window.nativeWindow.displayState != air.NativeWindowDisplayState.MINIMIZED){ + var beforeState = window.nativeWindow.displayState; + var afterState = air.NativeWindowDisplayState.MINIMIZED; + var displayStateEvent = + new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + window.nativeWindow.dispatchEvent(displayStateEvent); + if(!displayStateEvent.isDefaultPrevented()){ + window.nativeWindow.minimize(); + return true; + } else { + return false; + } + } + return false; +} +
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
notifyUser + Triggers a visual cue through the operating system that an event of + interest has occurred.typeStringA string representing the urgency of the notification. + + Triggers a visual cue through the operating system that an event of + interest has occurred. + +

When NativeWindow.supportsNotification is true, + the visual cue will conform to the operating system convention of the + native system. For example, on Windows, the task bar icon will flash.

+ +

The type parameter determines the intensity of the cue. + Constants for the permitted values are defined in the NotificationType + class, and may be:

+
  • NotificationType.INFORMATIONAL
  • NotificationType.CRITICAL
+

The cues provided for informational notifications are of short duration; + those provided for critical notifications will last until the user activates + this window. Not all Linux window managers support two levels of notification. + For such window managers, notifyUser() will have the same affect + no matter which option is specified.

+ +

Note: Calling notifyUser() when + NativeWindow.supportsNotification is false + is allowed, but does nothing.

+ +
orderInBackOf + Sends this window directly behind the specified window.true if this window was successfully sent to the + back; false if this window is invisible or minimized. + + Booleanwindowflash.display:NativeWindowAn application window. + + + Sends this window directly behind the specified window. + +

Does not activate or acquire the focus for the window or the application. + Minimized or hidden (visible is false) windows cannot be + reordered.

+ +

An owned window can never be moved behind its owner. If this window has an owner, + then the owner and its other owned windows are also ordered behind the target. If the target + window has an owner, then this window is ordered behind the owner of the target instead.

+ +

Some Linux window managers do not allow utility windows to be ordered behind normal windows.

+ +
The following examples show how to move a window just below another + window with references to the NativeWindow instances: + +windowBehind.orderInBackOf(windowFront); + With references to display objects on the window stages: + +displayObjBehind.stage.nativeWindow.orderInBackOf(displayObjectFront.stage.nativeWindow); + + From a JavaScript routine running in an HTMLLoader object (or HTML root window) + using references to two JavaScript Window objects: + +jsWindowObjBehind.nativeWindow.orderInBackOf(jsWindowObjFront.nativeWindow); +
orderInFrontOf + Brings this window directly in front of the specified window.true if this window was successfully brought to the + front; false if this window is invisible or minimized. + + Booleanwindowflash.display:NativeWindowAn application window. + + + Brings this window directly in front of the specified window. + +

Does not activate or acquire the focus for the window or the application. + Minimized or hidden (visible is false) windows cannot be + reordered.

+ +

A window can never be moved in front of a window that it owns. If this window has an owner, + then the owner and its other owned windows are also ordered in front of the target. If the target + window has an owner, then this window is also ordered in front of any other windows that have the + same owner as the target.

+ +

Some Linux window managers do not allow normal windows to be ordered in front of utility windows.

+ +
The following examples show how to move a window just above another + window with references to the NativeWindow instances: + +windowFront.orderInFrontOf(windowBehind); + With references to display objects on the window stages: + +displayObjFront.stage.nativeWindow.orderInFrontOf(displayObjectBehind.stage.nativeWindow); + + From a JavaScript routine running in an HTMLLoader object (or HTML root window) + using references to two JavaScript window objects: + +jsWindowObjFront.nativeWindow.orderInFrontOf(jsWindowObjBehind.nativeWindow); + +
orderToBack + Sends this window behind any other visible windows.true if this window was successfully sent to the + back; false if this window is invisible or minimized. + + Boolean + Sends this window behind any other visible windows. + +

Does not activate or acquire the focus for this window or the application. + Minimized or hidden (visible is false) windows cannot be + reordered.

+ +

If alwaysInFront is true, then calling this method will not + send this window behind any windows which have + alwaysInFront set to false.

+ +

An owned window can never be moved behind its owner. If this window has an owner, + then the owner and its other owned windows are also ordered to the bottom of window display list. + This window will move behind any other windows owned by the same window. If this window owns other + windows, then those windows are also moved to the back, maintaining their current order + relative to each other.

+ +

Some Linux window managers do not allow utility windows to be ordered behind normal windows.

+ +
The following examples show how to move a window behind all other + windows in the application (with the same alwaysInFront setting): + +windowObj.orderToBack(); + + With a reference to a display object on the window stage: + +displayObj.stage.nativeWindow.orderToBack(); + From a JavaScript routine running in an HTMLLoader object in the window + (or a root HTML window): + +window.nativeWindow.orderToBack(); + +
orderToFront + Brings this window in front of any other visible windows.true if this window was successfully brought to the + front; false if this window is invisible or minimized. + + Boolean + Brings this window in front of any other visible windows. + +

Does not activate or acquire the focus for this window or the application. + Minimized or hidden (visible is false) windows cannot be + reordered.

+ +

If alwaysInFront is false, then calling this method will not + send this window in front of any windows which have + alwaysInFront set to true.

+ +

A window can never be moved in front of a window that it owns. If this window owns other + windows, then those windows are also moved to the front, maintaining their current order + relative to each other. If this window has an owner, + then the owner and its other owned windows are also ordered to the front of the window display order. + This window is moved in front of other windows that have the same owner.

+ +

Some Linux window managers do not allow normal windows to be ordered in front of utility windows.

+ +
The following examples show how to move a window in front of all other + windows in the application (with the same alwaysInFront setting): + +windowObj.orderToFront(); + + With a reference to a display object on the window stage: + +displayObj.stage.nativeWindow.orderToFront(); + From a JavaScript routine running in an HTMLLoader object in the window + (or a root HTML window): + +window.nativeWindow.orderToFront(); + +
restore + Restores this window from either a minimized or a maximized state.If the method is called after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Restores this window from either a minimized or a maximized state. + +

Calling restore() dispatches a displayStateChange event, + and, if applicable, a move and a resize event. + Whereas system chrome will dispatch a displayStateChanging event that can + be canceled when a restore command is initiated by a user, your restore logic must + implement this behavior, if desired. +

+ +

If the window is already in the NativeWindowDisplayState.NORMAL state, + no action is taken and no events are dispatched.

+ +

+ To detect the completion of the state change, listen for + the displayStateChange event, which is dispatched on all platforms. +

+ +
+ The following example illustrates how to allow cancelation of a restore operation: + +public function restoreWindow(nativeWin:NativeWindow):Boolean{ + if(nativeWin.displayState != NativeWindowDisplayState.NORMAL){ + var beforeState:String = nativeWin.displayState; + var afterState:String = NativeWindowDisplayState.NORMAL; + var displayStateChangingEvent:NativeWindowDisplayStateEvent = + new NativeWindowDisplayStateEvent(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + nativeWin.dispatchEvent(displayStateChangingEvent); + if(!displayStateChangingEvent.isDefaultPrevented()){ + nativeWin.restore(); + return true; + } else { + return false; + } + } + return false; +} + The following example illustrates how to allow cancelation of a restore operation from + a JavaScript routine running in an HTMLLoader object on the window (or an HTML window): + +function restoreWindow(nativeWin){ + if(window.nativeWindow.displayState != air.NativeWindowDisplayState.NORMAL){ + var beforeState = window.nativeWindow.displayState; + var afterState = air.NativeWindowDisplayState.NORMAL; + var displayStateEvent = + new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING, + true,true,beforeState,afterState); + window.nativeWindow.dispatchEvent(displayStateEvent); + if(!displayStateEvent.isDefaultPrevented()){ + window.nativeWindow.restore(); + return true; + } else { + return false; + } + } + return false; +} +
flash.display.NativeWindowDisplayStateflash.events.NativeWindowDisplayStateEvent
startMove + Starts a system-controlled move of this window.If the method is called after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationErrortrue if the move was successfully initiated and + false if the window is maximized. + Boolean + Starts a system-controlled move of this window. +

+ When called from a mouseDown event, this method begins a mouse-driven move + sequence that continues until a mouseUp event occurs. +

+

+ When called from other code this method begins a keyboard- or mouse-driven move sequence + consistent with the operating system's default sequence. +

+ +

During a move sequence, a series of events will be dispatched as the window origin moves. For + each incremental move, first a moving event is dispatched and then, if the + moving event is not canceled, the window location is updated and a + move event is dispatched. If a moving event is + canceled, the move sequence is immediately terminated.

+ +
The following example shows how to move a window in response to a + mouseDown event: + +var initOpts:NativeWindowInitOptions = new NativeWindowInitOptions(); +var win:NativeWindow = new NativeWindow(initOpts); +win.activate(); +win.stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + +function mouseDownHandler(event:MouseEvent):void +{ + win.startMove(); +} +
startResize + Starts a system-controlled resize operation of this window.If the method is called after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationErrortrue if the resize was successfully initiated and + false if the window is maximized. + + BooleanedgeOrCornerStringBRA constant from the NativeWindowResize class that specifies + which edge or corner of this window to resize. The following are + valid values: + +

+ ValueVertical alignmentHorizontal alignmentNativeWindowResize.TOPTopCenterNativeWindowResize.BOTTOMBottomCenterNativeWindowResize.LEFTCenterLeftNativeWindowResize.RIGHTCenterRightNativeWindowResize.TOP_LEFTTopLeftNativeWindowResize.TOP_RIGHTTopRightNativeWindowResize.BOTTOM_LEFTBottomLeftNativeWindowResize.BOTTOM_RIGHTBottomRightNativeWindowResize.NONE---- +

+ +
+ Starts a system-controlled resize operation of this window. +

+ When called from a mouseDown event handler this method begins a mouse-driven resizing + sequence that continues until a mouseUp event occurs. +

+

+ When called from other code this method begins a keyboard- or mouse-driven resizing sequence consistent + with the operating system's default sequence. +

+

During the resize sequence, a series of events will be dispatched as the + window dimensions change. For each incremental change, first a resizing + event is dispatched and then, if the resizing event is not + canceled, the window dimensions are updated and a resize event is dispatched. + If a resizing event is canceled, the the sequence is immediately terminated.

+ +
The following example shows how to resize a window in response to a + mouseDown event: + +stage.addEventListener(MouseEvent.MOUSE_DOWN, onResizeCommand); + +function onResizeCommand(event:MouseEvent):void +{ + var win:NativeWindow = event.target.nativeWindow; + var resizeFrom:String = ""; + if (event.stageY < win.height * .33) + { + resizeFrom = NativeWindowResize.TOP; + } + else if (event.stageY > win.height * .66) + { + resizeFrom = NativeWindowResize.BOTTOM; + } + if (event.stageX < win.width * .33) + { + resizeFrom += NativeWindowResize.LEFT; + } + else if (event.stageX > win.width * .66) + { + resizeFrom += NativeWindowResize.RIGHT; + } + win.startResize(resizeFrom); +} +
flash.display.NativeWindowResize
active + Indicates whether this window is the active application window.Boolean + Indicates whether this window is the active application window. + +

Use the activate() method to make a window active.

+ +
flash.display.NativeWindow.activate()flash.desktop.NativeApplication.activate()
alwaysInFront + Specifies whether this window will always be in front of other windows (including + those of other applications).Boolean + Specifies whether this window will always be in front of other windows (including + those of other applications). + +

There are two groups of windows in the system depth order. Windows in the + alwaysInFront group are always displayed in front of all other + windows. Depth ordering between windows within the same group is determined normally. + In other words, activating a window will bring it in front of other windows + in its group.

+ +

Changing alwaysInFront from false to true will + bring the window to the top of all other windows. Changing the property from true + to false will send the window to the back of "alwaysInFront" windows, but still + in front of other windows. Setting the property to its current value will not change the window + depth order. Setting the alwaysInFront property of a window that has an owner + has no effect.

+ +

The alwaysInFront property should rarely be set to true since + windows with this setting will appear in front of the windows of other applications + even when the other application is active.

+ +

OS behavior notes:

+
  • Some Linux window managers do not display windows that have the alwaysInFront + property set to in front of fullscreen windows.
  • On Mac® OS X, setting alwaysInFront to true will + have no effect when the displayState property of the window stage + is fullScreen or fullScreenInteractive.
+ +
The following examples force a window to be displayed in front + of all other windows (that are not similarly forced to the front): + +windowObj.alwaysInFront = true; + With a reference to a display object on the window stage: + +displayObject.stage.nativeWindow.alwaysInFront=true; + From a JavaScript routine running in an HTMLLoader object in the + window (or a root HTML window): + +window.nativeWindow.alwaysInFront = true; +
bounds + The size and location of this window.flash.geom:RectangleIf the rectangle is null or contains invalid values. + ArgumentErrorArgumentErrorIf the bounds property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The size and location of this window. +

+ The dimensions of a window include any system chrome. The dimensions of a window's stage are equal to the + dimensions of the window, minus the size of any system chrome. Changing + the width and height of the window will change the stage's stageWidth and stageHeight. + The reverse also applies; changing the stage dimensions will change the window size. +

+

In a root HTML window, the outerWidth and outerHeight properties + are equivalent to the window height and width properties. + The innerWidth and innerHeight properties equal + the stage.stageWidth and stage.stageHeight + properties minus the thickness of any automatic scrollbars displayed + by the window.

+

+ A resize event is dispatched whenever the width or height of this window + changes. Likewise, a move event is dispatched whenever the origin (x,y) of this window + changes. On Mac OS and Windows, setting the bounds property directly will not + dispatch a moving or resizing event. However, on Linux the NativeWindow + does dispatch a moving and resizing events when you set + the bounds property. +

+

+ Setting the bounds property of a window is equivalent to setting its + x, y, width, and height properties. + Likewise, setting any of the individual dimensions is equivalent to setting the + bounds property. When you set all the dimensions at the same time by using the + bounds property, fewer events are dispatched. +

+

The order in which the individual dimensions are set is not guaranteed. On Linux + window managers that do not allow windows to extend off the desktop area, a change to an individual + property may be blocked even though the net affect of applying all the property changes would + have resulted in a legal window.

+ +

If the width or height specified is less than the minimum or greater than the maximum allowed + width or height, then the window width or height is set to the closest legal size. The factors that + determine the minimum and maximum width and height are the following:

+ +
  • The minSize and maxSize properties of the + NativeWindow object
  • The minimum and maximum operating system limits, which are the values of + NativeWindow.systemMinSize and NativeWindow.systemMaxSize.
  • The maximum width and height of a window in Adobe AIR, which are each 4095 pixels. + (In AIR 1.5 and earlier, the maximum width and height of a window is 2880 pixels each.)
  • The minimum width and height required by any displayed system chrome.
+ +

Pixel values are rounded to the nearest integer when the position or dimensions of + a window are changed.

+ +
The following examples set the bounds of a window with a + reference to a NativeWindow object: + +windowObj.bounds = new Rectangle(200, 200, 1000, 800); + With a reference to a display object on the window stage: + +displayObject.stage.nativeWindow.bounds = new Rectangle(20, 20, 800, 600); + From a JavaScript routine running in an HTMLLoader object in the window (or a root HTML window): + +window.nativeWindow.bounds = new air.Rectangle(20, 20, 800, 600); +
flash.display.NativeWindowInitOptions.resizable
closed + Indicates whether this window has been closed.Boolean + Indicates whether this window has been closed. + +

Accessing the following properties on a closed window will + throw an illegal operation error:

+
  • title
  • bounds
  • x, y, width, height
  • displayState
  • visible
+

Likewise, calling the following methods on a closed window will + also throw an illegal operation error:

+
  • minimize()
  • maximize()
  • restore()
  • startResize()
  • startMove()
+ +
The following examples show how to access the closed property + of a window: + +var isWindowClosed:Boolean = windowObj.closed; + With a reference to a display object on the window stage: + +var isWindowClosed:Boolean = displayObject.stage.nativeWindow.closed; + From a JavaScript routine running in an HTMLLoader object in the window + (or root HTML window): + +var isWindowClosed = window.nativeWindow.closed; +
displayState + The display state of this window.StringIf the displayState property is accessed + after this window has been closed. + IllegalOperationErrorflash.errors:IllegalOperationError + The display state of this window. +

+ Constants for the possible values are defined in the NativeWindowDisplayState class: +

+
  • NativeWindowDisplayState.NORMAL
  • NativeWindowDisplayState.MINIMIZED
  • NativeWindowDisplayState.MAXIMIZED
+ +
The following example shows how to get the current window + display state given a reference to the window object: + +var state:String = windowObj.displayState; +
flash.display.NativeWindowDisplayState
height + The height of this window in pixels.NumberIf the value set is null or invalid. + ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The height of this window in pixels. + +

The dimensions of a window include any system window chrome that is displayed. + The height of the usable display area inside a window is available from the + Stage.stageHeight property.

+ +

Changing the height property of a window is equivalent to changing the + height through the bounds property.

+ +

If the height specified is less than the minimum or greater than the maximum allowed height, + then the window height is set to the closest legal size. The factors that determine the minimum + and maximum height are the following:

+ +
  • The minSize.x and maxSize.x properties of the + NativeWindow object
  • The minimum and maximum operating system limits, which are the values of + NativeWindow.systemMinSize.x and NativeWindow.systemMaxSize.x.
  • The maximum height of a window in Adobe AIR, which is 4095 pixels + (2880 pixels in AIR 1.5 and earlier).
+ +

On Linux, setting the height property is an asynchronous operation.

+ +

+ To detect the completion of the height change, listen for + the resize event, which is dispatched on all platforms. +

+ +

Pixel values are rounded to the nearest integer when the height of + a window is changed.

+ +
flash.display.NativeWindow.boundsflash.display.Stage.stageHeight
isSupported + Indicates whether native windows are supported on the client system.Boolean + Indicates whether native windows are supported on the client system. + + maxSize + The maximum size for this window.flash.geom:PointIf assigned size is not within the + operating system minimum and maximum window sizes. + IllegalOperationErrorflash.errors:IllegalOperationErrorIf size is forbidden for the content's current privilege. + SecurityErrorSecurityErrorIf the size is null or contains invalid values. + ArgumentErrorArgumentErrorIf the maxSize property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The maximum size for this window. + +

The size limit is specified as the coordinates of a Point object. + The point x property corresponds to the window width, + the y property to the window height.

+ +

+ The maxSize restriction is enforced for window resizing operations + invoked both through ActionScript + code and through the operating system. +

+

+ Setting maxSize will change the window bounds if the + current bounds are larger than the new maximum size. +

+ +

If the width or height specified is greater than the maximum allowed width or height, + then the window width is set to the closest legal size. The factors that determine the minimum + and maximum width and height are the following:

+ +
  • The maximum operating system limit, which is the value NativeWindow.systemMaxSize.
  • The maximum width and height of a window in Adobe AIR, which is 4095 pixels for each. + (In AIR 1.5 and earlier, the maximum width and height of a window is 2880 pixels each.)
+ +

+ Note: On some operating systems, such as Mac OS X, maximizing a window will only enlarge the window to the maxSize + value even if the maximized window will be smaller than the operating system screen. The window will still be + in the maximized display state. +

+ +
The following examples show how to set the maximum allowed + size for a window. + +windowObj.maxSize = new Point(1040,920); + With a reference to a display object on the window stage: + +displayObject.stage.nativeWindow.maxSize = new Point(800,600); + From a JavaScript routine running in an HTMLLoader object in a window + (or in a root HTML window): + +window.nativeWindow.maxSize = new air.Point(960,960); +
flash.display.NativeWindow.systemMinSizeflash.display.NativeWindow.systemMaxSize
maximizable + Reports the maximizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the maximizable setting used to create this window. + +

The maximizable setting cannot be changed after a window is created.

+ +

Note: Some Linux window managers allow windows to be maximized by the user even when the + maximizable property is set to false.

+ +
flash.display.NativeWindowInitOptions.maximizable
menu + The native menu for this window.flash.display:NativeMenu + The native menu for this window. + +

When a NativeMenu object is assigned to the window menu + property, a native menu will be displayed for a window if + NativeWindow.supportsMenu is true, unless the window + systemChrome property is NativeWindowSystemChrome.NONE.

+ +

Note: Assigning a menu to a window when NativeWindow.supportsMenu + is false or when the window systemChrome property is + NativeWindowSystemChrome.NONE is allowed, but does nothing. Be sure to + use the NativeWindow.supportsMenu property to determine whether the + operating system supports window menus. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +
flash.display.NativeWindow.supportsMenu
minSize + The minimum size for this window.flash.geom:PointIf the assigned size is not within the + operating system minimum and maximum window sizes. + IllegalOperationErrorflash.errors:IllegalOperationErrorIf size is forbidden for the content's current privilege. + SecurityErrorSecurityErrorIf the size is null or contains invalid values. + ArgumentErrorArgumentErrorif the minSize property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The minimum size for this window. + +

The size limit is specified as the coordinates of a Point object. + The point x property corresponds to the window width, + the y property to the window height.

+

+ Setting minSize, will change the window bounds if the + current bounds are smaller than the new minimum size. +

+

+ The minSize restriction is enforced for window resizing operations + invoked both through ActionScript + code and through the operating system. +

+

+ Note: The width and height of any displayed system chrome may + make it impossible to set a window as small as the specified minimum size. +

+ +
The following examples show how to set the minimum allowed + size for a window: + +windowObj.minSize = new Point(200,80); + With a reference to a display object on the window stage: + +displayObject.stage.nativeWindow.minSize = new Point(120,60); + From a JavaScript routine running in an HTMLLoader object in a window + (or in a root HTML window): + +window.nativeWindow.minSize = new air.Point(80,60); +
flash.display.NativeWindow.systemMinSizeflash.display.NativeWindow.systemMaxSize
minimizable + Reports the minimizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the minimizable setting used to create this window. + +

The minimizable setting cannot be changed after a window is created.

+ +

Note: Some Linux window managers allow windows to be minimizable by the user even when the + minimizable property is set to false.

+ +
flash.display.NativeWindowInitOptions.minimizable
owner + The NativeWindow object that owns this window.flash.display:NativeWindow + The NativeWindow object that owns this window. + +

Window ownership is established when a window is created and cannot be changed. + To create a window that has an owner, set the owning NativeWindow object as the + owner property of the NativeWindowInitOptions object used to create + the owned window.

+ +

Note: On Linux, some window managers do not display owned windows in front of the + owning window when the owner is in fullscreen mode.

+ +
flash.display.NativeWindowInitOptions.owner
resizable + Reports the resizable setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the resizable setting used to create this window. + +

The resizable setting cannot be changed after a window is created.

+ +
flash.display.NativeWindowInitOptions.resizable
stage + The Stage object for this window.flash.display:Stage + The Stage object for this window. The + Stage object is the root object in the display list architecture used in ActionScript + 3.0-based SWF content. + +

+ The stage is the root of the display list for the window. Add visual display objects to a window by + adding them to the stage or to another object already in the display list of this stage. The stage + dimensions are those of the window client area when the window uses system chrome. The stage + dimensions are equal to the dimensions of the window if system chrome is not used. +

+ + + +
The following example shows how to set stage properties for a + NativeWindow instance: + +import flash.display.StageAlign; + +windowObj.stage.align = StageAlign.TOP_LEFT; +
flash.display.Stage
supportsMenu + Indicates whether AIR supports native window menus on the current computer system.Boolean + Indicates whether AIR supports native window menus on the current computer system. + +

When NativeWindow.supportsMenu is true, + a native menu will be displayed for a window when a NativeMenu + object is assigned to the window menu property (unless the window + systemChrome property is NativeWindowSystemChrome.NONE). + Be sure to use the NativeWindow.supportsMenu property to determine whether the + operating system native window menus. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +

Note: Assigning a menu to a window when NativeWindow.supportsMenu + is false or when the window systemChrome property is + NativeWindowSystemChrome.NONE is allowed, but does nothing.

+ +
flash.display.NativeMenuflash.desktop.NativeApplication.supportsMenu
supportsNotification + Indicates whether AIR supports window notification cueing on the current computer system.Boolean + Indicates whether AIR supports window notification cueing on the current computer system. + +

When NativeWindow.supportsNotification is true, + calling the window's notifyUser() method will result in a + visual cue to the user that an event of interest has occurred. This visual + cue will conform to the operating system convention of the native system. + For example, on Windows®, the task bar icon will flash.

+ +

Note: Calling notifyUser() when + NativeWindow.supportsNotification is false + is allowed, but does nothing.

+ +
flash.display.NativeWindow.notifyUser()
supportsTransparency + Indicates whether AIR supports native windows with transparent pixels.Boolean + Indicates whether AIR supports native windows with transparent pixels. + +

When NativeWindow.supportsTransparency is true, + transparency in pixels of a native window will be honored, if the window + transparent property is set to true. Opacity of + all pixels will be set to 1 if NativeWindow.supportsTransparency + is false, regardless of the value of the window transparent + property. Fully transparent pixels will render as black when + NativeWindow.supportsTransparency is false. + Be sure to use the NativeWindow.supportsTransparency property to determine whether the + operating system supports transparency. Using other means (such as Capabilities.os) + to determine support can lead to programming errors (if some possible target operating systems + are not considered).

+ +

Note: The value of this property might change while an application + is running, based on user preferences set for the operating system.

+ +
flash.display.NativeWindow.transparent
systemChrome + Reports the system chrome setting used to create this window.StringWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the system chrome setting used to create this window. + +

The values returned by NativeWindow.systemChrome will be + one of the constants defined in the NativeWindowSystemChrome class.

+ +

The system chrome setting cannot be changed after a window is created.

+ +
The following example shows how to get the system chrome type for a window: + +var sysChromeType:String = windowObj.systemChrome; + With a reference to a display object on the window stage: + +var sysChromeType:String = displayObject.stage.nativeWindow.systemChrome; + From a JavaScript routine running in an HTMLLoader object in the window + (or root HTML window): + +var sysChromeType = window.nativeWindow.systemChrome; + The following example shows how to change the apparent + system chrome and transparency settings by creating a new window and moving all child + display objects to the new window: + +import flash.display.NativeWindow; +import flash.display.NativeWindowSystemChrome; +import flash.display.NativeWindowInitOptions; + +public function deChromeWindow(oldWindow:NativeWindow):NativeWindow{ + if(oldWindow.systemChrome != NativeWindowSystemChrome.NONE){ + var newOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); + newOptions.systemChrome = NativeWindowSystemChrome.NONE; + newOptions.transparent = true; + + var newWindow:NativeWindow = new NativeWindow(newOptions); + newWindow.stage.stageWidth = oldWindow.stage.stageWidth; + newWindow.stage.stageHeight = oldWindow.stage.stageHeight; + newWindow.stage.align = oldWindow.stage.align; + newWindow.stage.scaleMode = oldWindow.stage.scaleMode; + + for(var i:int = 0; i < oldWindow.stage.numChildren; i++){ + newWindow.stage.addChild(oldWindow.stage.getChildAt(i)); + } + newWindow.activate(); + oldWindow.close(); + + return newWindow; + } + return oldWindow; +} + +
flash.display.NativeWindowSystemChromeflash.display.NativeWindowInitOptions.systemChrome
systemMaxSize + The largest window size allowed by the operating system.flash.geom:Point + The largest window size allowed by the operating system. + +

The size limit is specified as the coordinates of a Point object. + The point x property corresponds to the window width, + the y property to the window height.

+ +

In addition to the operating system size limit, AIR has a maximum + window size limit of 4095 by 4095 pixels (2880 pixels by 2880 pixels + in AIR 1.5 and earlier). And an application can set + a limit using the maxSize property of the NativeWindow object.

+ +
systemMinSize + The smallest window size allowed by the operating system.flash.geom:Point + The smallest window size allowed by the operating system. + +

The size limit is specified as the coordinates of a Point object. + The point x property corresponds to the window width, + the y property to the window height.

+ +
title + The window title.StringIf the property is accessed after this window has been closed. + IllegalOperationErrorflash.errors:IllegalOperationError + The window title. +

+ The title will appear in the system chrome for the window, if displayed, as well as in other system-dependent + locations (such as the task bar). +

+ +
The following example sets the title of a window object: + +windowObj.title = "Window Title"; +
transparent + Reports the transparency setting used to create this window.BooleanWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the transparency setting used to create this window. + +

The transparent property cannot be changed after a window is created. + Transparency affects both the visual appearance and the mouse behavior of + the window. On Windows and Mac OS X, the window will not capture mouse events when the alpha value + of the pixel is below a certain threshold, which varies between about .06 and .01 depending on the operating + system. On Linux, the the window will capture mouse events above completely transparent areas and + therefore will prevent users from accessing other windows and items on the desktop.

+ + +

Note: Window transparency cannot always be supported. If the user's + operating system configuration is such that transparency is not available, the + window will be created without transparency. Areas that would have been transparent + are composited against black. Use the NativeWindow.supportsTransparency + property to determine whether window transparency is supported.

+ +
flash.display.NativeWindowInitOptions.transparent
type + Reports the window type setting used to create this window.StringWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Reports the window type setting used to create this window. + +

The values returned by NativeWindow.type will be + one of the constants defined in the NativeWindowType class.

+ +

The type setting cannot be changed after a window is created.

+ +
flash.display.NativeWindowTypeflash.display.NativeWindowInitOptions.type
visible + Specifies whether this window is visible.BooleanWhen trying to set to false without sufficient privilege. + SecurityErrorSecurityErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies whether this window is visible. + +

+ An invisible window is not displayed on the desktop, but all window + properties and methods are valid. +

+

+ By default, visible is set to false. To display + a window, set visible to true or call + NativeWindow.activate(). +

+

If this window has an owner, the visible state of that owning window determines + whether this window is displayed. If the owning window is not displayed, then + any owned windows are not displayed, even if their visible properties + are true.

+

+ Note: On Mac OS X, setting visible=false on a + minimized window will not remove the window icon from the dock. If a + user subsequently clicks the dock icon, the window will return to the + visible state and be displayed on the desktop. +

+ +
The following examples show how to access the visible property + of a window: + +windowObj.visible = true; + With a reference to a display object on the window stage: + +displayObj.stage.nativeWindow.visible = true; + From a JavaScript routine running in an HTMLLoader object in the window + (or root HTML window): + +window.nativeWindow.visible = true; +
activate()
width + The width of this window in pixels.NumberIf the value set is null or invalid. + ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The width of this window in pixels. + +

The dimensions reported for a native window include any system window chrome + that is displayed. + The width of the usable display area inside a window is available from the + Stage.stageWidth property.

+ +

Changing the width property of a window is equivalent to changing the + width through the bounds property.

+ +

If the width specified is less than the minimum or greater than the maximum allowed width, + then the window width is set to the closest legal size. The factors that determine the minimum + and maximum width are the following:

+ +
  • The minSize.y and maxSize.y properties of the + NativeWindow object
  • The minimum and maximum operating system limits, which are the values of + NativeWindow.systemMinSize.y and NativeWindow.systemMaxSize.y.
  • The maximum width of a window in Adobe AIR, which is 4095 pixels + (2880 pixels in AIR 1.5 and earlier).
+ +

On Linux, setting the width property is an asynchronous operation.

+ +

+ To detect the completion of the width change, listen for + the resize event, which is dispatched on all platforms. +

+ +

Pixel values are rounded to the nearest integer when the width of + a window is changed.

+ +
flash.display.NativeWindow.boundsflash.display.Stage.stageWidth
x + The horizontal axis coordinate of this window's top left corner relative to the + origin of the operating system desktop.NumberIf the value set is null or invalid. + ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The horizontal axis coordinate of this window's top left corner relative to the + origin of the operating system desktop. + +

On systems with more than one monitor, x can be negative. If you + save the value, perhaps to reposition a window at its previous location, you + should always verify that the window is placed in a usable location when the + position is restored. Changes in screen resolution or monitor arrangement can + can result in a window being placed off screen. Use the Screen class to obtain + information about the desktop geometry.

+ +

Changing the x property of a window is equivalent to changing the + location through the bounds property.

+ +

On Linux, setting the x property is an asynchronous operation.

+ +

+ To detect the completion of the position change, listen for + the move event, which is dispatched on all platforms. +

+ +

Pixel values are rounded to the nearest integer when the x-coordinate of + a window is changed.

+ +
flash.display.NativeWindow.boundsflash.display.Screen
y + The vertical axis coordinate of this window's top left corner relative to the + upper left corner of the operating system's desktop.NumberIf the value set is null or invalid. + ArgumentErrorArgumentErrorIf the property is accessed after this window has been closed. + + IllegalOperationErrorflash.errors:IllegalOperationError + The vertical axis coordinate of this window's top left corner relative to the + upper left corner of the operating system's desktop. + +

On systems with more than one monitor, y can be negative. If you + save the value, perhaps to reposition a window at its previous location, you + should always verify that the window is placed in a usable location when the + position is restored. Changes in screen resolution or monitor arrangement can + can result in a window being placed off screen. Use the Screen class to obtain + information about the desktop geometry.

+ +

Changing the y property of a window is equivalent to changing the + location through the bounds property.

+ +

On Linux, setting the y property is an asynchronous operation.

+ +

+ To detect the completion of the position change, listen for + the move event, which is dispatched on all platforms. +

+ +

Pixel values are rounded to the nearest integer when the y-coordinate of + a window is changed.

+ +
flash.display.NativeWindow.boundsflash.display.Screen
Stage + The Stage class represents the main drawing area.flash.display:DisplayObjectContainer + The Stage class represents the main drawing area. + +

For SWF content running in the browser (in + Flash® Player), the Stage represents the entire area where Flash + content is shown. For content running in AIR on desktop operating systems, each NativeWindow object has a corresponding + Stage object.

+ +

The Stage object is not globally accessible. You need to access it through the + stage property of a DisplayObject instance.

+ +

The Stage class has several ancestor classes — DisplayObjectContainer, InteractiveObject, + DisplayObject, and EventDispatcher — from which it inherits properties and methods. + Many of these properties and methods are either inapplicable to Stage objects, + or require security checks when called on a Stage object. The properties and methods that + require security checks are documented as part of the Stage class.

+ +

In addition, the following inherited properties are inapplicable to Stage objects. If you + try to set them, an IllegalOperationError is thrown. These properties may always be read, but + since they cannot be set, they will always contain default values.

+ +
  • accessibilityProperties
  • alpha
  • blendMode
  • cacheAsBitmap
  • contextMenu
  • filters
  • focusRect
  • loaderInfo
  • mask
  • mouseEnabled
  • name
  • opaqueBackground
  • rotation
  • scale9Grid
  • scaleX
  • scaleY
  • scrollRect
  • tabEnabled
  • tabIndex
  • transform
  • visible
  • x
  • y
+ +

Some events that you might expect to be a part of the Stage class, + such as enterFrame, exitFrame, + frameConstructed, and render, + cannot be Stage events because a reference to the Stage object + cannot be guaranteed to exist in every situation where these events + are used. Because these events cannot be dispatched by the Stage + object, they are instead dispatched by every DisplayObject instance, + which means that you can add an event listener to + any DisplayObject instance to listen for these events. + These events, which are part of the DisplayObject class, + are called broadcast events to differentiate them from events + that target a specific DisplayObject instance. + Two other broadcast events, activate and deactivate, + belong to DisplayObject's superclass, EventDispatcher. + The activate and deactivate events + behave similarly to the DisplayObject broadcast events, except + that these two events are dispatched not only by all DisplayObject + instances, but also by all EventDispatcher instances and instances + of other EventDispatcher subclasses. + For more information on broadcast events, see the DisplayObject class.

+ +
The following example uses the StageExample class to dispatch + events whenever the stage is activated or resized. This is accomplished by performing the following steps: +
  1. The class constructor first sets the Flash application to be fixed, regardless of the size of + the Flash Player window and then adds two event listeners with the + activateHandler() and resizeHandler() methods.
  2. The activateHandler() method runs when the left mouse button is clicked.
  3. The resizeHandler() method runs when the stage is resized.
+ +package { + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.Event; + + public class StageExample extends Sprite { + + public function StageExample() { + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + stage.addEventListener(Event.ACTIVATE, activateHandler); + stage.addEventListener(Event.RESIZE, resizeHandler); + } + + private function activateHandler(event:Event):void { + trace("activateHandler: " + event); + } + + private function resizeHandler(event:Event):void { + trace("resizeHandler: " + event); + trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight); + } + } +} +
flash.display.DisplayObjectstageVideoAvailability + Dispatched by the Stage object when the state of the stageVideos property changes.flash.events.StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITYflash.events.StageVideoAvailabilityEvent + Dispatched by the Stage object when the state of the stageVideos property changes. + + orientationChange + Dispatched by the Stage object when the stage orientation changes.flash.events.StageOrientationEvent.ORIENTATION_CHANGEflash.events.StageOrientationEvent + Dispatched by the Stage object when the stage orientation changes. + +

Orientation changes can occur when the user rotates the device, opens a slide-out keyboard, + or when the setAspectRatio() is called.

+ +

Note: If the autoOrients property is false, then the stage orientation + does not change when a device is rotated. Thus, StageOrientationEvents are only dispatched for + device rotation when autoOrients is true.

+ +
orientationChanging + Dispatched by the Stage object when the stage orientation begins changing.flash.events.StageOrientationEvent.ORIENTATION_CHANGINGflash.events.StageOrientationEvent + Dispatched by the Stage object when the stage orientation begins changing. + +

Important: orientationChanging events are not dispatched on Android devices.

+ +

Note: If the autoOrients property is false, then the stage orientation + does not change when a device is rotated. Thus, StageOrientationEvents are only dispatched for + device rotation when autoOrients is true.

+ +
fullScreen + Dispatched when the Stage object enters, or leaves, full-screen mode.flash.events.FullScreenEvent.FULL_SCREENflash.events.FullScreenEvent + Dispatched when the Stage object enters, or leaves, full-screen mode. A change + in full-screen mode can be initiated through ActionScript, or the user invoking a keyboard shortcut, + or if the current focus leaves the full-screen window. + + resize + Dispatched when the scaleMode property of the Stage object is set to + StageScaleMode.NO_SCALE and the SWF file is resized.flash.events.Event.RESIZEflash.events.Event + Dispatched when the scaleMode property of the Stage object is set to + StageScaleMode.NO_SCALE and the SWF file is resized. + mouseLeave + Dispatched by the Stage object when the pointer moves out of the + stage area.flash.events.Event.MOUSE_LEAVEflash.events.Event + Dispatched by the Stage object when the pointer moves out of the + stage area. If the mouse button is pressed, the event is not dispatched. + addChildAt + + Adds a child DisplayObject instance to this DisplayObjectContainer + instance.Calling the addChildAt() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThe DisplayObject instance that you pass in the + child parameter. + + flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this + DisplayObjectContainer instance. + + indexintThe index position to which the child is added. If you specify a + currently occupied index position, the child object that exists at that position and all + higher positions are moved up one position in the child list. + + + + Adds a child DisplayObject instance to this DisplayObjectContainer + instance. The child is added + at the index position specified. An index of 0 represents the back (bottom) + of the display list for this DisplayObjectContainer object. + +

For example, the following example shows three display objects, labeled a, b, and c, at + index positions 0, 2, and 1, respectively:

+ +

+ +

If you add a child object that already has a different display object container as + a parent, the object is removed from the child list of the other display object container.

+ +
addChild + + Adds a child DisplayObject instance to this DisplayObjectContainer instance.Calling the addChild() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThe DisplayObject instance that you pass in the + child parameter. + + flash.display:DisplayObjectchildflash.display:DisplayObjectThe DisplayObject instance to add as a child of this DisplayObjectContainer instance. + + + + Adds a child DisplayObject instance to this DisplayObjectContainer instance. The child is added + to the front (top) of all other children in this DisplayObjectContainer instance. (To add a child to a + specific index position, use the addChildAt() method.) + +

If you add a child object that already has a different display object container as + a parent, the object is removed from the child list of the other display object container.

+

Note: The command stage.addChild() can cause problems with a published SWF file, + including security problems and conflicts with other loaded SWF files. There is only one Stage within a Flash runtime instance, + no matter how many SWF files you load into the runtime. So, generally, objects + should not be added to the Stage, directly, at all. The only object the Stage should + contain is the root object. Create a DisplayObjectContainer to contain all of the items on the + display list. Then, if necessary, add that DisplayObjectContainer instance to the Stage.

+ +
addEventListener + + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.Calling the addEventListener method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this situation, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrortypeStringThe type of event. + + listenerFunctionThe listener function that processes the event. This function must accept + an Event object as its only parameter and must return nothing, as this example shows: + + + function(evt:Event):void + +

The function can have any name.

+ +
useCaptureBooleanfalse + + Determines whether the listener works in the capture phase or the + target and bubbling phases. If useCapture is set to true, + the listener processes the event only during the capture phase and not in the + target or bubbling phase. If useCapture is false, the + listener processes the event only during the target or bubbling phase. To listen for + the event in all three phases, call addEventListener twice, once with + useCapture set to true, then again with + useCapture set to false. + + priorityint0The priority level of the event listener. The priority is designated by + a signed 32-bit integer. The higher the number, the higher the priority. All listeners + with priority n are processed before listeners of priority n-1. If two + or more listeners share the same priority, they are processed in the order in which they + were added. The default priority is 0. + + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or + weak. A strong reference (the default) prevents your listener from being garbage-collected. + A weak reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbage-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. + + + +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's + priority, you must first call removeListener(). Then you can register the + listener again with the new priority level.

+ +

Keep in mind that after the listener is registered, subsequent calls to + addEventListener() with a different type or + useCapture value result in the creation of a separate listener registration. + For example, if you first register a listener with useCapture set to + true, it listens only during the capture phase. If you call + addEventListener() again using the same listener object, but with + useCapture set to false, you have two separate listeners: one + that listens during the capture phase and another that listens during the target and + bubbling phases. +

+ +

You cannot register an event listener for only the target phase or the bubbling + phase. Those phases are coupled during registration because bubbling + applies only to the ancestors of the target node.

+ +

If you no longer need an event listener, remove it by calling + removeEventListener(), or memory problems could result. Event listeners are not automatically + removed from memory because the garbage + collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference + parameter is set to true).

+ +

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event listeners + attached to it move along with it.

+ + +

If the event listener is being registered on a node while an event is being processed + on this node, the event listener is not triggered during the current phase but can be + triggered during a later phase in the event flow, such as the bubbling phase.

+ +

If an event listener is removed from a node while an event is being processed on the node, + it is still triggered by the current actions. After it is removed, the event listener is + never invoked again (unless registered again for future processing).

+ +
assignFocus + Sets keyboard focus to the interactive object specified by objectToFocus, with + the focus direction specified by the direction parameter.If focus cannot be set to the target or direction is not a valid type. + + ErrorErrorobjectToFocusflash.display:InteractiveObjectThe object to focus, or null to clear the focus from + any element on the Stage. + + directionStringThe direction from which objectToFocus is being focused. + Valid values are enumerated as constants in the FocusDirection class. + + Assigns keyboard focus to an interactive object and specifies the direction focus is coming from. + + + Sets keyboard focus to the interactive object specified by objectToFocus, with + the focus direction specified by the direction parameter. + +

The concept of focus direction must be defined by the application (or application framework). + No intrinsic focus sorting of interactive objects exists, although you could use other available + properties to establish an ordering principle. For example, you could sort interactive objects + according to their positions on the Stage or in the display list. Calling assignFocus() + is equivalent to setting the Stage.focus property, with the additional ability to + indicate the direction from which the focus is being set.

+ +

The objectToFocus will dispatch a focusIn event on receiving focus. + The direction property of the FocusEvent object will report the setting of the + direction parameter.

+ +

If you assign an HTMLLoader object to the objectToFocus parameter, the HTMLLoader + object selects the appropriate focusable object in the HTML DOM, based on the direction + parameter value. If it is FocusDirection.BOTTOM, the focusable object in the HTML + DOM at the end of the reading order is given focus. If it is FocusDirection.TOP, + the focusable object in the HTML DOM at the beginning of the reading order is given focus. + If it is NONE, the HTMLLoader object receives focus without changing its + current focused element.

+ +
flash.display.Stage.focusflash.display.FocusDirectionflash.events.FocusEvent
dispatchEvent + + Dispatches an event into the event flow.Calling the dispatchEvent() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorA value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called + on the event. + + Booleaneventflash.events:EventThe Event object that is dispatched into the event flow. + If the event is being redispatched, a clone of the event is created automatically. + After an event is dispatched, its target property cannot be changed, so you + must create a new copy of the event for redispatching to work. + + + + Dispatches an event into the event flow. The event target is the EventDispatcher + object upon which the dispatchEvent() method is called. + + getChildAtflash.display:DisplayObjectindexintgetChildIndexintchildflash.display:DisplayObjecthasEventListener + + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event.Calling the hasEventListener() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorA value of true if a listener of the specified type is registered; + false otherwise. + BooleantypeStringThe type of event. + + + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event. This allows you to determine where an EventDispatcher object has altered + handling of an event type in the event flow hierarchy. To determine whether a specific + event type actually triggers an event listener, use willTrigger(). + +

The difference between hasEventListener() and willTrigger() + is that hasEventListener() examines only the object to + which it belongs, whereas willTrigger() examines the entire + event flow for the event specified by the type parameter. + +

+ +

When hasEventListener() is called from a LoaderInfo object, only the + listeners that the caller can access are considered.

+ +
invalidate + Calling the invalidate() method signals Flash runtimes to alert display objects + on the next opportunity it has to render the display list (for example, when the playhead + advances to a new frame).Signals Flash runtimes to update properties of display objects on the next opportunity + it has to refresh the Stage. + + + Calling the invalidate() method signals Flash runtimes to alert display objects + on the next opportunity it has to render the display list (for example, when the playhead + advances to a new frame). After you call the invalidate() method, when the display + list is next rendered, the Flash runtime sends a render event to each display object that has + registered to listen for the render event. You must call the invalidate() + method each time you want the Flash runtime to send render events. + +

The render event gives you an opportunity to make changes to the display list + immediately before it is actually rendered. This lets you defer updates to the display list until the + latest opportunity. This can increase performance by eliminating unnecessary screen updates.

+ +

The render event is dispatched only to display objects that are in the same + security domain as the code that calls the stage.invalidate() method, + or to display objects from a security domain that has been granted permission via the + Security.allowDomain() method.

+ +
flash.events.Event.RENDER
isFocusInaccessible + Determines whether the Stage.focus property returns null for + security reasons.true if the object that has focus belongs to a security sandbox to which + the SWF file does not have access. + + BooleanDetermines whether the Stage.focus property would return null + for security reasons. + + + + Determines whether the Stage.focus property returns null for + security reasons. + In other words, isFocusInaccessible returns true if the + object that has focus belongs to a security sandbox to which the SWF file does not have access. + + removeChildAt + + Removes a child DisplayObject from the specified index position in the child list of + the DisplayObjectContainer.Calling the removeChildAt() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the object to be removed. To avoid this, + the owner of that object can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThe DisplayObject instance that was removed. + + flash.display:DisplayObjectindexintThe child index of the DisplayObject to remove. + + + + Removes a child DisplayObject from the specified index position in the child list of + the DisplayObjectContainer. The parent property of the removed child is set to + null, and the object is garbage collected if no other references to the child exist. The index + positions of any display objects above the child in the DisplayObjectContainer are decreased by 1. + +

The garbage collector reallocates unused memory space. When a variable or + object is no longer actively referenced or stored somewhere, the garbage collector sweeps + through and wipes out the memory space it used to occupy if no other references to it exist.

+ +
removeChildflash.display:DisplayObjectchildflash.display:DisplayObjectsetAspectRatio + Sets the stage to an orientation with the specified aspect ratio.The value passed as the newAspectRatio parameter is not valid. + The value must match one of the constants defined in the StageAspectRatio class. + + ArgumentErrorArgumentErrornewAspectRatioStringThe type code for the desired aspect ratio (StageAspectRatio.PORTRAIT + or StageAspectRatio.LANDSCAPE). + + + Sets the stage to an orientation with the specified aspect ratio. + +

If the stage orientation changes as a result of the method call, the Stage object dispatches + an orientationChange event.

+ +

To check whether device orientation is supported, check the value of the + Stage.supportsOrientantionChange property.

+ +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test + for support at run time using the Stage.supportsOrientantionChange property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
StageAspectRatiosupportsOrientationChange
setChildIndex + + Changes the position of an existing child in the display object container.Calling the setChildIndex() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorchildflash.display:DisplayObjectThe child DisplayObject instance for which you want to change + the index number. + + indexintThe resulting index number for the child display object. + + + + Changes the position of an existing child in the display object container. + This affects the layering of child objects. For example, the following example shows three + display objects, labeled a, b, and c, at index positions 0, 1, and 2, respectively: + +

+ +

When you use the setChildIndex() method and specify an index position + that is already occupied, the only positions that change are those in between the display object's former and new position. + All others will stay the same. + If a child is moved to an index LOWER than its current index, all children in between will INCREASE by 1 for their index reference. + If a child is moved to an index HIGHER than its current index, all children in between will DECREASE by 1 for their index reference. + For example, if the display object container + in the previous example is named container, you can swap the position + of the display objects labeled a and b by calling the following code:

+ + container.setChildIndex(container.getChildAt(1), 0); + +

This code results in the following arrangement of objects:

+ +

+ +
setOrientation + Sets the stage to the specified orientation.The value passed as the newOrientation parameter is not valid. + The value must match one of the constants defined in the StageOriention class, except for the + StageOrientation.UNKNOWN constant. + + ArgumentErrorArgumentErrornewOrientationStringThe new orientation of the stage. + + + Sets the stage to the specified orientation. + +

Set the newOrientation parameter + to one of the following four values defined as constants in the StageOrientation class:

+ +

+ StageOrientation constantStage orientationStageOrientation.DEFAULTSet the stage orientation to the default orientation (right-side up).StageOrientation.ROTATED_RIGHTSet the stage orientation to be rotated right.StageOrientation.ROTATED_LEFTSet the stage orientation to be rotated left.StageOrientation.UPSIDE_DOWNSet the stage orientation to be rotated upside down. +

+ +

Do not set the parameter to StageOrientation.UNKNOWN or any + string value other than those listed in the table.

+ +

To check whether changing device orientation is supported, check the value of the + Stage.supportsOrientantionChange property. Check the list provided by + the supportedOrientations property to determine which orientations + are supported by the current device.

+ +

Setting the orientation is an asynchronous operation. It is not guaranteed + to be complete immediately after you call the setOrientation() method. + Add an event listener for the orientationChange event to determine when + the orientation change is complete.

+ +

Important: The setOrientation() method was not supported on Android + devices before AIR 2.6.

+ +
autoOrientssupportsOrientationChangeStageOrientationEventStageOrientationorientationChangeflash.events:StageOrientationEventThe stage has resized as a result of the + call to the setOrientation() method. + + The stage has resized as a result of the + call to the setOrientation() method.
swapChildrenAtindex1intindex2intswapChildren + + Swaps the z-order (front-to-back order) of the two specified child objects.Calling the swapChildrenAt() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the owner of either of the objects to be swapped. To avoid this, + the object owners can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorchild1flash.display:DisplayObjectThe first child object. + + child2flash.display:DisplayObjectThe second child object. + + + + Swaps the z-order (front-to-back order) of the two specified child objects. All other child + objects in the display object container remain in the same index positions. + + willTrigger + + Checks whether an event listener is registered with this EventDispatcher object or any of + its ancestors for the specified event type.Calling the willTrigger() method of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorA value of true if a listener of the specified type will be triggered; false otherwise. + BooleantypeStringThe type of event. + + + Checks whether an event listener is registered with this EventDispatcher object or any of + its ancestors for the specified event type. This method returns true if an + event listener is triggered during any phase of the event flow when an event of the + specified type is dispatched to this EventDispatcher object or any of its descendants. + +

The difference between the hasEventListener() and the willTrigger() + methods is that hasEventListener() examines only the object to which it belongs, + whereas the willTrigger() method examines the entire event flow for the event specified by the + type parameter.

+ +

When willTrigger() is called from a LoaderInfo object, only the + listeners that the caller can access are considered.

+ +
align + A value from the StageAlign class that specifies the alignment of the stage in + Flash Player or the browser.String + A value from the StageAlign class that specifies the alignment of the stage in + Flash Player or the browser. The following are valid values: + +

+ ValueVertical AlignmentHorizontalStageAlign.TOPTopCenterStageAlign.BOTTOMBottomCenterStageAlign.LEFTCenterLeftStageAlign.RIGHTCenterRightStageAlign.TOP_LEFTTopLeftStageAlign.TOP_RIGHTTopRightStageAlign.BOTTOM_LEFTBottomLeftStageAlign.BOTTOM_RIGHTBottomRight +

+ +

The align property is only available to an object that is in the same security sandbox + as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the + calling object by calling the Security.allowDomain() method or the Security.alowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide.

+ +
flash.display.StageAlign
allowsFullScreen + Specifies whether this stage allows the use of the full screen mode + + Boolean + Specifies whether this stage allows the use of the full screen mode + + autoOrients + Specifies whether the stage automatically changes orientation when the device orientation changes.Boolean + Specifies whether the stage automatically changes orientation when the device orientation changes. + +

The initial value of this property is derived from the autoOrients + element of the application descriptor and defaults to false. When changing the + property to false, the behavior is not guaranteed. On some devices, the + stage remains in the current orientation. On others, the stage orientation changes to + a device-defined "standard" orientation, after which, no further stage orientation changes occur.

+ +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test + for support at run time using the Stage.supportsOrientantionChange property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
deviceOrientationsupportsOrientationChange
colorCorrectionSupport + Specifies whether the Flash runtime is running on an operating system that supports + color correction and whether the color profile of the main (primary) + monitor can be read and understood by the Flash runtime.String + Specifies whether the Flash runtime is running on an operating system that supports + color correction and whether the color profile of the main (primary) + monitor can be read and understood by the Flash runtime. This property also returns the default state + of color correction on the host system (usually the browser). + Currently the return values can be: +

The three possible values are strings with corresponding constants in the flash.display.ColorCorrectionSupport class:

+
  • "unsupported": Color correction is not available.
  • "defaultOn": Always performs color correction.
  • "defaultOff": Never performs color correction.
+ +
The following example shows an event handler that populates a text field with + the current environment's ability to support color correction or not. First, it checks the value + of stage.colorCorrectionSupport to see if it is DEFAULT_ON or DEFAULT_OFF, + values from the ColorCorrectionSupport class. If the property is either value, then the text field displays the current value. + Otherwise, if the value is neither DEFAULT_ON nor DEFAULT_OFF, the text field displays "unsupported". + +function addHandler(add_event:Event) { + if (stage.colorCorrectionSupport == ColorCorrectionSupport.DEFAULT_ON || stage.colorCorrectionSupport == ColorCorrectionSupport.DEFAULT_OFF) { + lblHasCM.text = "stage.colorCorrectionSupport: " + stage.colorCorrectionSupport; + } + else { + lblHasCM.text = "stage.colorCorrectionSupport: unsupported"; + } +} + +
flash.display.ColorCorrectionSupportcolorCorrection
colorCorrection + Controls Flash runtime color correction for displays.StringAttempts to use monitor color correction + + + + Controls Flash runtime color correction for displays. + Color correction works only if the main monitor is assigned a valid ICC color profile, which specifies + the device's particular color attributes. + By default, the Flash runtime tries to match the color correction of its host (usually a browser). + +

Use the Stage.colorCorrectionSupport property + to determine if color correction is available on the current system and the default state. +. If color correction is available, all colors on the stage are assumed to be in + the sRGB color space, which is the most standard color space. Source profiles of input devices are not considered during color correction. + No input color correction is applied; only the stage output is mapped to the main + monitor's ICC color profile.

+ +

In general, the benefits of activating color management include predictable and consistent color, better conversion, + accurate proofing and more efficient cross-media output. Be aware, though, that color management does not provide + perfect conversions due to devices having a different gamut from each other or original images. + Nor does color management eliminate the need for custom or edited profiles. + Color profiles are dependent on browsers, operating systems (OS), OS extensions, output devices, and application support.

+ +

Applying color correction degrades the Flash runtime performance. + A Flash runtime's color correction is document style color correction because + all SWF movies are considered documents with implicit sRGB profiles. + Use the Stage.colorCorrectionSupport property to tell the Flash runtime + to correct colors when displaying the SWF file (document) to the display color space. + Flash runtimes only compensates for differences between monitors, not for differences between input devices (camera/scanner/etc.). +

+ +

The three possible values are strings with corresponding constants in the flash.display.ColorCorrection class:

+
  • "default": Use the same color correction as the host system.
  • "on": Always perform color correction.
  • "off": Never perform color correction.
+ +
The following example shows an event handler that toggles color correction in the current + SWF file and populates a text field with + the current state of color correction. If the Stage.colorCorrection value is not a value + from the ColorCorrection class, then the handler reports an error. + +function addHandler(add_event:Event) { + switch(stage.colorCorrection) { + case ColorCorrection.ON: + stage.colorCorrection = ColorCorrection.OFF; + lblCMEnableState.text = "State: " + stage.colorCorrection; + break; + case ColorCorrection.OFF: + stage.colorCorrection = ColorCorrection.DEFAULT; + lblCMEnableState.text = "State: " + stage.colorCorrection; + break; + case ColorCorrection.DEFAULT: + stage.colorCorrection = ColorCorrection.ON; + lblCMEnableState.text = "State: " + stage.colorCorrection; + break; + default: + lblCMEnableState.text = "Error."; + break; +} + +
flash.display.ColorCorrectioncolorCorrectionSupport
coloruintdeviceOrientation + The physical orientation of the device.String + The physical orientation of the device. + +

On devices with slide-out keyboards, the state of the keyboard has a higher priority in determining the device orientation + than the rotation detected by the accelerometer. Thus on a portrait-aspect device with a side-mounted keyboard, + the deviceOrientation property will report ROTATED_LEFT when the keyboard is open + no matter how the user is holding the device.

+ +

Use the constants defined in the StageOrientation class when setting or comparing values for this property.

+ +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test + for support at run time using the Stage.supportsOrientationChange property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
autoOrientsStageOrientation
displayState + A value from the StageDisplayState class that specifies which display state to use.StringCalling the displayState property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + Trying to set the displayState property while the settings dialog is displayed, without a user response, or + if the param or embed HTML tag's allowFullScreen attribute is not set to + true throws a security error. + + SecurityErrorSecurityError + A value from the StageDisplayState class that specifies which display state to use. The following + are valid values: + +
  • StageDisplayState.FULL_SCREEN Sets AIR application or Flash runtime to expand the + stage over the user's entire screen, with keyboard input disabled.
  • StageDisplayState.FULL_SCREEN_INTERACTIVE Sets the AIR application to expand the + stage over the user's entire screen, with keyboard input allowed. + (Not available for content running in Flash Player.)
  • StageDisplayState.NORMAL Sets the Flash runtime back to the standard stage display mode.
+ +

The scaling behavior of the movie in full-screen mode is determined by the scaleMode + setting (set using the Stage.scaleMode property or the SWF file's embed + tag settings in the HTML file). If the scaleMode property is set to noScale + while the application transitions to full-screen mode, the Stage width and height + properties are updated, and the Stage dispatches a resize event. If any other scale mode is set, + the stage and its contents are scaled to fill the new screen dimensions. The Stage object retains its original + width and height values and does not dispatch a resize event.

+ +

The following restrictions apply to SWF files that play within an HTML page (not those using the stand-alone + Flash Player or not running in the AIR runtime):

+ +
  • To enable full-screen mode, add the allowFullScreen parameter to the object + and embed tags in the HTML page that includes the SWF file, with allowFullScreen set + to "true", as shown in the following example: + + <param name="allowFullScreen" value="true" /> + ... + <embed src="example.swf" allowFullScreen="true" ... > + +

    An HTML page may also use a script to generate SWF-embedding tags. You need to alter the script + so that it inserts the proper allowFullScreen settings. HTML pages generated by Flash Professional and + Flash Builder use the AC_FL_RunContent() function to embed references to SWF files, and you + need to add the allowFullScreen parameter settings, as in the following:

    + + AC_FL_RunContent( ... "allowFullScreen", "true", ... )
  • Full-screen mode is initiated in response to a mouse click or key press by the user; the movie cannot change + Stage.displayState without user input. Flash runtimes restrict keyboard input in full-screen mode. + Acceptable keys include keyboard shortcuts that terminate full-screen mode and non-printing keys such as arrows, space, Shift, + and Tab keys. Keyboard shortcuts that terminate full-screen mode are: Escape (Windows, Linux, and Mac), Control+W (Windows), + Command+W (Mac), and Alt+F4. +

    A Flash runtime dialog box appears over the movie when users enter full-screen mode to inform the users they are in + full-screen mode and that they can press the Escape key to end full-screen mode.

  • Starting with Flash Player 9.0.115.0, full-screen works the same in windowless mode as it does in window mode. + If you set the Window Mode (wmode in the HTML) to Opaque Windowless (opaque) + or Transparent Windowless (transparent), full-screen can be initiated, + but the full-screen window will always be opaque.
+ +

These restrictions are not present for SWF content running in the + stand-alone Flash Player or in AIR. AIR supports an interactive full-screen mode which allows keyboard input.

+ +

For AIR content running in full-screen mode, the system screen saver + and power saving options are disabled while video content is playing and until either the video stops + or full-screen mode is exited.

+ +

On Linux, setting displayState to StageDisplayState.FULL_SCREEN or + StageDisplayState.FULL_SCREEN_INTERACTIVE is an asynchronous operation.

+ +
The following example creates an interactive demonstration of + how to create a fullscreen experience by modifying the displayState + property.

Note: Fullscreen can only be triggered in certain situations, such as if the + user has clicked or pressed a key, due to security restrictions. When run in a + browser, the allowFullScreen property must be set to true.

+ +package { + import flash.display.Sprite; + import flash.display.Stage; + import flash.events.*; + import flash.net.NetConnection; + import flash.net.NetStream; + import flash.media.Video; + + public class FullScreenExample extends Sprite + { + private var videoURL:String = "testVideo.flv"; + private var connection:NetConnection; + private var stream:NetStream; + private var video:Video; + + public function FullScreenExample() { + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + + loaderInfo.addEventListener(Event.INIT, createMouseListener); + } + + private function createMouseListener(event:Event):void { + stage.addEventListener(MouseEvent.CLICK,toggleFullScreen); + } + + private function toggleFullScreen(event:MouseEvent):void { + switch(stage.displayState) { + case "normal": + stage.displayState = "fullScreen"; + break; + case "fullScreen": + default: + stage.displayState = "normal"; + break; + } + } + + // Video related: + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Unable to locate video: " + videoURL); + break; + } + } + private function connectStream():void { + var stream:NetStream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + + video = new Video(stage.stageWidth,stage.stageHeight); + video.attachNetStream(stream); + stream.play(videoURL); + addChild(video); + } + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + private function asyncErrorHandler(event:AsyncErrorEvent):void { + // ignore AsyncErrorEvent events. + } + } +} +
flash.display.StageDisplayStateStage.scaleModeflash.events.FullScreenEventflash.events.Event.RESIZE
focus + The interactive object with keyboard focus; or null if focus is not set + or if the focused object belongs to a security sandbox to which the calling object does not + have access.flash.display:InteractiveObjectThrows an error if focus cannot be set to the target. + + ErrorErrorThe object with keyboard focus. + + The interactive object with keyboard focus; or null if focus is not set + or if the focused object belongs to a security sandbox to which the calling object does not + have access. + + The following sets the initial focus to the text field myTF so the user can start typing without having to click anything. + If you test this code within the authoring tool interface, you can only have access to a few keys because the host (browser or tool) interprets most + key presses first. To see this example work as intended, compile it and run the SWF file. + +var myTF:TextField = new TextField(); +myTF.border =true; +myTF.type = TextFieldType.INPUT; + +addChild(myTF); +stage.focus= myTF; +frameRate + Gets and sets the frame rate of the stage.NumberCalling the frameRate property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + Gets and sets the frame rate of the stage. The frame rate is defined as frames per second. + By default the rate is set to the frame rate of the first SWF file loaded. Valid range for the frame rate + is from 0.01 to 1000 frames per second. + +

Note: An application might not be able to follow + high frame rate settings, either because the target platform is not fast enough or the player is + synchronized to the vertical blank timing of the display device (usually 60 Hz on LCD devices). + In some cases, a target platform might also choose to lower the maximum frame rate if it + anticipates high CPU usage.

+ +

For content running in Adobe AIR, setting the frameRate property of one Stage + object changes the frame rate for all Stage objects (used by different NativeWindow objects). +

+ +
fullScreenHeight + Returns the height of the monitor that will be used when going to full screen size, if that state + is entered immediately.uint + Returns the height of the monitor that will be used when going to full screen size, if that state + is entered immediately. If the user has multiple monitors, the monitor that's used is the + monitor that most of the stage is on at the time. + +

Note: If the user has the opportunity to move the browser from one + monitor to another between retrieving the value and going to full screen + size, the value could be incorrect. If you retrieve the value in an event handler that + sets Stage.displayState to StageDisplayState.FULL_SCREEN, the value will be + correct.

+ +

This is the pixel height of the monitor and is the same as the + stage height would be if Stage.align is set to StageAlign.TOP_LEFT + and Stage.scaleMode is set to StageScaleMode.NO_SCALE.

+ + +
This example creates a green rectangle the size of the stage and places a red square on it that + it activates as a button. Clicking the red square triggers the enterFullScreen() event handler, + which sets the fullScreenSourceRect property and enters full screen mode. To set the + fullScreenSourceRect property, the event handler starts with the location and dimensions of the + red square. It then compares the aspect ratio (width divided by height) of the red square to the + aspect ratio of the stage at full screen width and height so that it can expand the rectangle + (fullScreenSourceRect) to match the screen's aspect ratio. The result is that the red + square occupies the entire height of the monitor with the green background visible on each side. + If the aspect ratio was not matched, the stage background color, which is white by default, would show + on each side instead of the green background. + +

Note: Test this example in the browser. In the Flash Publish Settings dialog, on the HTML tab, + select the template Flash Only - Allow Full Screen. Specify the Flash Player version 9.0.115.0, and make sure + the Flash and HTML formats are selected on the Formats tab. Then publish and open the resulting HTML file in + the browser.

+ + +import flash.display.Sprite; +import flash.display.Stage; +import flash.display.StageDisplayState; +import flash.events.MouseEvent; +import flash.geom.Rectangle; + +// cover the stage with a green rectangle +var greenRect:Sprite = new Sprite(); +greenRect.graphics.beginFill(0x00FF00); +greenRect.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); +addChild(greenRect); + +// create red square on stage, turn it into a button for going to full screen +var redSquare:Sprite = new Sprite(); +redSquare.graphics.beginFill(0xFF0000); +redSquare.graphics.drawRect(0, 0, 300, 300); +redSquare.x = 50; +redSquare.y = 50; +redSquare.addEventListener(MouseEvent.CLICK, enterFullScreen); +redSquare.buttonMode = true; +addChild(redSquare); + +function enterFullScreen(e:MouseEvent):void +{ + // we will go to full screen zoomed in on the red square + var redSquare:Sprite = e.target as Sprite; + var fullScreenRect:Rectangle = new Rectangle(redSquare.x, redSquare.y, redSquare.width, redSquare.height); + + // calculate aspect ratio of the red square + var rectAspectRatio:Number = fullScreenRect.width / fullScreenRect.height; + + // calculate aspect ratio of the screen + var screenAspectRatio:Number = stage.fullScreenWidth / stage.fullScreenHeight; + + // change the fullScreenRect so that it covers the entire screen, keeping it centered on the redSquare + // try commenting out this section to see what happens if you do not fix the aspect ratio. + if (rectAspectRatio > screenAspectRatio) { + var newHeight:Number = fullScreenRect.width / screenAspectRatio; + fullScreenRect.y -= ((newHeight - fullScreenRect.height) / 2); + fullScreenRect.height = newHeight; + } else if (rectAspectRatio < screenAspectRatio) { + var newWidth:Number = fullScreenRect.height * screenAspectRatio; + fullScreenRect.x -= ((newWidth - fullScreenRect.width) / 2); + fullScreenRect.width = newWidth; + } + + // go to full screen + stage.fullScreenSourceRect = fullScreenRect; + stage.displayState = StageDisplayState.FULL_SCREEN; +} +
displayStatefullScreenSourceRectfullScreenWidthscaleModeStageDisplayStateflash.events.Event.RESIZEflash.events.FullScreenEvent
fullScreenSourceRect + Sets the Flash runtime to scale a specific region of the stage to full-screen mode.flash.geom:Rectangle + Sets the Flash runtime to scale a specific region of the stage to full-screen mode. + If available, the Flash runtime scales in hardware, which uses the graphics and video card on a user's computer, + and generally displays content more quickly than software scaling. + +

When this property is set to a valid rectangle and the displayState property is set to full-screen mode, + the Flash runtime scales the specified area. The actual Stage size in pixels within ActionScript does not change. + The Flash runtime enforces a minimum limit for the size of the rectangle to accommodate the standard "Press Esc to exit full-screen mode" message. + This limit is usually around 260 by 30 pixels but can vary on platform and Flash runtime version.

+ +

This property can only be set when the Flash runtime is not in full-screen mode. + To use this property correctly, set this property first, then set the displayState property to full-screen mode, as shown in the code examples.

+

To enable scaling, set the fullScreenSourceRect property to a rectangle object:

+ + // valid, will enable hardware scaling + stage.fullScreenSourceRect = new Rectangle(0,0,320,240); + + +

To disable scaling, set the fullScreenSourceRect=null in ActionScript 3.0, and undefined in ActionScript 2.0.

+ + stage.fullScreenSourceRect = null; + + +

The end user also can select within Flash Player Display Settings to turn off hardware scaling, which is enabled by default. + For more information, see www.adobe.com/go/display_settings.

+ + +
To take advantage of hardware scaling, you set the whole stage or part of the stage to full-screen mode. + The following ActionScript 3.0 code sets the whole stage to full-screen mode: + + +import flash.geom.*; +{ + stage.fullScreenSourceRect = new Rectangle(0,0,320,240); + stage.displayState = StageDisplayState.FULL_SCREEN; +} + In the following example, the user can switch between playing a video in full or normal + screen mode by clicking on the stage. If the SWF for this example is running in Flash Player 9.0.115.0 + or later, then it will use hardware acceleration to improve the full-screen scaling of the display. + +

Before using the full-screen mode with hardware scaling, the following conditions must be met:

+ +
  1. Flash Player version 9.0.115.0 or later is needed, + as well as an authoring tool that supports it.
  2. HTML templates need to be modified to support full screen. The allowFullScreen + attribute must be set to true for the object and embed tag. + (The scripts that generate SWF-embedding tags must also allow for full screen.) For sample of + files that can be used for Flash Builder, see the article, + Exploring full-screen + mode in Flash Player 9.
  3. Your application must have permission and access to an FLV video file. In this example, it is assumed + that Flash Video (FLV) file is in the same directory as the SWF file.
  4. The user must allow access to full screen.
  5. For additional information on hardware scaling, see the article + Exploring Flash Player support for high-definition H.264 video and AAC audio for Flash Player.
+ +

An FLV file is loaded using NetConnection and NetStream objects. Since the FLV file + is in the same directory as the SWF file and will connect via HTTP, the NetConnection.connect() + method's parameter is set to null. The connect NetConnection object + reports its status by dispatching a netStatus event which invokes + the netStatusHandler() method. The netStatusHandler() method + checks if the connection was successful and invokes connectStream() method, + which creates a NetStream object that takes the NetConnection object as a parameter. + It also creates a video object and attached the NetStream object to the video object. + The video object then is added to the display list and the stream is set to play. Since + the FLV video file does not contain metadata or cue point information, an AsyncError + event will be dispatched. A listener must be set up to handle the event. Here the listener + is set up and it ignores the event. Another listener for netStatus event is also + set up for the NetStream object. It will display an error message if the stream was not found. + (Note that netStatusHandler() could be used to handle any number of different + status information reported for the stream or connection.)

+ +

When the properties and methods of a loaded SWF file are accessible, the + createMouseListener() method is invoked. It sets up an event listener for when + the mouse is clicked on the stage. The toggleFullScreen() method checks if + the display state is in the full or normal screen mode. If it is normal, the size of the video object + is set to the size of the video stream. The fullScreenSourceRect property is set + to a rectangle matching the dimensions of the video object. Then the Stage.displayMode + property is set to full screen, which causes the video in the source rectangle to expand to fill + the full screen area. If system requirements are met, the machine's graphics hardware will be + used to improve the performance of the full-screen video rendering and the display state is set + to full-screen mode. In order to catch any security error that may occur while switching to + the full-screen mode, a try...catch is used. (Note that the display state must be + set to full-screen mode after the fullScreenSourceRect property is set.) Before + switching to the normal-screen mode, the video object's width and height are set back to the saved + original video object's width and height. Otherwise, the changes made to the video object for + the full-screen mode will determine the width and height.

+ + +package { + import flash.display.Sprite; + import flash.display.StageDisplayState; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + import flash.events.NetStatusEvent; + import flash.events.AsyncErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.events.MouseEvent; + import flash.events.Event; + import flash.geom.Rectangle; + + public class Stage_fullScreenSourceRectExample2 extends Sprite { + private var videoURL:String = "testVideo1.flv"; + private var connection:NetConnection; + private var stream:NetStream; + private var myVideo:Video; + private var savedWidth:uint; + private var savedHeight:uint; + + public function Stage_fullScreenSourceRectExample2() { + + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + + loaderInfo.addEventListener(Event.INIT, createMouseListener); + } + + private function createMouseListener(event:Event):void { + stage.addEventListener(MouseEvent.CLICK, toggleFullScreen); + } + + private function toggleFullScreen(event:MouseEvent):void { + + if(stage.displayState == StageDisplayState.NORMAL) { + myVideo.width = myVideo.videoWidth; + myVideo.height = myVideo.videoHeight; + + try { + stage.fullScreenSourceRect = new Rectangle(myVideo.x, myVideo.y, + myVideo.width, myVideo.height); + stage.displayState = StageDisplayState.FULL_SCREEN; + + } catch (e:SecurityError) { + trace ("A security error occurred while switching to full screen: " + event); + myVideo.width = savedWidth; + myVideo.height = savedHeight; + } + + }else { + myVideo.width = savedWidth; + myVideo.height = savedHeight; + stage.displayState = StageDisplayState.NORMAL; + } + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace ("Unable to locate video: " + videoURL); + break; + } + } + + private function connectStream():void { + var stream:NetStream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + + myVideo = new Video(); + myVideo.attachNetStream(stream); + stream.play(videoURL); + + savedWidth = myVideo.width; + savedHeight = myVideo.height; + + addChild(myVideo); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function asyncErrorHandler(event:AsyncErrorEvent):void { + + } + } +} +
flash.display.StageDisplayStateStage.displayStateStage.scaleModeflash.events.FullScreenEventflash.events.Event.RESIZE
fullScreenWidth + Returns the width of the monitor that will be used when going to full screen size, if that state + is entered immediately.uint + Returns the width of the monitor that will be used when going to full screen size, if that state + is entered immediately. If the user has multiple monitors, the monitor that's used is the + monitor that most of the stage is on at the time. + +

Note: If the user has the opportunity to move the browser from one + monitor to another between retrieving the value and going to full screen + size, the value could be incorrect. If you retrieve the value in an event handler that + sets Stage.displayState to StageDisplayState.FULL_SCREEN, the value will be + correct.

+ +

This is the pixel width of the monitor and is the same as the stage width would be if + Stage.align is set to StageAlign.TOP_LEFT and + Stage.scaleMode is set to StageScaleMode.NO_SCALE.

+ + +
This example creates a green rectangle the size of the stage and places a red square on it that + it activates as a button. Clicking the red square triggers the enterFullScreen() event handler, + which sets the fullScreenSourceRect property and enters full screen mode. To set the + fullScreenSourceRect property, the event handler starts with the location and dimensions of the + red square. It then compares the aspect ratio (width divided by height) of the red square to the + aspect ratio of the stage at full screen width and height so that it can expand the rectangle + (fullScreenSourceRect) to match the screen's aspect ratio. The result is that the red + square occupies the entire height of the monitor with the green background visible on each side. + If the aspect ratio was not matched, the stage background color, which is white by default, would show + on each side instead of the green background. + +

Note: Test this example in the browser. In the Flash Publish Settings dialog, on the HTML tab, + select the template Flash Only - Allow Full Screen. Specify the Flash Player version 9.0.115.0, and make sure + the Flash and HTML formats are selected on the Formats tab. Then publish and open the resulting HTML file in + the browser.

+ + +import flash.display.Sprite; +import flash.display.Stage; +import flash.display.StageDisplayState; +import flash.events.MouseEvent; +import flash.geom.Rectangle; + +// cover the stage with a green rectangle +var greenRect:Sprite = new Sprite(); +greenRect.graphics.beginFill(0x00FF00); +greenRect.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); +addChild(greenRect); + +// create red square on stage, turn it into a button for going to full screen +var redSquare:Sprite = new Sprite(); +redSquare.graphics.beginFill(0xFF0000); +redSquare.graphics.drawRect(0, 0, 300, 300); +redSquare.x = 50; +redSquare.y = 50; +redSquare.addEventListener(MouseEvent.CLICK, enterFullScreen); +redSquare.buttonMode = true; +addChild(redSquare); + +function enterFullScreen(e:MouseEvent):void +{ + // we will go to full screen zoomed in on the red square + var redSquare:Sprite = e.target as Sprite; + var fullScreenRect:Rectangle = new Rectangle(redSquare.x, redSquare.y, redSquare.width, redSquare.height); + + // calculate aspect ratio of the red square + var rectAspectRatio:Number = fullScreenRect.width / fullScreenRect.height; + + // calculate aspect ratio of the screen + var screenAspectRatio:Number = stage.fullScreenWidth / stage.fullScreenHeight; + + // change the fullScreenRect so that it covers the entire screen, keeping it centered on the redSquare + // try commenting out this section to see what happens if you do not fix the aspect ratio. + if (rectAspectRatio > screenAspectRatio) { + var newHeight:Number = fullScreenRect.width / screenAspectRatio; + fullScreenRect.y -= ((newHeight - fullScreenRect.height) / 2); + fullScreenRect.height = newHeight; + } else if (rectAspectRatio < screenAspectRatio) { + var newWidth:Number = fullScreenRect.height * screenAspectRatio; + fullScreenRect.x -= ((newWidth - fullScreenRect.width) / 2); + fullScreenRect.width = newWidth; + } + + // go to full screen + stage.fullScreenSourceRect = fullScreenRect; + stage.displayState = StageDisplayState.FULL_SCREEN; +} +
displayStatefullScreenHeightfullScreenSourceRectscaleModeStageDisplayStateflash.events.Event.RESIZEflash.events.FullScreenEvent
height + + Indicates the height of the display object, in pixels.NumberReferencing the height property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorIt is always illegal to set the height property of a Stage object, + even if the calling object is the Stage owner (the main SWF file). + + IllegalOperationErrorflash.errors:IllegalOperationError + + Indicates the height of the display object, in pixels. The height is calculated based on the bounds of the content of the display object. + When you set the height property, the scaleY property is adjusted accordingly, as shown in the + following code: + + + var rect:Shape = new Shape(); + rect.graphics.beginFill(0xFF0000); + rect.graphics.drawRect(0, 0, 100, 100); + trace(rect.scaleY) // 1; + rect.height = 200; + trace(rect.scaleY) // 2; + +

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a height + of 0, even if you try to set height to a different value.

+ +
mouseChildren + + Determines whether or not the children of the object are mouse, or user input device, enabled.BooleanReferencing the mouseChildren property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + + Determines whether or not the children of the object are mouse, or user input device, enabled. + If an object is enabled, a user can interact with it by using a mouse or user input device. The default is true. + +

This property is useful when you create a button with an instance of the Sprite class + (instead of using the SimpleButton class). When you use a Sprite instance to create a button, + you can choose to decorate the button by using the addChild() method to add additional + Sprite instances. This process can cause unexpected behavior with mouse events because + the Sprite instances you add as children can become the target object of a mouse event + when you expect the parent instance to be the target object. To ensure that the parent + instance serves as the target objects for mouse events, you can set the + mouseChildren property of the parent instance to false.

+

No event is dispatched by setting this property. You must use the + addEventListener() method to create interactive functionality.

+ +
nativeWindow + A reference to the NativeWindow object containing this Stage.flash.display:NativeWindow + A reference to the NativeWindow object containing this Stage. + +

The window represents the native operating system window; the Stage + represents the content contained by the window. This property is only + valid for content running in AIR on platforms that support the NativeWindow class. + On other platforms, this property will be null. + In Flash Player (content running in a + browser), this property will also be null.

+ +
numChildren + + Returns the number of children of this object.intReferencing the numChildren property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + + Returns the number of children of this object. + + orientation + The current orientation of the stage.String + The current orientation of the stage. This property is set to one of four values, + defined as constants in the StageOrientation class: + + StageOrientation constantStage orientationStageOrientation.DEFAULTThe screen is in the default orientation (right-side up).StageOrientation.ROTATED_RIGHTThe screen is rotated right.StageOrientation.ROTATED_LEFTThe screen is rotated left.StageOrientation.UPSIDE_DOWNThe screen is rotated upside down.StageOrientation.UNKNOWNThe application has not yet determined the initial orientation of the screen. + You can add an event listener for the orientationChange event + +

To set the stage orientation, use the setOrientation() method.

+ +

Important: orientation property is supported on Android devices from 2.6 namespace onwards.

+ +
StageOrientationautoOrientsdeviceOrientationsupportsOrientationChange
quality + A value from the StageQuality class that specifies which rendering quality is used.StringCalling the quality property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + A value from the StageQuality class that specifies which rendering quality is used. + The following are valid values: + +
  • StageQuality.LOW—Low rendering quality. Graphics are not + anti-aliased, and bitmaps are not smoothed, but runtimes still use mip-mapping.
  • StageQuality.MEDIUM—Medium rendering quality. Graphics are + anti-aliased using a 2 x 2 pixel grid, bitmap smoothing is dependent on the Bitmap.smoothing setting. + Runtimes use mip-mapping. This setting is suitable for movies that do not contain text.
  • StageQuality.HIGH—High rendering quality. Graphics are anti-aliased + using a 4 x 4 pixel grid, and bitmap smoothing is dependent on the Bitmap.smoothing setting. + Runtimes use mip-mapping. This is the default rendering quality setting that Flash Player uses.
  • StageQuality.BEST—Very high rendering quality. Graphics are + anti-aliased using a 4 x 4 pixel grid. If Bitmap.smoothing is true the runtime uses a high quality + downscale algorithm that produces fewer artifacts (however, using StageQuality.BEST with Bitmap.smoothing set to true + slows performance significantly and is not a recommended setting).
+ +

Higher quality settings produce better rendering of scaled bitmaps. However, higher + quality settings are computationally more expensive. In particular, when rendering scaled video, + using higher quality settings can reduce the frame rate. +

+ +

In the desktop profile of Adobe AIR, quality can be set + to StageQuality.BEST or StageQuality.HIGH (and the default value + is StageQuality.HIGH). Attempting to set it to another value has no effect + (and the property remains unchanged). In the moble profile of AIR, all four quality settings + are available. The default value on mobile devices is StageQuality.MEDIUM.

+ +

For content running in Adobe AIR, setting the quality property of one Stage + object changes the rendering quality for all Stage objects (used by different NativeWindow objects). +

+ + Note: The operating system draws the device fonts, + which are therefore unaffected by the quality property. + +
flash.display.StageQualityflash.display.Bitmap.smoothing
scaleMode + A value from the StageScaleMode class that specifies which scale mode to use.StringCalling the scaleMode property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorA value from the StageScaleMode class that specifies which scale mode to use. + + + + A value from the StageScaleMode class that specifies which scale mode to use. + The following are valid values: + +
  • StageScaleMode.EXACT_FIT—The entire application is visible + in the specified area without trying to preserve the original aspect ratio. Distortion can occur, and the application may appear stretched or compressed. +
  • StageScaleMode.SHOW_ALL—The entire application is visible + in the specified area without distortion while maintaining the original aspect ratio of the application. + Borders can appear on two sides of the application. +
  • StageScaleMode.NO_BORDER—The entire application fills the specified area, + without distortion but possibly with some cropping, while maintaining the original aspect ratio + of the application. +
  • StageScaleMode.NO_SCALE—The entire application is fixed, so that + it remains unchanged even as the size of the player window changes. Cropping might + occur if the player window is smaller than the content. +
+ +
flash.display.StageScaleMode
showDefaultContextMenu + Specifies whether to show or hide the default items in the Flash runtime + context menu.BooleanCalling the showDefaultContextMenu property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorSpecifies whether to show or hide the default items in the Flash Player + context menu. + + + + Specifies whether to show or hide the default items in the Flash runtime + context menu. + +

If the showDefaultContextMenu property is set to true (the + default), all context menu items appear. If the showDefaultContextMenu property + is set to false, only the Settings and About... menu items appear.

+ +
softKeyboardRect + The area of the stage that is currently covered by the software keyboard.flash.geom:Rectangle + The area of the stage that is currently covered by the software keyboard. + +

The area has a size of zero (0,0,0,0) when the soft keyboard is not visible.

+ +

When the keyboard opens, the softKeyboardRect is set at the time the + softKeyboardActivate event is dispatched. If the keyboard changes size while open, + the runtime updates the softKeyboardRect property and dispatches an + additional softKeyboardActivate event.

+ +

Note: On Android, the area covered by the keyboard is estimated when + the operating system does not provide the information necessary to determine the exact + area. This problem occurs in fullscreen mode and also when the keyboard opens in response to + an InteractiveObject receiving focus or invoking the requestSoftKeyboard() method.

+ +
SoftKeyboardEventInteractiveObject.needsSoftKeyboard
stageFocusRect + Specifies whether or not objects display a glowing border when they have focus.BooleanCalling the stageFocusRect property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorSpecifies whether or not objects display a glowing border when they have focus. + + + + Specifies whether or not objects display a glowing border when they have focus. + + stageHeight + The current height, in pixels, of the Stage.intCalling the stageHeight property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + The current height, in pixels, of the Stage. + +

If the value of the Stage.scaleMode property is set to StageScaleMode.NO_SCALE + when the user resizes the window, the Stage content maintains its size while the + stageHeight property changes to reflect the new height size of the screen area occupied by + the SWF file. (In the other scale modes, the stageHeight property always reflects the original + height of the SWF file.) You can add an event listener for the resize event and then use the + stageHeight property of the Stage class to determine the actual pixel dimension of the resized + Flash runtime window. The event listener allows you to control how + the screen content adjusts when the user resizes the window.

+ +

Air for TV devices have slightly different behavior than desktop devices + when you set the stageHeight property. + If the Stage.scaleMode + property is set to StageScaleMode.NO_SCALE and you set the stageHeight + property, the stage height does not change until the next + frame of the SWF.

+ +

Note: In an HTML page hosting the SWF file, both the object and embed tags' height attributes must be set to a percentage (such as 100%), not pixels. If the + settings are generated by JavaScript code, the height parameter of the AC_FL_RunContent() + method must be set to a percentage, too. This percentage is applied to the stageHeight + value.

+ +
flash.display.StageScaleMode
stageVideos + + A list of StageVideo objects available for playing external videos. + + A list of StageVideo objects available for playing external videos. + +

You can use only a limited number of StageVideo objects at a time. + When a SWF begins to run, the number of available StageVideo objects depends on the platform + and on available hardware. +

+ +

To use a StageVideo object, assign a member of the stageVideos Vector object to a StageVideo variable. +

+ + +

All StageVideo objects are displayed on the stage behind any display objects. + The StageVideo objects are displayed on the stage in the order they appear in + the stageVideos Vector object. For example, if the stageVideos Vector object contains + three entries:

+ + +
  1. The StageVideo object in the 0 index of the stageVideos Vector object is + displayed behind all StageVideo objects.
  2. The StageVideo object at index 1 is displayed in front + of the StageVideo object at index 0.
  3. The StageVideo object at index 2 is displayed in front + of the StageVideo object at index 1.
+ +

Use the StageVideo.depth property to change this ordering.

+ +

Note: AIR for TV devices support only one StageVideo object.

+ +
The following code illustrates how to get a StageVideo object: + + +var stageVideo:StageVideo; + +if ( stage.stageVideos.length >= 1 ) { + stageVideo = stage.stageVideos[0]; +} +
flash.media.StageVideoflash.events.StageVideoEvent
stageWidth + Specifies the current width, in pixels, of the Stage.intCalling the stageWidth property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + Specifies the current width, in pixels, of the Stage. + + +

If the value of the Stage.scaleMode property is set to StageScaleMode.NO_SCALE + when the user resizes the window, the Stage content maintains its defined size while the stageWidth + property changes to reflect the new width size of the screen area occupied by the SWF file. (In the other scale + modes, the stageWidth property always reflects the original width of the SWF file.) You can add an event + listener for the resize event and then use the stageWidth property of the Stage class to + determine the actual pixel dimension of the resized Flash runtime window. The event listener allows you to control how + the screen content adjusts when the user resizes the window.

+ +

Air for TV devices have slightly different behavior than desktop devices + when you set the stageWidth property. + If the Stage.scaleMode + property is set to StageScaleMode.NO_SCALE and you set the stageWidth + property, the stage width does not change until the next + frame of the SWF.

+ +

Note: In an HTML page hosting the SWF file, both the object and embed tags' width attributes must be set to a percentage (such as 100%), not pixels. If the + settings are generated by JavaScript code, the width parameter of the AC_FL_RunContent() + method must be set to a percentage, too. This percentage is applied to the stageWidth + value.

+ +
flash.display.StageScaleMode
supportedOrientations + The orientations supported by the current device. + The orientations supported by the current device. + +

You can use the orientation strings included in this list as parameters for + the setOrientation() method. Setting an unsupported orientation fails without error.

+ +

The possible orientations include:

+ StageOrientation constantStage orientationStageOrientation.DEFAULTSet the stage orientation to the default orientation (right-side up).StageOrientation.ROTATED_RIGHTSet the stage orientation to be rotated right.StageOrientation.ROTATED_LEFTSet the stage orientation to be rotated left.StageOrientation.UPSIDE_DOWNSet the stage orientation to be rotated upside down. + + +
StageOrientationautoOrientssetOrientationorientation
supportsOrientationChange + Whether the application supports changes in the stage orientation (and device rotation).Boolean + Whether the application supports changes in the stage orientation (and device rotation). + Currently, this property is only true in AIR applications running on mobile + devices. + + autoOrientsdeviceOrientationsupportsOrientationChangetabChildren + + Determines whether the children of the object are tab enabled.BooleanReferencing the tabChildren property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityError + + Determines whether the children of the object are tab enabled. Enables or disables tabbing for the + children of the object. The default is true. +

Note: Do not use the tabChildren property with Flex. + Instead, use the mx.core.UIComponent.hasFocusableChildren property.

+ +
textSnapshot + + Returns a TextSnapshot object for this DisplayObjectContainer instance.flash.text:TextSnapshotReferencing the textSnapshot property of a Stage object throws an + exception because the Stage class does not implement this property. To avoid this, call the + textSnapshot property of a display object container other than the Stage object. + + IllegalOperationErrorflash.errors:IllegalOperationError + + Returns a TextSnapshot object for this DisplayObjectContainer instance. + + width + + Indicates the width of the display object, in pixels.NumberReferencing the width property of a Stage object throws an exception for + any caller that is not in the same security sandbox as the Stage owner (the main SWF file). + To avoid this, the Stage owner can grant permission to the domain of the caller by calling + the Security.allowDomain() method or the Security.allowInsecureDomain() method. + For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorIt is always illegal to set the width property of a Stage object, + even if you are the Stage owner. + + IllegalOperationErrorflash.errors:IllegalOperationError + + Indicates the width of the display object, in pixels. The width is calculated based on the bounds of the content of the display object. + When you set the width property, the scaleX property is adjusted accordingly, as shown in the + following code: + + + var rect:Shape = new Shape(); + rect.graphics.beginFill(0xFF0000); + rect.graphics.drawRect(0, 0, 100, 100); + trace(rect.scaleX) // 1; + rect.width = 200; + trace(rect.scaleX) // 2; + +

Except for TextField and Video objects, a display object with no content (such as an empty sprite) has a width + of 0, even if you try to set width to a different value.

+ +
wmodeGPU + Indicates whether GPU compositing is available and in use.Boolean + Indicates whether GPU compositing is available and in use. The wmodeGPU value is true only + when all three of the following conditions exist: +

  • GPU compositing has been requested.
  • GPU compositing is available.
  • GPU compositing is in use.

+

Specifically, the wmodeGPU property indicates one of the following:

+

  1. GPU compositing has not been requested or is unavailable. In this case, the wmodeGPU property value is false.
  2. GPU compositing has been requested (if applicable and available), but the environment is operating in "fallback mode" + (not optimal rendering) due to limitations of the content. In this case, the wmodeGPU property value is true.
  3. GPU compositing has been requested (if applicable and available), and the environment is operating in the best mode. In this case, the + wmodeGPU property value is also true.

+

In other words, the wmodeGPU property identifies the capability and state of the rendering environment. For runtimes + that do not support GPU compositing, such as AIR 1.5.2, the value is always false, because (as stated above) the value is + true only when GPU compositing has been requested, is available, and is in use.

+

The wmodeGPU property is useful to determine, at runtime, whether or not GPU compositing is in use. The value of + wmodeGPU indicates if your content is going to be scaled by hardware, or not, so you can present graphics at the correct size. + You can also determine if you're rendering in a fast path or not, so that you can adjust your content complexity accordingly.

+

For Flash Player in a browser, GPU compositing can be requested by the value of gpu for the wmode HTML + parameter in the page hosting the SWF file. For other configurations, GPU compositing can be requested in the header of a SWF file + (set using SWF authoring tools).

+

However, the wmodeGPU property does not identify the current rendering performance. Even if GPU compositing is "in use" the rendering + process might not be operating in the best mode. To adjust your content for optimal rendering, use a Flash runtime debugger version, + and set the DisplayGPUBlendsetting in your mm.cfg file.

+ +

Note: This property is always false when referenced + from ActionScript that runs before the runtime performs its first rendering + pass. For example, if you examine wmodeGPU from a script in Frame 1 of + Adobe Flash Professional, and your SWF file is the first SWF file loaded in a new + instance of the runtime, then the wmodeGPU value is false. + To get an accurate value, wait until at least one rendering pass + has occurred. If you write an event listener for the + exitFrame event of any DisplayObject, the wmodeGPU value at + is the correct value.

+ +
The following example examines the wmodeGPU property after the display object mySprite + is rendered, so you can get an accurate value. + +mySprite.addEventListener(EXIT_FRAME, exithandler): + +function exithandler(exiteventobject:Event):void { + trace(stage.wmodeGPU); +} +
DisplayObject exitFrame event
NativeWindowInitOptions + The NativeWindowInitOptions class defines the initialization options + used to construct a new NativeWindow instance.Object + The NativeWindowInitOptions class defines the initialization options + used to construct a new NativeWindow instance. +

The properties defined in the + initialization options cannot be changed after a window is created.

+ +

Note: For the initial application window created automatically + by AIR, all of these properties (except type) are + set in the application descriptor. The initial window is always type NativeWindowType.NORMAL.

+ +
flash.display.NativeWindowflash.display.NativeWindowTypeflash.display.NativeWindowSystemChromeNativeWindowInitOptions + Creates a new NativeWindowInitOptions object. + Creates a new NativeWindowInitOptions object. + +

The default values of the newly created object are:

+
  • systemChrome = NativeWindowSystemChrome.STANDARD
  • type = NativeWindowType.NORMAL
  • transparent = false
  • owner = null
  • resizable = true
  • maximizable = true
  • minimizable = true
+ +
maximizable + Specifies whether the window can be maximized by the user.Booleantrue + + + Specifies whether the window can be maximized by the user. + +

+ For windows with system chrome, this setting will affect the appearance of the window + maximize button. It will also affect other parts of the system-managed + user interface, such as the window menu on Microsoft Windows. +

+ +

+ When set to false, the window cannot be maximized by the user. Calling the + NativeWindow maximize() method directly will maximize the window. +

+ +

OS behavior notes:

+
  • On operating systems, such as Mac OS X, in which maximizing + a window does not also prevent resizing, both maximizable and + resizable must be set to false to prevent + the window from being zoomed or resized.
  • Some Linux window managers allow windows to be maximized by the user even when the + maximizable property is set to false.
+ +
flash.display.NativeWindow.displayState
minimizable + Specifies whether the window can be minimized by the user.Booleantrue + + + Specifies whether the window can be minimized by the user. + +

+ For windows with system chrome, this setting will affect the appearance of the + window minimize button. It will also affect other parts of the system-managed + user interface, such as the window menu on Microsoft Windows. +

+ +

+ When set to false, the window cannot be minimized by the user. Calling the + NativeWindow minimize() method directly will minimize the window. +

+ +

Note: Some Linux window managers allow windows to be minimized by the user even when the + minimizable property is set to false.

+ +
flash.display.NativeWindow.displayState
owner + Specifies the NativeWindow object that should own any windows created with + this NativeWindowInitOptions.flash.display:NativeWindow<code>null</code> + + + Specifies the NativeWindow object that should own any windows created with + this NativeWindowInitOptions. + +

When a window has an owner, that window is always displayed in front of its owner, + is minimized and hidden along with its owner, and closes when its owner closes.

+ +
flash.display.NativeWindow.ownerflash.display.NativeWindow.listOwnedWindows()
resizable + Specifies whether the window can be resized by the user.Booleantrue + + + Specifies whether the window can be resized by the user. + +

+ When set to false, the window cannot be resized by the user using system chrome. + Calling the NativeWindow startResize() method in response to a mouse event will + allow the user to resize the window. Setting the window bounds directly will also change the window size. +

+ +

OS behavior notes:

+
  • On operating systems, such as Mac OS X, in which + maximizing windows is a resizing operation, both maximizable and + resizable must be set to false to prevent + the window from being zoomed or resized.
  • Some Linux window managers allow windows to be resized by the user even when the + resizable property is set to false.
+ +
flash.display.NativeWindow.bounds
systemChrome + Specifies whether system chrome is provided for the window.StringNativeWindowSystemChrome.STANDARD + + + Specifies whether system chrome is provided for the window. + +

Chrome refers to the window controls that allow a user to control the desktop + properties of a window. System chrome uses the standard controls for the desktop + environment in which the AIR application is run and conforms to the standard + look-and-feel of the native operating system.

+

+ To use chrome provided by a framework (such as Flex), or to provide your own window + chrome, set systemChrome to NativeWindowSystemChrome.NONE. +

+

Constants for the valid values of this property are defined in the + NativeWindowSystemChrome class: +

+
  • NativeWindowSystemChrome.NONE
  • NativeWindowSystemChrome.STANDARD
+ +

If not specified, the default value for systemChrome is + NativeWindowSystemChrome.STANDARD. +

+ +

Setting the transparent property to true for a window + with system chrome is not supported.

+ +
flash.display.NativeWindowSystemChrome
transparent + Specifies whether the window supports transparency and alpha blending against the desktop.Booleanfalse + + + Specifies whether the window supports transparency and alpha blending against the desktop. + +

+ If true, the window display is composited against the desktop. Areas of the window + not covered by a display object, or covered by display objects with an alpha setting near zero, + are effectively invisible and will not intercept mouse events (which will be received by the + desktop object below the window). The alpha value at which an object will no longer + intercepting mouse events varies between about .06 and .01, depending on the operating system. +

+ +

Setting the transparent property to true for a window + with system chrome is not supported.

+ +

Note: Not all Linux window managers support transparency. On such systems, transparent + areas of a window are composited against black.

+ +
type + Specifies the type of the window to be created.StringNativeWindowType.NORMAL + + + Specifies the type of the window to be created. + +

Constants for the valid values of this property are defined in the + NativeWindowType class: +

+ +
  • NativeWindowType.NORMAL — A typical window. + Normal windows use full-size chrome and appear on the Windows or Linux + task bar.
  • NativeWindowType.UTILITY — A tool palette. Utility + windows use a slimmer version of the system chrome and do not appear + on the Windows task bar.
  • NativeWindowType.LIGHTWEIGHT — lightweight windows cannot have + system chrome and do not appear on the Windows or Linux task bar. In addition, lightweight + windows do not have the System (Alt-Space) menu on Windows. Lightweight windows + are suitable for notification bubbles and controls such as combo-boxes + that open a short-lived display area. When the lightweight type is + used, systemChrome must be set to NativeWindowSystemChrome.NONE.
+ +

+ If not specified, the default value for type is + NativeWindowType.NORMAL. +

+ +
flash.display.NativeWindowType
ShaderParameter + A ShaderParameter instance represents a single input parameter of + a shader kernel.Object + A ShaderParameter instance represents a single input parameter of + a shader kernel. A kernel can be defined to accept zero, one, or more + parameters that are used in the kernel execution. A ShaderParameter + provides information about the parameter, such as the type of data + it expects. It also provides a mechanism for setting the parameter + value that is used when the shader executes. To specify a value or + values for the shader parameter, + create an Array containing the value or values and assign it to the + value property. + +

A ShaderParameter instance representing a parameter + for a Shader instance is accessed as a property of the Shader instance's + data property. The ShaderParameter property has the same name + as the parameter's name in the shader code. + For example, if a shader defines a parameter named radius, + the ShaderParameter instance representing the radius parameter + is available as the radius property, as shown here:

+ + var radiusParam:ShaderParameter = myShader.data.radius; + +

In addition to the defined properties of the ShaderParameter class, + each ShaderParameter instance has additional properties + corresponding to any metadata defined for the parameter. These properties + are added to the ShaderParameter object when it is created. The properties' + names match the metadata names specified in the shader's source code. + The data type of each property varies according to the data type of the + corresponding metadata. A text metadata value such as "description" is a String + instance. A metadata property with a non-string value (such as minValue + or defaultValue) is represented as an Array instance. The number of elements and + element data types correspond to the metadata values.

+ +

For example, suppose a shader includes the following two parameter declarations:

+ + + parameter float2 size + < + description: "The size of the image to which the kernel is applied"; + minValue: float2(0.0, 0.0); + maxValue: float2(100.0, 100.0); + defaultValue: float2(50.0, 50.0); + >; + + parameter float radius + < + description: "The radius of the effect"; + minValue: 0.0; + maxValue: 50.0; + defaultValue: 25.0; + >; + + +

The ShaderParameter instance + corresponding to the size parameter has the following metadata + properties in addition to its built-in properties:

+ + Property nameData typeValuenameString"size"descriptionString"The size of the image to which the kernel is applied"minValueArray[0, 0]maxValueArray[100, 100]defaultValueArray[50, 50] + +

The ShaderParameter corresponding to the radius parameter + has the following additional properties:

+ + Property nameData typeValuenameString"radius"descriptionString"The radius of the effect"minValueArray[0]maxValueArray[50]defaultValueArray[25] + +

Generally, developer code does not create a ShaderParameter instance + directly. A ShaderParameter instance is created for each of a shader's + parameters when the Shader instance is created.

+ +
flash.display.ShaderDataflash.display.Shader.dataShaderParameter + Creates a ShaderParameter instance. + Creates a ShaderParameter instance. Developer code does + not call the ShaderParameter constructor + directly. A ShaderParameter instance is created for each of a + shader's parameters when the Shader instance is created. + + index + The zero-based index of the parameter.int + The zero-based index of the parameter. + + type + The data type of the parameter as defined in the shader.String + The data type of the parameter as defined in the shader. The set of + possible values for the type property is defined by the + constants in the ShaderParameterType class. + + flash.display.ShaderParameterTypevalue + The value or values that are passed in as the parameter value to the shader.Array + The value or values that are passed in as the parameter value to the shader. + The value property is an indexed Array. The number and type of + the elements of the Array correspond to the data type of the parameter, which + can be determined using the type property. + +

The following table indicates the parameter type and corresponding + number and data type of the value Array's elements:

+ + Parameter type# ElementsElement data typefloat (ShaderParameterType.FLOAT)1Numberfloat2 (ShaderParameterType.FLOAT2)2Numberfloat3 (ShaderParameterType.FLOAT3)3Numberfloat4 (ShaderParameterType.FLOAT4)4Numberint (ShaderParameterType.INT)1int or uintint2 (ShaderParameterType.INT2)2int or uintint3 (ShaderParameterType.INT3)3int or uintint4 (ShaderParameterType.INT4)4int or uintbool (ShaderParameterType.BOOL)1Booleanbool2 (ShaderParameterType.BOOL2)2Booleanbool3 (ShaderParameterType.BOOL3)3Booleanbool4 (ShaderParameterType.BOOL4)4Booleanfloat2x2 (ShaderParameterType.MATRIX2X2)4Numberfloat3x3 (ShaderParameterType.MATRIX3X3)9Numberfloat4x4 (ShaderParameterType.MATRIX4X4)16Number + +

For the matrix parameter types, the array elements fill the rows of + the matrix, then the columns. For example, suppose the following line + of ActionScript is used to fill a float2x2 + parameter named myMatrix:

+ + myShader.data.myMatrix.value = [.1, .2, .3, .4]; + +

Within the shader, the matrix elements have the following values:

+ +
  • myMatrix[0][0]: .1
  • myMatrix[0][1]: .2
  • myMatrix[1][0]: .3
  • myMatrix[1][1]: .4
+ +
GradientType +The GradientType class provides values for the type parameter in the +beginGradientFill() and lineGradientStyle() methods of the flash.display.Graphics class.Object +The GradientType class provides values for the type parameter in the +beginGradientFill() and lineGradientStyle() methods of the flash.display.Graphics class. + +LINEAR + Value used to specify a linear gradient fill.linearString + Value used to specify a linear gradient fill. + + RADIAL + Value used to specify a radial gradient fill.radialString + Value used to specify a radial gradient fill. + + InterpolationMethod +The InterpolationMethod class provides values for the interpolationMethod +parameter in the Graphics.beginGradientFill() and +Graphics.lineGradientStyle() methods.Object +The InterpolationMethod class provides values for the interpolationMethod +parameter in the Graphics.beginGradientFill() and +Graphics.lineGradientStyle() methods. This parameter determines +the RGB space to use when rendering the gradient. + + + flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()LINEAR_RGB + Specifies that the linear RGB interpolation method should be used.linearRGBString + Specifies that the linear RGB interpolation method should be used. This means that + an RGB color space based on a linear RGB color model is used. + + + RGBRGB + Specifies that the RGB interpolation method should be used.rgbString + Specifies that the RGB interpolation method should be used. This means that the gradient is rendered with + exponential sRGB (standard RGB) space. + The sRGB space is a W3C-endorsed standard that defines a non-linear conversion between + red, green, and blue component values and the actual intensity of the visible component color. + +

For example, consider a simple linear gradient between two colors (with the spreadMethod + parameter set to SpreadMethod.REFLECT). The different interpolation methods affect + the appearance as follows:

+ + InterpolationMethod.LINEAR_RGBInterpolationMethod.RGB + +
LINEAR_RGB
IGraphicsPath + This interface is used to define objects that can be used as path parameters in the flash.display.Graphics + methods and drawing classes. + This interface is used to define objects that can be used as path parameters in the flash.display.Graphics + methods and drawing classes. Use the implementor classes of this interface to + create and manage path property data, and to reuse the same data for different instances. + flash.display.Graphics.drawGraphicsData()flash.display.Graphics.drawPath()IGraphicsFill + This interface is used to define objects that can be used as fill parameters in the flash.display.Graphics + methods and drawing classes. + This interface is used to define objects that can be used as fill parameters in the flash.display.Graphics + methods and drawing classes. Use the implementor classes of this interface to + create and manage fill property data, and to reuse the same data for different instances. + flash.display.Graphics.drawGraphicsData()flash.display.GraphicsStroke.fillLoaderInfo + The LoaderInfo class provides information about a loaded SWF file or a loaded image file + (JPEG, GIF, or PNG).flash.events:EventDispatcher + The LoaderInfo class provides information about a loaded SWF file or a loaded image file + (JPEG, GIF, or PNG). LoaderInfo objects are available for any display object. + The information provided includes load progress, the URLs of the loader and + loaded content, the number of bytes total for the media, and the nominal height and width of the + media. + +

You can access LoaderInfo objects in two ways:

+ +
  • The contentLoaderInfo property of a flash.display.Loader object— + The contentLoaderInfo property is always available for any Loader object. + For a Loader object that has not called the load() or loadBytes() + method, or that has not sufficiently loaded, attempting to access many of the properties of the + contentLoaderInfo property throws an error.
  • The loaderInfo property of a display object.
+ +

The contentLoaderInfo property of a Loader object provides information about + the content that the Loader object is loading, whereas the loaderInfo property of + a DisplayObject provides information about the root SWF file for that display object.

+ +

When you use a Loader object to load a display object (such as a SWF file or a bitmap), the + loaderInfo property of the display object is the same as the contentLoaderInfo + property of the Loader object (DisplayObject.loaderInfo = Loader.contentLoaderInfo). + Because the instance of the main class of the SWF file has + no Loader object, the loaderInfo property is the only way to + access the LoaderInfo for the instance of the main class of the SWF file.

+ +

The following diagram shows the different uses of the LoaderInfo object—for the instance of the main class of + the SWF file, for the contentLoaderInfo property of a Loader object, and for the loaderInfo + property of a loaded object:

+ +

+ +

+ +

When a loading operation is not complete, some properties of the contentLoaderInfo + property of a Loader object are not available. You can obtain some properties, such as + bytesLoaded, bytesTotal, url, loaderURL, + and applicationDomain. When the loaderInfo object dispatches the + init event, you can access all properties of the loaderInfo object and + the loaded image or SWF file.

+ +

Note: All properties of LoaderInfo objects are read-only.

+ +

The EventDispatcher.dispatchEvent() method + + is not applicable to LoaderInfo objects. If you call dispatchEvent() + on a LoaderInfo object, an IllegalOperationError exception is thrown.

+ + + +
The following example uses the LoaderInfoExample class to display an image on + the stage. This is accomplished by performing the following steps: +
  1. A property url is created, which is the location and name of the image.
  2. The class constructor creates a Loader object named loader.
  3. The loader object instantiates an event listener to ensure that the image loads properly.
  4. The constructor creates a new instance of a URLRequest object, request, + with url passed so that the file name and location are known.
  5. The request object is then passed to the load() method of the + loader object, which loads the image onto the display list.
+

Important: This example requires that you add a file named Image.gif in the same directory + as the compiled SWF file. Use an image that has an area that fits within the dimensions of the main SWF file.

+ +package { + import flash.display.Loader; + import flash.display.LoaderInfo; + import flash.display.Sprite; + import flash.events.*; + import flash.net.URLRequest; + + public class LoaderInfoExample extends Sprite { + private var url:String = "Image.gif"; + + public function LoaderInfoExample() { + var loader:Loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + var request:URLRequest = new URLRequest(url); + loader.load(request); + addChild(loader); + } + + private function initHandler(event:Event):void { + var loader:Loader = Loader(event.target.loader); + var info:LoaderInfo = LoaderInfo(loader.contentLoaderInfo); + trace("initHandler: loaderURL=" + info.loaderURL + " url=" + info.url); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
flash.display.Loaderflash.display.Loader.contentflash.display.DisplayObjectflash.display.DisplayObject.loaderInfohttpStatus + Dispatched when a network request is made over HTTP and an HTTP status code can be detected.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent + Dispatched when a network request is made over HTTP and an HTTP status code can be detected. + Loader.load()unload + Dispatched by a LoaderInfo object whenever a loaded object is removed by using the unload() + method of the Loader object, or when a second load is performed by the same Loader object and the + original content is removed prior to the load beginning.flash.events.Event.UNLOADflash.events.Event + Dispatched by a LoaderInfo object whenever a loaded object is removed by using the unload() + method of the Loader object, or when a second load is performed by the same Loader object and the + original content is removed prior to the load beginning. + Loader.load()Loader.unload()progress + Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched when data is received as the download operation progresses. + Loader.load()open + Dispatched when a load operation starts.flash.events.Event.OPENflash.events.Event + Dispatched when a load operation starts. + Loader.load()ioError + Dispatched when an input or output error occurs that causes a load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input or output error occurs that causes a load operation to fail. + Loader.load()init + Dispatched when the properties and methods of a loaded SWF file are + accessible and ready for use.flash.events.Event.INITflash.events.Event + Dispatched when the properties and methods of a loaded SWF file are + accessible and ready for use. The content, however, can still be downloading. A LoaderInfo object + dispatches the init event when the following conditions exist: +
  • All properties and methods associated with the loaded object and those associated + with the LoaderInfo object are accessible.
  • The constructors for all child objects have completed.
  • All ActionScript code in the first frame of the loaded SWF's main timeline has been executed.
+ +

For example, an Event.INIT is dispatched when the first frame of a movie or animation is loaded. + The movie is then accessible and can be added to the display list. The complete movie, however, can + take longer to download. The Event.COMPLETE is only dispatched once the full movie is loaded.

+ +

The init event always precedes the complete event.

+ +
Loader.load()
complete + Dispatched when data has loaded successfully.flash.events.Event.COMPLETEflash.events.Event + Dispatched when data has loaded successfully. In other words, it is dispatched when all the content + has been downloaded and the loading has finished. The complete event is always dispatched + after the init event. The init event is dispatched when the object + is ready to access, though the content may still be downloading. + + Loader.load()getLoaderInfoByDefinition + Returns the LoaderInfo object associated with a SWF file defined as an object.The caller is not running in the local trusted sandbox. + + SecurityErrorSecurityErrorThe associated LoaderInfo object. Returns null when called + in non-debugger builds (or when debugging is not enabled) or if the referenced object + does not have an associated LoaderInfo object (such as some objects used by the AIR runtime). + + flash.display:LoaderInfoobjectObjectThe object for which you want to get an associated LoaderInfo object. + + Returns the LoaderInfo object associated with a SWF file defined as an object. + actionScriptVersion + The ActionScript version of the loaded SWF file.uintIf the file is not downloaded sufficiently to retrieve the requested information. + + ErrorErrorIf the file is not a SWF file. + + ErrorError + The ActionScript version of the loaded SWF file. + + The language version is specified by using the enumerations in the + ActionScriptVersion class, such as ActionScriptVersion.ACTIONSCRIPT2 + and ActionScriptVersion.ACTIONSCRIPT3. + +

Note: This property always has a value of either ActionScriptVersion.ACTIONSCRIPT2 or + ActionScriptVersion.ACTIONSCRIPT3. ActionScript 1.0 and 2.0 are + both reported as ActionScriptVersion.ACTIONSCRIPT2 (version 2.0). This property + only distinguishes ActionScript 1.0 and 2.0 from ActionScript 3.0.

+ +
flash.display.ActionScriptVersion
applicationDomain + When an external SWF file is loaded, all ActionScript 3.0 definitions contained in the loaded + class are stored in the applicationDomain property.flash.system:ApplicationDomainThis security sandbox of the caller is not allowed to access this ApplicationDomain. + + SecurityErrorSecurityError + When an external SWF file is loaded, all ActionScript 3.0 definitions contained in the loaded + class are stored in the applicationDomain property. + +

All code in a SWF file is defined to exist in an application domain. The current application + domain is where your main application runs. The system domain contains all application domains, + including the current domain and all classes used by Flash Player or Adobe AIR.

+ +

All application domains, except the system domain, have an associated parent domain. + The parent domain of your main application's applicationDomain is the system domain. + Loaded classes are defined only when their parent doesn't already define them. + You cannot override a loaded class definition with a newer definition.

+ +

For usage examples of application domains, see the "Client System Environment" chapter + in the ActionScript 3.0 Developer's Guide.

+ +
flash.system.ApplicationDomain
bytesLoaded + The number of bytes that are loaded for the media.uint + The number of bytes that are loaded for the media. When this number equals + the value of bytesTotal, all of the bytes are loaded. + + bytesTotal + The number of compressed bytes in the entire media file.uint + The number of compressed bytes in the entire media file. + +

Before the first progress event is dispatched by + this LoaderInfo object's corresponding Loader object, bytesTotal is 0. + After the first progress event from the Loader object, bytesTotal + reflects the actual number of bytes to be downloaded.

+ +
flash.events.ProgressEventflash.display.Loader
bytes + The bytes associated with a LoaderInfo object.flash.utils:ByteArrayIf the object accessing this API is prevented from + accessing the loaded object due to security restrictions. This situation can occur, + for instance, when a Loader object attempts to access the contentLoaderInfo.content + property and it is not granted security permission to access the loaded content. + +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
SecurityErrorSecurityError
+ The bytes associated with a LoaderInfo object. + +
childAllowsParent + Expresses the trust relationship from content (child) to the Loader (parent).Boolean Thrown if the file is not downloaded sufficiently + to retrieve the requested information. + ErrorError + Expresses the trust relationship from content (child) to the Loader (parent). + If the child has allowed the parent access, true; otherwise, + false. This property is set to true if the child object + has called the allowDomain() method to grant permission to the parent domain + or if a URL policy is loaded at the child domain that grants permission + to the parent domain. If child and parent are in + the same domain, this property is set to true. + +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
childSandboxBridge + A object that can be set by the loaded content's code to expose properties and methods that can be accessed + by code in the Loader object's sandbox.ObjectOnly content in the loaded content's sandbox can set this property. + + SecurityErrorSecurityError + A object that can be set by the loaded content's code to expose properties and methods that can be accessed + by code in the Loader object's sandbox. This sandbox bridge lets content from a non-application domain have + controlled access to scripts in the AIR application sandbox, and vice versa. The sandbox bridge serves as a gateway between + the sandboxes, providing explicit interaction between application and non-application security sandboxes. + + parentSandboxBridgecontentType + The MIME type of the loaded file.String + The MIME type of the loaded file. The value is null if not enough of the file has loaded + in order to determine the type. The following list gives the possible values: + +
  • "application/x-shockwave-flash"
  • "image/jpeg"
  • "image/gif"
  • "image/png"
+
content + The loaded object associated with this LoaderInfo object.flash.display:DisplayObjectIf the object accessing this API is prevented from + accessing the loaded object due to security restrictions. This situation can occur, + for instance, when a Loader object attempts to access the contentLoaderInfo.content + property and it is not granted security permission to access the loaded content. + +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
SecurityErrorSecurityError
+ The loaded object associated with this LoaderInfo object. + +
frameRate + The nominal frame rate, in frames per second, of the loaded SWF file.NumberIf the file is not downloaded sufficiently to retrieve the requested information. + + ErrorErrorIf the file is not a SWF file. + ErrorError + The nominal frame rate, in frames per second, of the loaded SWF file. This + number is often an integer, but need not be. + +

This value may differ from the actual frame rate in use. + Flash Player or Adobe AIR only uses a single frame rate for all loaded SWF files at + any one time, and this frame rate is determined by the nominal + frame rate of the main SWF file. Also, the main frame rate may not be able to be achieved, depending on hardware, sound synchronization, + and other factors.

+ +
height + The nominal height of the loaded file.intIf the file is not downloaded sufficiently to retrieve the requested information. + ErrorError + The nominal height of the loaded file. This value might differ from the actual + height at which the content is displayed, since the loaded content or its parent + display objects might be scaled. + + isURLInaccessible + Indicates if the LoaderInfo.url property has been + truncated.Boolean + Indicates if the LoaderInfo.url property has been + truncated. When the isURLInaccessible value is true the + LoaderInfo.url value is only the domain of the final URL from which the content loaded. + For example, the property is truncated if the content is loaded from http://www.adobe.com/assets/hello.swf, + and the LoaderInfo.url property has the value http://www.adobe.com. The isURLInaccessible + value is true only when all of the following are also true: + +
  • An HTTP redirect occurred while loading the content.
  • The SWF file calling Loader.load() is from a different domain than + the content's final URL.
  • The SWF file calling Loader.load() does not have permission to access + the content. Permission is granted to access the content the same way permission is granted for + BitmapData.draw(): + call Security.allowDomain() to access a SWF file + (or for non-SWF file content, establish a policy file and use the LoaderContext.checkPolicyFile + property).
+ +

Note: The isURLInaccessible property was added for Flash Player 10.1 and AIR 2.0. + However, this property is made available to SWF files of all versions when the + Flash runtime supports it. So, using some authoring tools in "strict mode" causes a compilation error. To work around the error + use the indirect syntax myLoaderInfo["isURLInaccessible"], or disable strict mode. If you are using Flash Professional CS5 + or Flex SDK 4.1, you can use and compile this API for runtimes released before Flash Player 10.1 and AIR 2.

+ +

For application content in AIR, the value of this property is always false.

+ +
urlBitmapData.draw()flash.system.Security.allowDomain()flash.system.LoaderContext.checkPolicyFile
loaderURL + The URL of the SWF file that initiated the loading of the media + described by this LoaderInfo object.String + The URL of the SWF file that initiated the loading of the media + described by this LoaderInfo object. For the instance of the main class of the SWF file, this + URL is the same as the SWF file's own URL. + + loader + The Loader object associated with this LoaderInfo object.flash.display:LoaderIf the object accessing this API is prevented from + accessing the Loader object because of security restrictions. This can occur, + for instance, when a loaded SWF file attempts to access its loaderInfo.loader + property and it is not granted security permission to access the loading SWF file. + +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
SecurityErrorSecurityError
+ The Loader object associated with this LoaderInfo object. If this LoaderInfo object + is the loaderInfo property of the instance of the main class of the SWF file, no + Loader object is associated. + +
parameters + An object that contains name-value pairs that represent the parameters provided + to the loaded SWF file.Object + An object that contains name-value pairs that represent the parameters provided + to the loaded SWF file. + +

You can use a for-in loop to extract all the names and values + from the parameters object.

+ +

The two sources of parameters are: the query string in the + URL of the main SWF file, and the value of the FlashVars HTML parameter (this affects + only the main SWF file).

+ +

The parameters property replaces the ActionScript 1.0 and 2.0 technique of + providing SWF file parameters as properties of the main timeline.

+ +

The value of the parameters property is null for Loader objects + that contain SWF files that use ActionScript 1.0 or 2.0. It is only + non-null for Loader objects that contain SWF files that use ActionScript 3.0.

+ +
parentAllowsChild + Expresses the trust relationship from Loader (parent) to the content (child).Boolean Thrown if the file is not downloaded sufficiently + to retrieve the requested information. + ErrorError + Expresses the trust relationship from Loader (parent) to the content (child). + If the parent has allowed the child access, true; otherwise, + false. This property is set to true if the parent object + called the allowDomain() method to grant permission to the child domain + or if a URL policy file is loaded at the parent domain granting permission + to the child domain. If child and parent are in + the same domain, this property is set to true. + +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
parentSandboxBridge + A object that can be set by code in the Loader object's sandbox to expose properties and methods that can be accessed + by the loaded content's code.ObjectOnly content in the Loader object's sandbox can set this property. + + SecurityErrorSecurityError + A object that can be set by code in the Loader object's sandbox to expose properties and methods that can be accessed + by the loaded content's code. This sandbox bridge lets content from a non-application domain have controlled + access to scripts in the AIR application sandbox, and vice versa. The sandbox bridge serves as a gateway between + the sandboxes, providing explicit interaction between application and non-application security sandboxes. + + childSandboxBridgesameDomain + Expresses the domain relationship between the loader and the content: true if they have + the same origin domain; false otherwise.Boolean Thrown if the file is not downloaded sufficiently + to retrieve the requested information. + ErrorError + Expresses the domain relationship between the loader and the content: true if they have + the same origin domain; false otherwise. + + sharedEvents + An EventDispatcher instance that can be used to exchange events across security boundaries.flash.events:EventDispatcher + An EventDispatcher instance that can be used to exchange events across security boundaries. + Even when the Loader object and the loaded content originate from security domains that do not trust + one another, both can access sharedEvents and send and receive events via this object. + + swfVersion + The file format version of the loaded SWF file.uintIf the file is not downloaded sufficiently to retrieve the requested information. + + ErrorErrorIf the file is not a SWF file. + + ErrorError + The file format version of the loaded SWF file. + + The file format is specified using the enumerations in the + SWFVersion class, such as SWFVersion.FLASH7 and SWFVersion.FLASH9. + + flash.display.SWFVersionuncaughtErrorEvents + An object that dispatches an uncaughtError event when an unhandled error + occurs in code in this LoaderInfo object's SWF file.flash.events:UncaughtErrorEvents + An object that dispatches an uncaughtError event when an unhandled error + occurs in code in this LoaderInfo object's SWF file. An uncaught error happens when + an error is thrown outside of any try..catch blocks or when an ErrorEvent + object is dispatched with no registered listeners. + +

This property is created when the SWF associated with this LoaderInfo has finished + loading. Until then the uncaughtErrorEvents property is null. + In an ActionScript-only project, you can access this property during or after the execution + of the constructor function of the main class of the SWF file. For a Flex project, + the uncaughtErrorEvents property is available after the + applicationComplete event is dispatched.

+ +
The following example demonstrates the use of an uncaught error event + handler to detect uncaught errors in an ActionScript project. The example defines + an uncaughtError event handler to detect uncaught errors. It also + provides a button that, when clicked, throws an error that is caught by the + uncaught error handler. + +

In the constructor, the code registers a listener for the uncaughtError + event dispatched by the LoaderInfo object's uncaughtErrorEvents property.

+ +

In the uncaughtErrorHandler() method, the code checks the data type of + the error property and responds accordingly.

+ +package +{ + import flash.display.Sprite; + import flash.events.ErrorEvent; + import flash.events.MouseEvent; + import flash.events.UncaughtErrorEvent; + + public class UncaughtErrorEventExample extends Sprite + { + public function UncaughtErrorEventExample() + { + loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + + drawUI(); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + + private function drawUI():void + { + var btn:Sprite = new Sprite(); + btn.graphics.clear(); + btn.graphics.beginFill(0xFFCC00); + btn.graphics.drawRect(0, 0, 100, 50); + btn.graphics.endFill(); + addChild(btn); + btn.addEventListener(MouseEvent.CLICK, clickHandler); + } + + private function clickHandler(event:MouseEvent):void + { + throw new Error("Gak!"); + } + } +} + + +
The following example is the Flex equivalent of the previous example, + using an MXML document instead of an ActionScript class as the root content. + +<?xml version="1.0" encoding="utf-8"?> +<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/halo" + applicationComplete="applicationCompleteHandler();"> + + <fx:Script> + <![CDATA[ + import flash.events.ErrorEvent; + import flash.events.MouseEvent; + import flash.events.UncaughtErrorEvent; + + private function applicationCompleteHandler():void + { + loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + + private function clickHandler(event:MouseEvent):void + { + throw new Error("Gak!"); + } + ]]> + </fx:Script> + + <s:Button label="Cause Error" click="clickHandler(event);"/> +</s:WindowedApplication> +
UncaughtErrorEventLoader.uncaughtErrorEvents
url + The URL of the media being loaded.String + The URL of the media being loaded. + +

Before the first progress event is dispatched by this LoaderInfo + object's corresponding Loader object, the value of the url property + might reflect only the initial URL specified in the call to the load() + method of the Loader object. After the first progress event, the + url property reflects the media's final URL, after any redirects and relative + URLs are resolved.

+

In some cases, the value of the url property is truncated; see the + isURLInaccessible property for details.

+ +
isURLInaccessibleflash.display.Loader.load()
width + The nominal width of the loaded content.intIf the file is not downloaded sufficiently to retrieve the requested information. + ErrorError + The nominal width of the loaded content. This value might differ from the actual + width at which the content is displayed, since the loaded content or its parent + display objects might be scaled. + +
StageQuality +The StageQuality class provides values for the Stage.quality property.Object +The StageQuality class provides values for the Stage.quality property. + +flash.display.Stage.qualityBEST +Specifies very high rendering quality: graphics are anti-aliased using a 4 x 4 pixel +grid and bitmaps are always smoothed.bestString +Specifies very high rendering quality: graphics are anti-aliased using a 4 x 4 pixel +grid and bitmaps are always smoothed. + +HIGH +Specifies high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid, +and bitmaps are smoothed if the movie is static.highString +Specifies high rendering quality: graphics are anti-aliased using a 4 x 4 pixel grid, +and bitmaps are smoothed if the movie is static. + +LOW +Specifies low rendering quality: graphics are not anti-aliased, and bitmaps are not smoothed.lowString +Specifies low rendering quality: graphics are not anti-aliased, and bitmaps are not smoothed. + +MEDIUM +Specifies medium rendering quality: graphics are anti-aliased using a 2 x 2 pixel grid, +but bitmaps are not smoothed.mediumString +Specifies medium rendering quality: graphics are anti-aliased using a 2 x 2 pixel grid, +but bitmaps are not smoothed. This setting is suitable for movies that do not contain text. + +BitmapData + The BitmapData class lets you work with the data (pixels) of a Bitmap object + bitmap image.Lets you work with the bitmap data of a Bitmap object. + + flash.display:IBitmapDrawableObject + The BitmapData class lets you work with the data (pixels) of a Bitmap object + . You can use the methods of the BitmapData class + to create arbitrarily sized transparent or opaque bitmap images and manipulate them in various + ways at runtime. You can also access the BitmapData for a bitmap image + that you load with the flash.display.Loader class. + +

This class lets you separate bitmap rendering operations from the + internal display updating routines of Flash Player. By manipulating + a BitmapData object directly, you can create complex images without incurring the + per-frame overhead of constantly redrawing the content from vector data.

+ +

The methods of the BitmapData class support + effects that are not available through the filters available to non-bitmap display objects.

+ +

A BitmapData object contains an array of pixel data. This data can represent either + a fully opaque bitmap or a transparent bitmap that contains alpha channel data. + Either type of BitmapData object is stored as a buffer of 32-bit integers. + Each 32-bit integer determines the properties of a single pixel in the bitmap.

+ +

Each 32-bit integer is a combination of four 8-bit channel values (from 0 to 255) that + describe the alpha transparency and the red, green, and blue (ARGB) values of the pixel. + (For ARGB values, the most significant byte represents the alpha channel value, followed by red, + green, and blue.)

+ +

The four channels (alpha, red, green, and blue) are represented as numbers + when you use them with the BitmapData.copyChannel() method or the + DisplacementMapFilter.componentX + and DisplacementMapFilter.componentY properties, and these numbers + are represented by the following constants in the BitmapDataChannel class:

+ +
  • BitmapDataChannel.ALPHA
  • BitmapDataChannel.RED
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.BLUE
+ +

You can attach BitmapData objects to a Bitmap object by using the + bitmapData property of the Bitmap object.

+ +

You can use a BitmapData object to fill a Graphics object by using the + Graphics.beginBitmapFill() method.

+ +

In the AIR runtime, the DockIcon, Icon, InteractiveIcon, and SystemTrayIcon classes each include + a bitmaps property that is an array of BitmapData objects that define the bitmap images + for an icon.

+ +

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is + 2,880 pixels in height and 2,880 in width.

+ +

Calls to any method or property of a BitmapData object throw an ArgumentError error if + the BitmapData object is invalid (for example, if it has height == 0 and + width == 0) or it has been disposed of via dispose().

+ +
The following example uses the class BitmapDataExample to load the + image Image.gif into a DisplayObject in the default location (0, 0). A copy + of Image.gif is then placed to the right of the original, which has new colors applied to pixels + that pass a test using the threshold() method. + The task is accomplished using the following steps: +
  1. A url property is created, which is the location and name of the image file
  2. The class constructor creates a Loader object, which then instantiates an event listener, + which is dispatched when the completeHandler() method completes the image manipulation.
  3. The request URLRequest object is then passed to loader.load(), which loads the image + into memory by using a display object.
  4. The image is then placed on the display list, which displays the image on screen at + coordinates x = 0, y = 0.
  5. The completeHandler() method then does the following: +
    • Creates a second Loader, along with a Bitmap object, which is initialized with the + Loader object.
    • Creates a second Bitmap object, duplicate, which in turn calls the + duplicateImage() method, which creates a duplicate of the original image.
    • Creates a BitmapData object that is assigned to the duplicate object's + BitmapData object.
    • Creates a new Rectangle object initialized with the same coordinates, width, and height + as the original image.
    • Creates a new Point object, which defaults to x = 0, y = 0.
    • Creates the following variables: +
      • operation — Applies the new color when the threshold + value is greater than or equal to the original.
      • threshold — The value against which each pixel is compared (in this example, + light gray with an alpha of 0xCC).
      • color — The color that the pixels are set to that pass the threshold + test, which is solid yellow in this case.
      • mask — The exact opposite of color (transparent blue).
      • copySource — Set to false, indicating the pixel values are + not copied if the threshold value does not pass. This value has no meaning because + the image is duplicated and only pixels that pass the threshold test are changed.
    • Calls the threshold() method using the preceding variables. The resulting threshold + equation is as follows: if (current pixel Value & 0x000000FF) >= + (0xCCCCCCCC & 0x000000FF) then set pixel to 0xFFFFFF00.
+

Notes: +

  • You will need to compile the SWF file with Local Playback Security set to Access Local Files Only. +
  • This example requires that a file named Image.gif be placed in the same directory as your SWF file. +
  • It is recommended that you use an image of up to approximately 80 pixels in width.
+

+ + +package { + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.*; + import flash.geom.Point; + import flash.geom.Rectangle; + import flash.net.URLRequest; + + public class BitmapDataExample extends Sprite { + private var url:String = "Image.gif"; + private var size:uint = 80; + + public function BitmapDataExample() { + configureAssets(); + } + + private function configureAssets():void { + var loader:Loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + + var request:URLRequest = new URLRequest(url); + loader.x = size * numChildren; + loader.load(request); + addChild(loader); + } + + private function duplicateImage(original:Bitmap):Bitmap { + var image:Bitmap = new Bitmap(original.bitmapData.clone()); + image.x = size * numChildren; + addChild(image); + return image; + } + + private function completeHandler(event:Event):void { + var loader:Loader = Loader(event.target.loader); + var image:Bitmap = Bitmap(loader.content); + + var duplicate:Bitmap = duplicateImage(image); + var bitmapData:BitmapData = duplicate.bitmapData; + var sourceRect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height); + var destPoint:Point = new Point(); + var operation:String = ">="; + var threshold:uint = 0xCCCCCCCC; + var color:uint = 0xFFFFFF00; + var mask:uint = 0x000000FF; + var copySource:Boolean = true; + + bitmapData.threshold(bitmapData, + sourceRect, + destPoint, + operation, + threshold, + color, + mask, + copySource); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load image: " + url); + } + } +} +
flash.display.Bitmap.bitmapDataflash.desktop.DockIcon.bitmapsflash.display.Graphics.beginBitmapFill()flash.desktop.Icon.bitmapsflash.desktop.InteractiveIcon.bitmapsflash.display.Loaderflash.desktop.SystemTrayIcon.bitmapsBitmapData + Creates a BitmapData object with a specified width and height.width and/or height exceed the maximum dimensions. + + ArgumentErrorArgumentErrorwidthintThe width of the bitmap image in pixels. + + heightintThe height of the bitmap image in pixels. + + transparentBooleantrueSpecifies whether the bitmap image supports per-pixel transparency. + The default value is true (transparent). To create a fully transparent bitmap, set the value + of the transparent parameter to true and the value of the fillColor + parameter to 0x00000000 (or to 0). Setting the transparent property to false + can result in minor improvements in rendering performance. + + fillColoruint0xFFFFFFFFA 32-bit ARGB color value that you use to fill the bitmap image area. + The default value is 0xFFFFFFFF (solid white). + + + Creates a BitmapData object with a specified width and height. + If you specify a value for the fillColor parameter, every pixel in the bitmap is set + to that color. + +

By default, the bitmap is created as transparent, unless you pass the value false + for the transparent parameter. After you create an opaque bitmap, you cannot change it to + a transparent bitmap. Every pixel in an opaque bitmap uses only 24 bits of color channel information. + If you define the bitmap as transparent, every pixel uses 32 bits of color channel information, + including an alpha transparency channel.

+ +

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is + 2,880 pixels in height and 2,880 pixels in width. + If you specify a width or height value that is greater than 2880, a new instance is not created.

+ +
applyFilter + Takes a source image and a filter object and generates the + filtered image.The sourceBitmapData, sourceRect, destPoint or filter are null. + TypeErrorTypeErrorThe transparency of the BitmapData objects are not + compatible with the filter operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorA number that indicates whether the filter was applied successfully. + If 0 is returned, the filter was applied successfully. + If a negative number is returned, an error occurred during the application of the filter. + + sourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different + BitmapData object or it can refer to the current BitmapData instance. + + + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + + destPointflash.geom:PointThe point within the destination image (the current BitmapData + instance) that corresponds to the upper-left corner of the source rectangle. + + filterflash.filters:BitmapFilterThe filter object that you use to perform the filtering operation. Each type + of filter has certain requirements, as follows: + +
  • BlurFilter — + This filter can use source and destination images + that are either opaque or transparent. If the formats of the images do + not match, the copy of the source image that is made during the + filtering matches the format of the destination image.
  • BevelFilter, DropShadowFilter, GlowFilter, ChromeFilter — + The destination image of these filters must be a transparent + image. Calling DropShadowFilter or GlowFilter creates an image that + contains the alpha channel data of the drop shadow or glow. It does not + create the drop shadow onto the destination image. If you use any of these + filters with an opaque destination image, an exception + is thrown.
  • ConvolutionFilter — This filter can use source and + destination images that are either opaque or transparent.
  • ColorMatrixFilter — This filter can use source and + destination images that are either opaque or transparent.
  • DisplacementMapFilter — This filter can use source and + destination images that are either opaque or transparent, but the + source and destination image formats must be the same.
+ +
+ Takes a source image and a filter object and generates the + filtered image. + +

This method relies on the behavior of built-in filter + objects, which determine the destination + rectangle that is affected by an input source rectangle.

+ +

After a filter is applied, the resulting image can be larger than the input image. + For example, if you use a BlurFilter class + to blur a source rectangle of (50,50,100,100) and a + destination point of (10,10), the area that changes in the + destination image is larger than (10,10,60,60) because of + the blurring. This happens internally during the applyFilter() + call.

+ +

If the sourceRect parameter of the sourceBitmapData parameter is + an interior region, such as (50,50,100,100) in a 200 x 200 image, the filter uses the source + pixels outside the sourceRect parameter to generate + the destination rectangle.

+ +

If the BitmapData object and the object specified as the sourceBitmapData + parameter are the same object, the application uses a temporary copy of the object to + perform the filter. For best performance, avoid this situation.

+ +
The following example shows how to apply a blur filter to a BitmapData instance: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Point; +import flash.geom.Rectangle; +import flash.filters.BlurFilter; + +var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00); +var rect:Rectangle = new Rectangle(10, 10, 40, 10); +bmd.fillRect(rect, 0xFF0000); + +var pt:Point = new Point(10, 10); +var filter:BlurFilter = new BlurFilter(); +bmd.applyFilter(bmd, rect, pt, filter); + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +
flash.filters.BevelFilterflash.filters.BlurFilterflash.filters.ColorMatrixFilterflash.filters.ConvolutionFilterflash.filters.DisplacementMapFilterflash.filters.DropShadowFilterflash.filters.GlowFilterflash.display.DisplayObject.filters
clone + Returns a new BitmapData object that is a clone of the original instance + with an exact copy of the contained bitmap.A new BitmapData object that is identical to the original. + + flash.display:BitmapDataReturns a new BitmapData object with an exact copy of the original bitmap. + + + + + Returns a new BitmapData object that is a clone of the original instance + with an exact copy of the contained bitmap. + + The following example shows how to clone a BitmapData instance, and it shows that when you modify the + cloned BitmapData instance, the original remains unmodified: + + +import flash.display.Bitmap; +import flash.display.BitmapData; + +var bmd1:BitmapData = new BitmapData(100, 80, false, 0x00000000); +var bmd2:BitmapData = bmd1.clone(); + +bmd1.setPixel32(1, 1, 0xFFFFFFFF); + +trace(bmd1.getPixel32(1, 1).toString(16)); // ffffffff +trace(bmd2.getPixel32(1, 1).toString(16)); // ff000000 + +var bm1:Bitmap = new Bitmap(bmd1); +this.addChild(bm1); + +var bm2:Bitmap = new Bitmap(bmd2); +bm2.x = 110; +this.addChild(bm2); +colorTransform + Adjusts the color values in a specified area of a bitmap image by using a + ColorTransform object.The rect or colorTransform are null. + + TypeErrorTypeErrorrectflash.geom:RectangleA Rectangle object that defines the area of the image in which the + ColorTransform object is applied. + + colorTransformflash.geom:ColorTransformA ColorTransform object that describes the color transformation + values to apply. + + + Adjusts the color values in a specified area of a bitmap image by using a + ColorTransform object. If the rectangle + matches the boundaries of the bitmap image, this method transforms the color values of + the entire image. + + The following example shows how to apply a color transform to the left half (rectangle) of a + BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.ColorTransform; + +var bmd:BitmapData = new BitmapData(80, 30, false, 0xFF0000); + +var cTransform:ColorTransform = new ColorTransform(); +cTransform.alphaMultiplier = 0.5 +var rect:Rectangle = new Rectangle(0, 0, 40, 30); +bmd.colorTransform(rect, cTransform); + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +flash.geom.ColorTransformflash.geom.Rectanglecompare + + Compares two BitmapData objects.The otherBitmapData is null. + + TypeErrorTypeErrorIf the two BitmapData objects have the same dimensions (width and height), the + method returns a new BitmapData object that has the difference between the two objects (see the + main discussion). If the BitmapData objects are equivalent, the method returns the number 0. + If the widths of the BitmapData objects are not equal, the method returns the number -3. + If the heights of the BitmapData objects are not equal, the method returns the number -4. + + ObjectotherBitmapDataflash.display:BitmapDataThe BitmapData object to compare with the source BitmapData object. + + + + Compares two BitmapData objects. If the two BitmapData objects have the same dimensions + (width and height), the method returns a new BitmapData object, in which each pixel is + the "difference" between the pixels in the two source objects: + +
  • If two pixels are equal, the difference pixel is 0x00000000.
  • If two pixels have different RGB values (ignoring the alpha value), the difference + pixel is 0xRRGGBB where RR/GG/BB are the individual difference values between red, green, + and blue channels (the pixel value in the source object minus the pixel value in the + otherBitmapData object). Alpha channel differences are ignored in this case.
  • If only the alpha channel value is different, the pixel value is 0xZZFFFFFF, + where ZZ is the difference in the alpha values (the alpha value in the source object + minus the alpha value in the otherBitmapData object).
+ +

For example, consider the following two BitmapData objects:

+ + + var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFF8800); + var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCCC6600); + var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData; + trace ("0x" + diffBmpData.getPixel(0,0).toString(16); // 0x332200 + + + + +

Note: The colors used to fill the two BitmapData objects have slightly different RGB values + (0xFF0000 and 0xFFAA00). The result of the compare() method is a new BitmapData + object with each pixel showing the difference in the RGB values between the two bitmaps.

+ +

Consider the following two BitmapData objects, in which the RGB colors are the same, + but the alpha values are different:

+ + + var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00); + var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00); + var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData; + trace ("0x" + diffBmpData.getPixel32(0,0).toString(16); // 0x33ffffff + + + + +

The result of the compare() method is a new BitmapData + object with each pixel showing the difference in the alpha values between the two bitmaps.

+ +

If the BitmapData objects are equivalent (with the same width, height, and identical pixel values), + the method returns the number 0.

+ +

If the widths of the BitmapData objects are not equal, the method returns the number -3.

+ +

If the heights of the BitmapData objects are not equal, but the widths are the same, + the method returns the number -4.

+ +

The following example compares two Bitmap objects with different widths (50 and 60):

+ + + var bmd1:BitmapData = new BitmapData(100, 50, false, 0xFFFF0000); + var bmd2:BitmapData = new BitmapData(100, 60, false, 0xFFFFAA00); + trace(bmd1.compare(bmd2)); // -4 + + + + +
The following example shows the value of a pixel in the BitmapData object that results from + comparing two BitmapData objects of the same dimensions: + + +import flash.display.Bitmap; +import flash.display.BitmapData; + +var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00); +var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00); +var diffBmpData:BitmapData = BitmapData(bmd1.compare(bmd2)); +var diffValue:String = diffBmpData.getPixel32(1, 1).toString(16); +trace (diffValue); // 33ffffff + +var bm1:Bitmap = new Bitmap(bmd1); +addChild(bm1); +var bm2:Bitmap = new Bitmap(bmd2); +addChild(bm2); +bm2.x = 60; +
copyChannel + Transfers data from one channel of another BitmapData object or the current + BitmapData object into a channel of the current BitmapData object.The sourceBitmapData, sourceRect or destPoint are null. + + TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different BitmapData object + or it can refer to the current BitmapData object. + + sourceRectflash.geom:RectangleThe source Rectangle object. To copy only channel data from a smaller area + within the bitmap, specify a source rectangle that is smaller than the overall size of the + BitmapData object. + + destPointflash.geom:PointThe destination Point object that represents the upper-left corner of the rectangular area + where the new channel data is placed. + To copy only channel data + from one area to a different area in the destination image, specify a point other than (0,0). + + sourceChanneluintThe source channel. Use a value from the BitmapDataChannel class + (BitmapDataChannel.RED, BitmapDataChannel.BLUE, + BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA). + + destChanneluintThe destination channel. Use a value from the BitmapDataChannel class + (BitmapDataChannel.RED, BitmapDataChannel.BLUE, + BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA). + + + Transfers data from one channel of another BitmapData object or the current + BitmapData object into a channel of the current BitmapData object. + All of the data in the other channels in the destination BitmapData object are + preserved. + +

The source channel value and destination channel value can be + one of following values:

+
  • BitmapDataChannel.RED
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.BLUE
  • BitmapDataChannel.ALPHA
+ + +
The following example shows how to copy the red channel in a BitmapData object to its own + blue channel in a 20 x 20 pixel region: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.Point; + +var bmd:BitmapData = new BitmapData(100, 80, false, 0x00FF0000); + +var rect:Rectangle = new Rectangle(0, 0, 20, 20); +var pt:Point = new Point(10, 10); +bmd.copyChannel(bmd, rect, pt, BitmapDataChannel.RED, BitmapDataChannel.BLUE); + +var bm:Bitmap = new Bitmap(bmd); +this.addChild(bm); +
flash.geom.Rectangle
copyPixels + Provides a fast routine to perform pixel manipulation + between images with no stretching, rotation, or color effects.The sourceBitmapData, sourceRect, destPoint are null. + + TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image from which to copy pixels. The source image can be a + different BitmapData instance, or it can refer to the current BitmapData + instance. + + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + + destPointflash.geom:PointThe destination point that represents the upper-left corner of the rectangular + area where the new pixels are placed. + + alphaBitmapDataflash.display:BitmapDatanullA secondary, alpha BitmapData object source. + + alphaPointflash.geom:PointnullThe point in the alpha BitmapData object source that corresponds to + the upper-left corner of the sourceRect parameter. + + mergeAlphaBooleanfalseTo use the alpha channel, set the value to + true. To copy pixels with no alpha channel, set the value to + false. + + + Provides a fast routine to perform pixel manipulation + between images with no stretching, rotation, or color effects. This method copies a + rectangular area of a source image to a + rectangular area of the same size at the destination point of the destination + BitmapData object. + +

If you include the alphaBitmap and alphaPoint parameters, you can use a secondary + image as an alpha source for the source image. If the source + image has alpha data, both sets of alpha data are used to + composite pixels from the source image to the destination image. The + alphaPoint parameter is the point in the alpha image that + corresponds to the upper-left corner of the source + rectangle. Any pixels outside the intersection of the source + image and alpha image are not copied to the destination image.

+ +

The mergeAlpha property controls whether or not the alpha + channel is used when a transparent image is copied onto + another transparent image. To copy + pixels with the alpha channel data, set the mergeAlpha + property to true. By default, the mergeAlpha property is + false.

+ +
The following example shows how to copy pixels from a 20 x 20 pixel region in one BitmapData object + to another BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.Point; + +var bmd1:BitmapData = new BitmapData(40, 40, false, 0x000000FF); +var bmd2:BitmapData = new BitmapData(80, 40, false, 0x0000CC44); + +var rect:Rectangle = new Rectangle(0, 0, 20, 20); +var pt:Point = new Point(10, 10); +bmd2.copyPixels(bmd1, rect, pt); + +var bm1:Bitmap = new Bitmap(bmd1); +this.addChild(bm1); +var bm2:Bitmap = new Bitmap(bmd2); +this.addChild(bm2); +bm2.x = 50; +
dispose + Frees memory that is used to store the BitmapData object. + Frees memory that is used to store the BitmapData object. + +

When the dispose() method is called on an image, the width and height of the image are set to 0. + All subsequent calls to methods or properties of this BitmapData instance fail, and an + exception is thrown.

+

BitmapData.dispose() releases the memory occupied by the actual bitmap data, immediately (a bitmap can consume up to 64 MB of memory). + After using BitmapData.dispose(), the BitmapData object is no longer usable and the Flash runtime throws an exception if you call + functions on the BitmapData object. + However, BitmapData.dispose() does not garbage collect the BitmapData object (approximately 128 bytes); the memory occupied by the actual + BitmapData object is released at the time the BitmapData object is collected by the garbage collector.

+ +
The following example shows the effect of calling a method of a BitmapData object after a call to the + dispose() method (an exception is thrown): + +import flash.display.BitmapData; + +var myBitmapData:BitmapData = new BitmapData(100, 80, false, 0x000000FF); +trace(myBitmapData.getPixel(1, 1)); // 255 == 0xFF + +myBitmapData.dispose(); +try { + trace(myBitmapData.getPixel(1, 1)); +} catch (error:Error) { + trace(error); // ArgumentError +} +
flash.system.System.gc()
draw + Draws the source display object onto the bitmap image, using the + Flash runtime vector renderer.The source parameter is not a BitmapData + or DisplayObject object. + + ArgumentErrorArgumentErrorThe source object and (in the case of + a Sprite or MovieClip object) all of its child objects do not come from the same domain as + the caller, or are not in a content that is accessible to the caller by having called the + Security.allowDomain() method. This restriction does not apply + to AIR content in the application security sandbox. + + SecurityErrorSecurityErrorThe source is null or not a valid IBitmapDrawable object. + + ArgumentErrorArgumentErrorsourceflash.display:IBitmapDrawableThe display object or BitmapData object to draw to the BitmapData object. + (The DisplayObject and BitmapData classes implement the IBitmapDrawable interface.) + + + matrixflash.geom:MatrixnullA Matrix object used to scale, rotate, or translate the coordinates + of the bitmap. If you do not want to apply a matrix transformation to the image, + set this parameter to an identity matrix, created with the default + new Matrix() constructor, or pass a null value. + + colorTransformflash.geom:ColorTransformnullA ColorTransform object that you use to adjust the color values of + the bitmap. If no object is supplied, the bitmap image's colors are not transformed. + If you must pass this parameter but you do not want to transform the image, set this + parameter to a ColorTransform object created with the default new ColorTransform() + constructor. + + blendModeStringnullA string value, from the flash.display.BlendMode class, specifying the + blend mode to be applied to the resulting bitmap. + + clipRectflash.geom:RectanglenullA Rectangle object that defines the area of the source object to draw. + If you do not supply this value, no clipping occurs and the entire source object is drawn. + + smoothingBooleanfalseA Boolean value that determines whether a BitmapData object is + smoothed when scaled or rotated, due to a scaling or rotation in the matrix + parameter. The smoothing parameter only applies if the source + parameter is a BitmapData object. With smoothing set to false, + the rotated or scaled BitmapData image can appear pixelated or jagged. For example, the following + two images use the same BitmapData object for the source parameter, but the + smoothing parameter is set to true on the left and false + on the right: + +

+ +

Drawing a bitmap with smoothing set to true takes longer + than doing so with smoothing set to false.

+ +
+ Draws the source display object onto the bitmap image, using the + Flash runtime vector renderer. + You can specify matrix, colorTransform, + blendMode, and a destination clipRect parameter to control + how the rendering performs. Optionally, you can specify whether the bitmap + should be smoothed when scaled (this works only if the source object + is a BitmapData object). + +

This method directly corresponds to how objects are drawn + with the standard vector renderer for objects in the authoring tool + interface.

+ +

The source display object does not use any of its applied transformations + for this call. It is treated as it exists in the library or + file, with no matrix transform, no color transform, and no blend + mode. To draw a display object (such as a movie clip) by using its own transform properties, + you can copy its transform property object to the transform property + of the Bitmap object that uses the BitmapData object.

+ +

This method is supported over RTMP in Flash Player 9.0.115.0 + and later and in Adobe AIR. You can control access to streams on + Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess + and Client.videoSampleAccess properties in + Server-Side ActionScript Language Reference for Adobe Flash Media Server.

+ +

If the source object and (in the case of a Sprite or MovieClip object) all + of its child objects do not come from the same domain as the caller, or are not in a content that is + accessible to the caller by having called the Security.allowDomain() method, a call to + the draw() throws a SecurityError exception. This restriction does not apply + to AIR content in the application security sandbox.

+ +

There are also restrictions on using a loaded bitmap image as the source. + A call to the draw() method is successful if the loaded image comes from the same domain as the caller. + Also, a cross-domain policy file on the image's server can grant permission to the domain of the SWF content + calling the draw() method. In this case, you must set the checkPolicyFile property + of a LoaderContext object, and use this object as the context parameter when calling the load() + method of the Loader object used to load the image. These restrictions do not apply to AIR content in the + application security sandbox.

+ +

On Windows, the draw() method cannot capture SWF content embedded in an HTML + page in an HTMLLoader object in Adobe AIR.

+ +

The draw() method cannot capture PDF content in Adobe AIR. + Nor can it capture or SWF content embedded in HTML in which the wmode attribute is set + to "window" in Adobe AIR.

+ +
The following example shows how to draw a TextField object to a BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.text.TextField; + +var tf:TextField = new TextField(); +tf.text = "bitmap text"; + +var myBitmapData:BitmapData = new BitmapData(80, 20); +myBitmapData.draw(tf); +var bmp:Bitmap = new Bitmap(myBitmapData); +this.addChild(bmp); +
flash.display.BlendModeflash.geom.ColorTransformflash.geom.Matrixflash.system.JPEGLoaderContext
fillRect + Fills a rectangular area of pixels with a specified ARGB color.The rect is null. + + TypeErrorTypeErrorrectflash.geom:RectangleThe rectangular area to fill. + coloruintThe ARGB color value that fills the area. ARGB colors are often + specified in hexadecimal format; for example, 0xFF336699. + + + Fills a rectangular area of pixels with a specified ARGB color. + + The following example shows how to fill a rectangular region of a BitmapData object with blue: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; + +var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00); + +var rect:Rectangle = new Rectangle(0, 0, 20, 20); +myBitmapData.fillRect(rect, 0x0000FF); + +var bm:Bitmap = new Bitmap(myBitmapData); +addChild(bm); +flash.geom.RectanglefloodFill + Performs a flood fill operation on an image starting + at an (x, y) coordinate and filling with a certain color.xintThe x coordinate of the image. + yintThe y coordinate of the image. + coloruintThe ARGB color to use as a fill. + + Performs a flood fill operation on an image starting + at a (x, y) coordinate. + + + Performs a flood fill operation on an image starting + at an (x, y) coordinate and filling with a certain color. The + floodFill() method is similar to the paint bucket tool in various paint + programs. The color is an ARGB color that contains alpha information and + color information. + + The following example shows how to fill a region of a BitmapData object — that is, the region + surrounding the pixel defined by the point (10, 10) in which all colors match the color at that + point — with red + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; + +var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00); + +var rect:Rectangle = new Rectangle(0, 0, 20, 20); +myBitmapData.fillRect(rect, 0x000000FF); +rect = new Rectangle(15, 15, 25, 25); +myBitmapData.fillRect(rect, 0x000000FF); + +myBitmapData.floodFill(10, 10, 0x00FF0000); + +var bm:Bitmap = new Bitmap(myBitmapData); +addChild(bm); +generateFilterRect + Determines the destination rectangle that the applyFilter() method call affects, given a + BitmapData object, a source rectangle, and a filter object.The sourceRect or filter are null. + + TypeErrorTypeErrorA destination rectangle computed by using an image, the sourceRect parameter, + and a filter. + + flash.geom:RectanglesourceRectflash.geom:RectangleA rectangle defining the area of the source image to use as input. + filterflash.filters:BitmapFilterA filter object that you use to calculate the destination rectangle. + + Determines the destination rectangle that will be affected by the applyFilter() call. + + + Determines the destination rectangle that the applyFilter() method call affects, given a + BitmapData object, a source rectangle, and a filter object. + +

For example, a blur filter normally affects an area larger than the size of the original + image. A 100 x 200 pixel image that is being filtered by a default BlurFilter + instance, where blurX = blurY = 4 generates a destination rectangle of + (-2,-2,104,204). + The generateFilterRect() method lets you find out the size of this destination + rectangle in advance so that you can size the destination image appropriately before you perform a filter + operation.

+ +

Some filters clip their destination rectangle based on the source image size. + For example, an inner DropShadow does not generate a larger result than its source + image. In this API, the BitmapData object is used as the source bounds and not the + source rect parameter.

+ +
The following example shows how you can use the generateFilterRect() method to + determine the rectangular area that the result of a blur filter will occupy. The results of the + generateFilterRect() method are output by the trace() function: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Point; +import flash.geom.Rectangle; +import flash.filters.BlurFilter; + +var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00); +var rect:Rectangle = new Rectangle(10, 10, 40, 10); +bmd.fillRect(rect, 0xFF0000); + +var pt:Point = new Point(10, 10); +var filter:BlurFilter = new BlurFilter(); + +trace(bmd.generateFilterRect(rect, filter)); +// (x=8, y=8, w=44, h=14) + +bmd.applyFilter(bmd, rect, pt, filter); +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); + Note that the generateFilterRect() method does not apply the filter. Call the applyFilter() method + to apply the filter. +
getColorBoundsRect + Determines a rectangular region that either fully encloses all pixels of a specified color within the + bitmap image (if the findColor parameter is set to true) or fully encloses + all pixels that do not include the specified color (if the findColor parameter is set + to false).The region of the image that is the specified color. + + flash.geom:RectanglemaskuintA hexadecimal value, specifying the bits of the ARGB color to consider. The color + value is combined with this hexadecimal value, by using the & (bitwise AND) operator. + + coloruintA hexadecimal value, specifying the ARGB color to match (if findColor + is set to true) or not to match (if findColor + is set to false). + + findColorBooleantrueIf the value is set to true, returns the bounds of a color value in an image. + If the value is set to false, returns the bounds of where this color doesn't exist in an image. + + + Determines a rectangular region that either fully encloses all pixels of a specified color within the + bitmap image (if the findColor parameter is set to true) or fully encloses + all pixels that do not include the specified color (if the findColor parameter is set + to false). + +

For example, if you have a source image and you want to determine the rectangle of + the image that contains a nonzero alpha channel, pass + {mask: 0xFF000000, color: 0x00000000} as parameters. If the findColor + parameter is set to true, the entire image is searched for the bounds of pixels + for which (value & mask) == color (where value is the color value + of the pixel). If the findColor parameter is set to false, the entire + image is searched for the bounds of pixels for which (value & mask) != color + (where value is the color value of the pixel). To determine white space around an + image, pass {mask: 0xFFFFFFFF, color: 0xFFFFFFFF} + to find the bounds of nonwhite pixels.

+ +
The following example creates a BitmapData object with red in the top half of its pixels. It then calls + the getColorBoundsRect() method to determine the rectangle in which pixels are red (0xFF0000), and + then it calls the same method to determine the rectangle in which pixels are not red (by setting the + findColor parameter to false: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; + +var bmd:BitmapData = new BitmapData(80, 40, false, 0xFFFFFF); +var rect:Rectangle = new Rectangle(0, 0, 80, 20); +bmd.fillRect(rect, 0xFF0000); + +var maskColor:uint = 0xFFFFFF; +var color:uint = 0xFF0000; +var redBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, true); +trace(redBounds); // (x=0, y=0, w=80, h=20) + +var notRedBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, false); +trace(notRedBounds); // (x=0, y=20, w=80, h=20) + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +
getPixel32 + Returns an ARGB color value that contains alpha channel data and RGB + data.A number representing an ARGB pixel value. If the (x, y) coordinates are + outside the bounds of the image, 0 is returned. + + uintxintThe x position of the pixel. + yintThe y position of the pixel. + + + Returns an ARGB color value that contains alpha channel data and RGB + data. This method is similar to the getPixel() method, which returns an + RGB color without alpha channel data. + +

All pixels in a BitmapData object are stored as premultiplied color values. + A premultiplied image pixel has the red, green, and blue + color channel values already multiplied by the alpha data. For example, if the + alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied + values. This loss of data can cause some problems when you perform operations. All BitmapData + methods take and return unmultiplied values. The internal pixel representation is converted + from premultiplied to unmultiplied before it is returned as a value. During a set operation, + the pixel value is premultiplied before the raw image pixel is set.

+ +
The following example creates a BitmapData object filled with a color, then uses the + getPixel32() method to determine the color value in the upper-left pixel, and then + determines the hexidecimal values for each color component (alpha, red, green, and blue): + + +import flash.display.BitmapData; + +var bmd:BitmapData = new BitmapData(80, 40, true, 0xFF44AACC); + +var pixelValue:uint = bmd.getPixel32(0, 0); +var alphaValue:uint = pixelValue >> 24 & 0xFF; +var red:uint = pixelValue >> 16 & 0xFF; +var green:uint = pixelValue >> 8 & 0xFF; +var blue:uint = pixelValue & 0xFF; + +trace(alphaValue.toString(16)); // ff +trace(red.toString(16)); // 44 +trace(green.toString(16)); // aa +trace(blue.toString(16)); // cc +
getPixel()setPixel32()
getPixel + Returns an integer that represents an RGB pixel value from a BitmapData object at + a specific point (x, y).A number that represents an RGB pixel value. If the (x, y) coordinates are + outside the bounds of the image, the method returns 0. + + uintxintThe x position of the pixel. + yintThe y position of the pixel. + + Returns an integer representing a RGB pixel value from a BitmapData object at + a specific point. + + + Returns an integer that represents an RGB pixel value from a BitmapData object at + a specific point (x, y). The getPixel() method returns an + unmultiplied pixel value. No alpha information is returned. + +

All pixels in a BitmapData object are stored as premultiplied color values. + A premultiplied image pixel has the red, green, and blue + color channel values already multiplied by the alpha data. For example, if the + alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied + values. This loss of data can cause some problems when you perform operations. All BitmapData + methods take and return unmultiplied values. The internal pixel representation is converted + from premultiplied to unmultiplied before it is returned as a value. During a set operation, + the pixel value is premultiplied before the raw image pixel is set.

+ +
The following example creates a BitmapData object filled with red, then uses the + getPixel() method to determine the color value in the upper-left pixel: + +import flash.display.BitmapData; + +var bmd:BitmapData = new BitmapData(80, 40, false, 0xFF0000); + +var pixelValue:uint = bmd.getPixel(0, 0); +trace(pixelValue.toString(16)); // ff0000; +
getPixel32()setPixel()
getPixels + Generates a byte array from a rectangular region of pixel data.The rect is null. + + TypeErrorTypeErrorA ByteArray representing the pixels in the given Rectangle. + + flash.utils:ByteArrayrectflash.geom:RectangleA rectangular area in the current BitmapData object. + + + Generates a byte array from a rectangular region of pixel data. + Writes an unsigned integer (a 32-bit unmultiplied pixel value) + for each pixel into the byte array. + + The following example creates a BitmapData object filled with random noise pixels, then uses the + getPixels() method to fill a ByteArray object with the pixel values of the BitmapData object + +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.utils.ByteArray; + +var bmd:BitmapData = new BitmapData(80, 40, true); +var seed:int = int(Math.random() * int.MAX_VALUE); +bmd.noise(seed); + +var bounds:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height); +var pixels:ByteArray = bmd.getPixels(bounds); +flash.utils.ByteArraygetVector + Generates a vector array from a rectangular region of pixel data.The rect is null. + + TypeErrorTypeErrorA Vector representing the given Rectangle. + rectflash.geom:RectangleA rectangular area in the current BitmapData object. + + + Generates a vector array from a rectangular region of pixel data. + Returns a Vector object of unsigned integers (a 32-bit unmultiplied pixel value) + for the specified rectangle. + + + histogram + Computes a 256-value binary number histogram of a BitmapData object.hRectflash.geom:RectanglenullThe area of the BitmapData object to use. + + + Computes a 256-value binary number histogram of a BitmapData object. This method returns a Vector object + containing four Vector.<Number> instances (four Vector objects that contain Number objects). + The four Vector instances represent the red, green, blue and alpha components + in order. Each Vector instance contains 256 values that represent the population + count of an individual component value, from 0 to 255. + + hitTest + Performs pixel-level hit detection between one bitmap image + and a point, rectangle, or other bitmap image.The secondObject parameter is not a Point, Rectangle, + Bitmap, or BitmapData object. + + ArgumentErrorArgumentErrorThe firstPoint is null. + + TypeErrorTypeErrorA value of true if a hit occurs; otherwise, false. + + BooleanfirstPointflash.geom:Point A position of the upper-left corner of the BitmapData image in an arbitrary coordinate space. + The same coordinate space is used in defining the secondBitmapPoint parameter. + + firstAlphaThresholduintThe smallest alpha channel value that is considered opaque for this hit test. + + secondObjectObjectA Rectangle, Point, Bitmap, or BitmapData object. + + secondBitmapDataPointflash.geom:PointnullA point that defines a pixel location in the second BitmapData object. + Use this parameter only when the value of secondObject is a + BitmapData object. + + secondAlphaThresholduint1The smallest alpha channel value that is considered opaque in the second BitmapData object. + Use this parameter only when the value of secondObject is a + BitmapData object and both BitmapData objects are transparent. + + + Performs pixel-level hit detection between one bitmap image + and a point, rectangle, or other bitmap image. A hit is defined as + an overlap of a point or rectangle over an opaque pixel, or two + overlapping opaque pixels. No stretching, + rotation, or other transformation of either object is considered when + the hit test is performed. + +

If an image is an opaque image, it is considered a fully opaque rectangle for this + method. Both images must be transparent images to perform pixel-level hit testing that + considers transparency. When you are testing two transparent images, the alpha threshold + parameters control what alpha channel values, from 0 to 255, are considered opaque.

+ +
The following example creates a BitmapData object that is only opaque in a rectangular region + (20, 20, 40, 40) and calls the hitTest() method with a Point object as the secondObject. + In the first call, the Point object defines the upper-left corner of the BitmapData object, which is not opaque, and + in the second call, the Point object defines the center of the BitmapData object, which is opaque. + +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.Point; + +var bmd1:BitmapData = new BitmapData(80, 80, true, 0x00000000); +var rect:Rectangle = new Rectangle(20, 20, 40, 40); +bmd1.fillRect(rect, 0xFF0000FF); + +var pt1:Point = new Point(1, 1); +trace(bmd1.hitTest(pt1, 0xFF, pt1)); // false +var pt2:Point = new Point(40, 40); +trace(bmd1.hitTest(pt1, 0xFF, pt2)); // true +
lock + Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, + are not updated when this BitmapData object changes. + Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, + are not updated when this BitmapData object changes. To improve performance, use this method + along with the unlock() method before and after numerous calls to the + setPixel() or setPixel32() method. + + The following example creates a BitmapData object based on the + bitmapData property of a Bitmap object, picture. + It then calls the lock() method before calling a complicated custom function, + complexTransformation(), that modifies the BitmapData object. (The picture object + and the complexTransformation() function are not defined in this example.) Even if the + complexTransformation() function updates the bitmapData property of + the picture object, changes are not reflected until the code calls the + unlock() method on the bitmapData object: + +import flash.display.BitmapData; + +var bitmapData:BitmapData = picture.bitmapData; +bitmapData.lock(); +bitmapData = complexTransformation(bitmapData); +bitmapData.unlock(); +picture.bitmapData = bitmapData; +setPixel()setPixel32()unlock()merge + Performs per-channel blending from a source image to a destination image.The sourceBitmapData, sourceRect or destPoint are null. + + TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different + BitmapData object, or it can refer to the current BitmapData object. + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + destPointflash.geom:PointThe point within the destination image (the current BitmapData + instance) that corresponds to the upper-left corner of the source rectangle. + redMultiplieruintA hexadecimal uint value by which to multiply the red channel value. + greenMultiplieruintA hexadecimal uint value by which to multiply the green channel value. + blueMultiplieruintA hexadecimal uint value by which to multiply the blue channel value. + alphaMultiplieruintA hexadecimal uint value by which to multiply the alpha transparency value. + + + Performs per-channel blending from a source image to a destination image. For each channel + and each pixel, a new value is computed based on the channel values of the source and destination + pixels. For example, in the red channel, the new value is computed as follows (where redSrc + is the red channel value for a pixel in the source image and redDest is the red channel + value at the corresponding pixel of the destination image): +

+ + new redDest = [(redSrc * redMultiplier) + (redDest * (256 - redMultiplier))] / 256; + +

+ +

The redMultiplier, greenMultiplier, blueMultiplier, and + alphaMultiplier values are the multipliers used for each color channel. Use a hexadecimal + value ranging from 0 to 0x100 (256) where 0 specifies the full + value from the destination is used in the result, 0x100 specifies the full value from the + source is used, and numbers in between specify a blend is used (such as 0x80 for 50%).

+ +
The following example creates two BitmapData objects. Both are 100 x 80 pixels in size. The first + is filled with green and the second is filled with red. The code calls the merge() method, merging + the second BitmapData pixels into the first BitmapData object, but only on a specified rectangular area: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.Point; + +var bmd1:BitmapData = new BitmapData(100, 80, true, 0xFF00FF00); +var bmd2:BitmapData = new BitmapData(100, 80, true, 0xFFFF0000); +var rect:Rectangle = new Rectangle(0, 0, 20, 20); +var pt:Point = new Point(20, 20); +var mult:uint = 0x80; // 50% +bmd1.merge(bmd2, rect, pt, mult, mult, mult, mult); + +var bm1:Bitmap = new Bitmap(bmd1); +addChild(bm1); +var bm2:Bitmap = new Bitmap(bmd2); +addChild(bm2); +bm2.x = 110; +
noise + Fills an image with pixels representing random noise.randomSeedintThe random seed number to use. If you keep all other parameters + the same, you can generate different pseudo-random results by varying the random seed value. The noise + function is a mapping function, not a true random-number generation function, so it creates the same + results each time from the same random seed. + + lowuint0The lowest value to generate for each channel (0 to 255). + highuint255The highest value to generate for each channel (0 to 255). + channelOptionsuint7A number that can be a combination of any of + the four color channel values (BitmapDataChannel.RED, + BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and + BitmapDataChannel.ALPHA). You can use the logical OR + operator (|) to combine channel values. + + grayScaleBooleanfalseA Boolean value. If the value is true, a grayscale image is created by setting + all of the color channels to the same value. + The alpha channel selection is not affected by + setting this parameter to true. + + + Fills an image with pixels representing random noise. + + The following example creates two BitmapData objects and calls the noise() + method on both. However, the grayscale parameter is set to false for the + call to the noise() method of the first object, and it is set to true for the + call to the noise() method of the second object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.display.BitmapDataChannel; + +var bmd1:BitmapData = new BitmapData(80, 80); +var bmd2:BitmapData = new BitmapData(80, 80); + +var seed:int = int(Math.random() * int.MAX_VALUE); +bmd1.noise(seed, 0, 0xFF, BitmapDataChannel.RED, false); +bmd2.noise(seed, 0, 0xFF, BitmapDataChannel.RED, true); + +var bm1:Bitmap = new Bitmap(bmd1); +this.addChild(bm1); +var bm2:Bitmap = new Bitmap(bmd2); +this.addChild(bm2); +bm2.x = 90; +flash.display.BitmapDataChannel.REDflash.display.BitmapDataChannel.BLUEflash.display.BitmapDataChannel.GREENflash.display.BitmapDataChannel.ALPHApaletteMap + Remaps the color channel values in an image that has up to four arrays of color palette data, one + for each channel.The sourceBitmapData, sourceRect or destPoint are null. + + TypeErrorTypeErrorsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different + BitmapData object, or it can refer to the current BitmapData instance. + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + destPointflash.geom:PointThe point within the destination image (the current BitmapData + object) that corresponds to the upper-left corner of the source rectangle. + redArrayArraynullIf redArray is not null, red = redArray[source red value] + else red = source rect value. + greenArrayArraynullIf greenArray is not null, green = greenArray[source + green value] else green = source green value. + blueArrayArraynullIf blueArray is not null, blue = blueArray[source blue + value] else blue = source blue value. + alphaArrayArraynullIf alphaArray is not null, alpha = alphaArray[source + alpha value] else alpha = source alpha value. + + + + Remaps the color channel values in an image that has up to four arrays of color palette data, one + for each channel. + +

Flash runtimes use the following steps to + generate the resulting image:

+ +
  1. After the red, green, blue, and alpha + values are computed, they are added together using standard 32-bit-integer arithmetic.
  2. The red, green, blue, and alpha channel values of each pixel are extracted into separate 0 to 255 values. + These values are used to look up new color values in the appropriate array: redArray, + greenArray, blueArray, and alphaArray. + Each of these four arrays should contain 256 values.
  3. After all four of the new channel values are retrieved, they are combined into a standard + ARGB value that is applied to the pixel.
+ +

Cross-channel effects can be supported with this method. + Each input array can contain full 32-bit values, and no shifting occurs when the + values are added together. This routine does not support per-channel + clamping.

+ +

If no array is specified for a channel, + the color channel is copied from the source image to the + destination image.

+ +

You can use this method for a variety of effects such as + general palette mapping (taking one channel and converting it + to a false color image). You can also use this method for a variety of advanced color + manipulation algorithms, such as gamma, curves, levels, and quantizing.

+ +
The following example creates a green BitmapData object with a red center square, and then + uses the paletteMap() method to swap red with green in the bottom rectangular half of the + BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; +import flash.geom.Point; + +var myBitmapData:BitmapData = new BitmapData(80, 80, false, 0x00FF0000); +myBitmapData.fillRect(new Rectangle(20, 20, 40, 40), 0x0000FF00); + +var redArray:Array = new Array(256); +var greenArray:Array = new Array(256); + +for(var i:uint = 0; i < 255; i++) { + redArray[i] = 0x00000000; + greenArray[i] = 0x00000000; +} + +redArray[0xFF] = 0x0000FF00; +greenArray[0xFF] = 0x00FF0000; + +var bottomHalf:Rectangle = new Rectangle(0, 0, 100, 40); +var pt:Point = new Point(0, 0); +myBitmapData.paletteMap(myBitmapData, bottomHalf, pt, redArray, greenArray); + +var bm1:Bitmap = new Bitmap(myBitmapData); +addChild(bm1); +
perlinNoise + Generates a Perlin noise image.baseXNumberFrequency to use in the x direction. For example, to generate a noise that + is sized for a 64 x 128 image, pass 64 for the baseX value. + + baseYNumberFrequency to use in the y direction. For example, to generate a noise that + is sized for a 64 x 128 image, pass 128 for the baseY value. + + numOctavesuintNumber of octaves or individual noise functions to combine to create this noise. Larger numbers of octaves create + images with greater detail. Larger numbers of octaves also require more processing time. + + randomSeedintThe random seed number to use. If you keep all other parameters the same, you can generate different + pseudo-random results by varying the random seed value. The Perlin noise function is a mapping function, not a + true random-number generation function, so it creates the same results each time from the same random seed. + + stitchBooleanA Boolean value. If the value is true, the method attempts to smooth the transition edges of the image to create seamless textures for + tiling as a bitmap fill. + + fractalNoiseBooleanA Boolean value. If the value is true, the method generates fractal noise; otherwise, + it generates turbulence. An image with turbulence has visible discontinuities in the gradient + that can make it better approximate sharper visual effects like flames and ocean waves. + + channelOptionsuint7 A number that can be a combination of any of + the four color channel values (BitmapDataChannel.RED, + BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and + BitmapDataChannel.ALPHA). You can use the logical OR + operator (|) to combine channel values. + + grayScaleBooleanfalseA Boolean value. If the value is true, a grayscale image is created by setting + each of the red, green, and blue color channels to + identical values. The alpha channel value is not affected if this value is + set to true. + + offsetsArraynullAn array of points that correspond to x and y offsets for each octave. + By manipulating the offset values you can smoothly scroll the layers of a perlinNoise image. + Each point in the offset array affects a specific octave noise function. + + + + Generates a Perlin noise image. + +

The Perlin noise generation algorithm interpolates and combines individual random noise functions (called octaves) + into a single function that generates more natural-seeming random noise. Like musical octaves, each octave function is twice the + frequency of the one before it. Perlin noise has been described as a "fractal sum of noise" because it combines multiple sets of noise data + with different levels of detail.

+ +

You can use Perlin noise functions to simulate natural + phenomena and landscapes, such as wood grain, clouds, and mountain ranges. In most cases, the output of a Perlin noise function + is not displayed directly but is used to enhance other images and give them pseudo-random variations.

+ +

Simple digital random noise functions often produce images with harsh, contrasting points. This kind of harsh contrast + is not often found in nature. The Perlin noise algorithm blends multiple noise functions that operate at different levels of detail. + This algorithm results in smaller variations among neighboring pixel values.

+ +
The following example creates a 200 x 200 pixel BitmapData object that calls the + perlinNoise() method to generate a red and blue watercolor effect: + + +import flash.display.Bitmap; +import flash.display.BitmapData; + +var bmd:BitmapData = new BitmapData(200, 200, false, 0x00CCCCCC); + +var seed:Number = Math.floor(Math.random() * 10); +var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE; +bmd.perlinNoise(100, 80, 6, seed, false, true, channels, false, null); + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +
pixelDissolve + Performs a pixel dissolve either from a source image to a destination image or by using the same image.The sourceBitmapData, sourceRect or destPoint are null. + TypeErrorTypeErrorThe numPixels value is negative + + TypeErrorTypeErrorThe new random seed value to use for subsequent calls. + + intsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different + BitmapData object, or it can refer to the current BitmapData instance. + + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + + destPointflash.geom:PointThe point within the destination image (the current BitmapData + instance) that corresponds to the upper-left corner of the source rectangle. + + randomSeedint0The random seed to use to start the pixel dissolve. + + numPixelsint0The default is 1/30 of the source area (width x height). + + fillColoruint0An ARGB color value that you use to fill pixels whose + source value equals its destination value. + + + Performs a pixel dissolve either from a source image to a destination image or by using the same image. + Flash runtimes use a randomSeed value + to generate a random pixel dissolve. The return value + of the function must be passed in on subsequent calls to + continue the pixel dissolve until it is finished. + +

If the source image does not equal the destination image, + pixels are copied from the source to the destination by using all of the + properties. This process allows dissolving from a blank image into a + fully populated image.

+ +

If the source and destination images are equal, pixels are + filled with the color parameter. This process allows dissolving away + from a fully populated image. In this mode, the destination + point parameter is ignored.

+ +
The following example uses the pixelDissolve() + method to convert a grey BitmapData object to a red one by dissolving + 40 pixels at a time until all pixels have changed colors: + +import flash.display.BitmapData; +import flash.display.Bitmap; +import flash.geom.Point; +import flash.geom.Rectangle; +import flash.utils.Timer; +import flash.events.TimerEvent; + +var bmd:BitmapData = new BitmapData(100, 80, false, 0x00CCCCCC); +var bitmap:Bitmap = new Bitmap(bmd); +addChild(bitmap); + +var tim:Timer = new Timer(20); +tim.start(); +tim.addEventListener(TimerEvent.TIMER, timerHandler); + +function timerHandler(event:TimerEvent):void { + var randomNum:Number = Math.floor(Math.random() * int.MAX_VALUE); + dissolve(randomNum); +} + +function dissolve(randomNum:Number):void { + var rect:Rectangle = bmd.rect; + var pt:Point = new Point(0, 0); + var numberOfPixels:uint = 100; + var red:uint = 0x00FF0000; + bmd.pixelDissolve(bmd, rect, pt, randomNum, numberOfPixels, red); + var grayRegion:Rectangle = bmd.getColorBoundsRect(0xFFFFFFFF, 0x00CCCCCC, true); + if(grayRegion.width == 0 && grayRegion.height == 0 ) { + tim.stop(); + } +} +
scroll + Scrolls an image by a certain (x, y) pixel amount.xintThe amount by which to scroll horizontally. + yintThe amount by which to scroll vertically. + + + Scrolls an image by a certain (x, y) pixel amount. Edge + regions outside the scrolling area are left unchanged. + + The following example shows the effect of scrolling a Bitmap data object 40 pixels to the right: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.geom.Rectangle; + +var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC); +var rect:Rectangle = new Rectangle(0, 0, 40, 40); +bmd.fillRect(rect, 0xFFFF0000); + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); + +trace (bmd.getPixel32(50, 20).toString(16)); // ffcccccccc + +bmd.scroll(30, 0); + +trace (bmd.getPixel32(50, 20).toString(16)); // ffff0000 +setPixel32 + Sets the color and alpha transparency values of a single pixel of a BitmapData + object.xintThe x position of the pixel whose value changes. + yintThe y position of the pixel whose value changes. + coloruintThe resulting ARGB color for the pixel. If the bitmap is opaque + (not transparent), the alpha transparency portion of this color value is ignored. + + + Sets the color and alpha transparency values of a single pixel of a BitmapData + object. This method is similar to the setPixel() method; the main difference is + that the setPixel32() method takes an + ARGB color value that contains alpha channel information. + +

All pixels in a BitmapData object are stored as premultiplied color values. + A premultiplied image pixel has the red, green, and blue + color channel values already multiplied by the alpha data. For example, if the + alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied + values. This loss of data can cause some problems when you perform operations. All BitmapData + methods take and return unmultiplied values. The internal pixel representation is converted + from premultiplied to unmultiplied before it is returned as a value. During a set operation, + the pixel value is premultiplied before the raw image pixel is set.

+ +

Note: To increase performance, when you use the setPixel() or + setPixel32() method repeatedly, call the lock() method before + you call the setPixel() or setPixel32() method, and then call + the unlock() method when you have made all pixel changes. This process prevents objects + that reference this BitmapData instance from updating until you finish making + the pixel changes.

+ +
The following example uses the setPixel32() + method to draw a transparent (alpha == 0x60) red line in a BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; + +var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC); + +for (var i:uint = 0; i < 80; i++) { + var red:uint = 0x60FF0000; + bmd.setPixel32(i, 40, red); +} + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +
setPixel()getPixel32()lock()unlock()
setPixel + Sets a single pixel of a BitmapData object.xintThe x position of the pixel whose value changes. + yintThe y position of the pixel whose value changes. + + coloruintThe resulting RGB color for the pixel. + + + Sets a single pixel of a BitmapData object. The current + alpha channel value of the image pixel is preserved during this + operation. The value of the RGB color parameter is treated as an unmultiplied color value. + +

Note: To increase performance, when you use the setPixel() or + setPixel32() method repeatedly, call the lock() method before + you call the setPixel() or setPixel32() method, and then call + the unlock() method when you have made all pixel changes. This process prevents objects + that reference this BitmapData instance from updating until you finish making + the pixel changes.

+ +
The following example uses the setPixel() + method to draw a red line in a BitmapData object: + + +import flash.display.Bitmap; +import flash.display.BitmapData; + +var bmd:BitmapData = new BitmapData(80, 80, false, 0xCCCCCC); + +for (var i:uint = 0; i < 80; i++) { + var red:uint = 0xFF0000; + bmd.setPixel(i, 40, red); +} + +var bm:Bitmap = new Bitmap(bmd); +addChild(bm); +
getPixel()setPixel32()lock()unlock()
setPixels + Converts a byte array into a rectangular region of pixel data.The inputByteArray object does not include enough data + to fill the area of the rect rectangle. The method fills as many pixels as + possible before throwing the exception. + + EOFErrorflash.errors:EOFErrorThe rect or inputByteArray are null. + + TypeErrorTypeErrorrectflash.geom:RectangleSpecifies the rectangular region of the BitmapData object. + + inputByteArrayflash.utils:ByteArrayA ByteArray object that consists of 32-bit unmultiplied pixel values + to be used in the rectangular region. + + + Converts a byte array into a rectangular region of pixel data. For each + pixel, the ByteArray.readUnsignedInt() method is called and the return value is + written into the pixel. If the byte array ends before the full rectangle + is written, the function returns. The data in the byte array is + expected to be 32-bit ARGB pixel values. No seeking is performed + on the byte array before or after the pixels are read. + + The following example uses the getPixels() and + setPixels() methods to copy pixels from one BitmapData object to another: + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.utils.ByteArray; +import flash.geom.Rectangle; + +var bmd1:BitmapData = new BitmapData(100, 100, true, 0xFFCCCCCC); +var bmd2:BitmapData = new BitmapData(100, 100, true, 0xFFFF0000); + +var rect:Rectangle = new Rectangle(0, 0, 100, 100); +var bytes:ByteArray = bmd1.getPixels(rect); + +bytes.position = 0; +bmd2.setPixels(rect, bytes); + +var bm1:Bitmap = new Bitmap(bmd1); +addChild(bm1); +var bm2:Bitmap = new Bitmap(bmd2); +addChild(bm2); +bm2.x = 110; +flash.utils.ByteArray.readUnsignedInt()setVector + Converts a Vector into a rectangular region of pixel data.The vector array is not large enough to read all the pixel data. + RangeErrorRangeErrorrectflash.geom:RectangleSpecifies the rectangular region of the BitmapData object. + + inputVectorA Vector object that consists of 32-bit unmultiplied pixel values to be used + in the rectangular region. + + + Converts a Vector into a rectangular region of pixel data. For each pixel, a Vector element is read + and written into the BitmapData pixel. The data in the Vector is expected to be 32-bit ARGB pixel values. + + threshold + Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values.The sourceBitmapData, sourceRect destPoint or operation are null. + TypeErrorTypeErrorThe operation string is not a valid operation + + ArgumentErrorArgumentErrorThe number of pixels that were changed. + uintsourceBitmapDataflash.display:BitmapDataThe input bitmap image to use. The source image can be a different + BitmapData object or it can refer to the current BitmapData instance. + + sourceRectflash.geom:RectangleA rectangle that defines the area of the source image to use as input. + + destPointflash.geom:PointThe point within the destination image (the current BitmapData + instance) that corresponds to the upper-left corner of the source rectangle. + + operationStringOne of the following comparison operators, passed as a String: "<", "<=", ">", ">=", "==", "!=" + + thresholduintThe value that each pixel is tested against to see if it meets or exceeds the threshhold. + + coloruint0The color value that a pixel is set to if the threshold test succeeds. The default value is 0x00000000. + + maskuint0xFFFFFFFFThe mask to use to isolate a color component. + + copySourceBooleanfalseIf the value is true, pixel values from the source image are copied to the destination + when the threshold test fails. If the value is false, the source image is not copied when the + threshold test fails. + + + Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values. + Using the threshold() method, you can isolate and replace color ranges in an image and perform other + logical operations on image pixels. + +

The threshold() method's test logic is as follows:

+ +
  1. If ((pixelValue & mask) operation (threshold & mask)), then + set the pixel to color;
  2. Otherwise, if copySource == true, then + set the pixel to corresponding pixel value from sourceBitmap.
+ +

The operation parameter specifies the comparison operator to use for the threshold test. + For example, by using "==" as the operation parameter, you + can isolate a specific color value in an image. Or by using {operation: + "<", mask: 0xFF000000, threshold: 0x7F000000, color: + 0x00000000}, you can set all destination pixels to be fully transparent + when the source image pixel's alpha is less than 0x7F. You can use this technique + for animated transitions and other effects.

+ +
The following example uses the perlinNoise() method to + add a blue and red pattern to one BitmapData object, and then uses the threshold() + method to copy those pixels from the first BitmapData object to a second one, replacing those pixels + in which the red value is greater than 0x80 (50%) with a pixel set to transparent red (0x20FF0000): + + +import flash.display.Bitmap; +import flash.display.BitmapData; +import flash.display.BitmapDataChannel; +import flash.geom.Point; +import flash.geom.Rectangle; + +var bmd1:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC); + +var seed:int = int(Math.random() * int.MAX_VALUE); +var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE; +bmd1.perlinNoise(100, 80, 12, seed, false, true, channels, false, null); + +var bitmap1:Bitmap = new Bitmap(bmd1); +addChild(bitmap1); + +var bmd2:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC); +var pt:Point = new Point(0, 0); +var rect:Rectangle = new Rectangle(0, 0, 200, 200); +var threshold:uint = 0x00800000; +var color:uint = 0x20FF0000; +var maskColor:uint = 0x00FF0000; +bmd2.threshold(bmd1, rect, pt, ">", threshold, color, maskColor, true); + +var bitmap2:Bitmap = new Bitmap(bmd2); +bitmap2.x = bitmap1.x + bitmap1.width + 10; +addChild(bitmap2); +
unlock + Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, + are updated when this BitmapData object changes.changeRectflash.geom:RectanglenullThe area of the BitmapData object that has changed. If you do not specify a value for + this parameter, the entire area of the BitmapData object is considered + changed. This parameter requires Flash Player version 9.0.115.0 or later. + + + Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, + are updated when this BitmapData object changes. To improve performance, use this method + along with the lock() method before and after numerous calls to the + setPixel() or setPixel32() method. + + The following example creates a BitmapData object based on the + bitmapData property of a Bitmap object, picture. + It then calls the lock() method before calling a complicated custom function, + complexTransformation(), that modifies the BitmapData object. (The picture object + and the complexTransformation() function are not defined in this example.) Even if the + complexTransformation() function updates the bitmapData property of + the picture object, changes are not reflected until the code calls the + unlock() method on the bitmapData object: + +import flash.display.BitmapData; + +var bitmapData:BitmapData = picture.bitmapData; +bitmapData.lock(); +bitmapData = complexTransformation(bitmapData); +bitmapData.unlock(); +picture.bitmapData = bitmapData; +lock()setPixel()setPixel32()height + The height of the bitmap image in pixels.int + The height of the bitmap image in pixels. + + rect + The rectangle that defines the size and location of the bitmap image.flash.geom:Rectangle + The rectangle that defines the size and location of the bitmap image. The top and left of the + rectangle are 0; the width and height are equal to the width and height in pixels of the + BitmapData object. + + transparent + Defines whether the bitmap image supports per-pixel transparency.Boolean + Defines whether the bitmap image supports per-pixel transparency. You can set this value only when you construct + a BitmapData object by passing in true for the transparent parameter of the constructor. Then, after you create + a BitmapData object, you can check whether it supports per-pixel transparency by determining if the value of the + transparent property is true. + + + width + The width of the bitmap image in pixels.int + The width of the bitmap image in pixels. + +
JointStyle +The JointStyle class is an enumeration of constant values that specify the joint style to use in drawing lines.Object +The JointStyle class is an enumeration of constant values that specify the joint style to use in drawing lines. +These constants are provided for use as values in the joints parameter of the +flash.display.Graphics.lineStyle() method. The method supports three types of joints: +miter, round, and bevel, as the following example shows: + +

+ + +
The following example uses the JointStyleExample class to show the result + of three different joint styles applied to three sets of joined lines. This task is accomplished by performing + the following steps: +
  1. The properties of each line are set as follows: +
    • The line length is set to 80 pixels.
    • The border color is set to orange.
    • The border size is set to 30 pixels.
    • The highlight color is set to gray.
    • The highlight size is set to zero pixels.
    • The alpha is set to 1, making it solid.
    • The pixel hinting is set to false (strokes not hinted to full pixels).
    • The line scale mode is set to normal, which scales the thickness.
    • The border caps and miter limit are declared but not set, so the default values are used.
  2. The class constructor creates three sets of two connected line segments. The segments start at x = 0, y = 0 + by calling the doDrawCorner() method three times using the three joint styles (miter, + round, and bevel). Each of the three calls to doDrawCorner() uses the joint style and + properties previously listed to draw two connected line segments and associated line highlights. This is done by + first creating a new Shape object child and then using methods of the Graphics + class to set the line style and draw the lines and highlights. Each instance of child + is added to the display list and promptly drawn on the stage.
  3. The connected line segments are then redrawn by using the refreshLayout() method + at y = 80 pixels and starting at x = 80 pixels, with a 25-pixel separation between the line segments.
+ +package { + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.JointStyle; + import flash.display.LineScaleMode; + import flash.display.Shape; + import flash.display.Sprite; + + public class JointStyleExample extends Sprite { + private var size:uint = 80; + private var borderColor:uint = 0xFFCC00; + private var borderSize:uint = 30; + private var highlightColor:uint = 0x666666; + private var highlightSize:uint = 0; + private var gutter:uint = 25; + private var borderAlpha:uint = 1; + private var borderPixelHinting:Boolean = false; + private var borderScaleMode:String = LineScaleMode.NORMAL; + private var borderCaps:String; + private var borderMiterLimit:uint; + + public function JointStyleExample() { + doDrawCorner(JointStyle.MITER); + doDrawCorner(JointStyle.ROUND); + doDrawCorner(JointStyle.BEVEL); + refreshLayout(); + } + + private function doDrawCorner(jointStyle:String):void { + var halfSize:uint = Math.round(size / 2); + var child:Shape = new Shape(); + child.graphics.lineStyle(borderSize, + borderColor, + borderAlpha, + borderPixelHinting, + borderScaleMode, + borderCaps, + jointStyle, + borderMiterLimit); + child.graphics.lineTo(0, 0); + child.graphics.lineTo(size, 0); + child.graphics.lineTo(halfSize, size); + child.graphics.endFill(); + + child.graphics.moveTo(0, 0); + child.graphics.lineStyle(highlightSize, highlightColor); + child.graphics.lineTo(0, 0); + child.graphics.lineTo(size, 0); + child.graphics.lineTo(halfSize, size); + + addChild(child); + } + + private function refreshLayout():void { + var ln:uint = numChildren; + var child:DisplayObject; + var lastChild:DisplayObject = getChildAt(0); + lastChild.x = size; + lastChild.y = size; + for (var i:uint = 1; i < ln; i++) { + child = getChildAt(i); + child.x = gutter + lastChild.x + lastChild.width; + child.y = size; + lastChild = child; + } + } + } +} +
flash.display.Graphics.lineStyle()BEVEL + + Specifies beveled joints in the joints parameter of the + flash.display.Graphics.lineStyle() method.bevelString + + Specifies beveled joints in the joints parameter of the + flash.display.Graphics.lineStyle() method. + + MITER + + Specifies mitered joints in the joints parameter of the + flash.display.Graphics.lineStyle() method.miterString + + Specifies mitered joints in the joints parameter of the + flash.display.Graphics.lineStyle() method. + + ROUND + + Specifies round joints in the joints parameter of the + flash.display.Graphics.lineStyle() method.roundString + + Specifies round joints in the joints parameter of the + flash.display.Graphics.lineStyle() method. + +
AVM1Movie + AVM1Movie is a simple class that represents AVM1 movie clips, which use ActionScript 1.0 or 2.0.flash.display:DisplayObject + AVM1Movie is a simple class that represents AVM1 movie clips, which use ActionScript 1.0 or 2.0. + (AVM1 is the ActionScript virtual machine used to run ActionScript 1.0 and 2.0. + AVM2 is the ActionScript virtual machine used to run ActionScript 3.0.) + When a Flash Player 8, or older, SWF file is loaded by a Loader object, an AVM1Movie + object is created. The AVM1Movie object can use methods and properties inherited from the + DisplayObject class (such as x, y, width, and so on). + However, no interoperability (such as calling methods or using parameters) between the AVM1Movie object + and AVM2 objects is allowed. + +

There are several restrictions on an AVM1 SWF file loaded by an AVM2 SWF file:

+ +
  • The loaded AVM1Movie object operates as a psuedo-root object for the AVM1 SWF file and all AVM1 SWF files + loaded by it (as if the ActionScript 1.0 lockroot property were set to true). + The AVM1 movie is always the top of any ActionScript 1.0 or 2.0 code execution in any children. + The _root property for loaded children is always this AVM1 SWF file, unless the + lockroot property is set in a loaded AVM1 SWF file.
  • The AVM1 content cannot load files into levels. For example, it cannot load files by calling + loadMovieNum("url", levelNum).
  • The AVM1 SWF file that is loaded by an AVM2 SWF file cannot load another SWF file into this. + That is, it cannot load another SWF file over itself. However, child Sprite objects, MovieClip objects, or other AVM1 + SWF files loaded by this SWF file can load into this.
+ +
DisplayObjectLoader
ShaderInput + A ShaderInput instance represents a single input image for + a shader kernel.Object + A ShaderInput instance represents a single input image for + a shader kernel. A kernel can be defined to accept zero, one, or more + source images that are used in the kernel execution. A ShaderInput + instance provides a mechanism for specifying the input image + that is used when the shader executes. To specify a value for the input, + create a BitmapData, ByteArray, or Vector.<Number> instance containing the image data + and assign it to the input property. + +

The ShaderInput instance representing a Shader instance's input image + is accessed as a property of the Shader instance's + data property. The ShaderInput property has the same name + as the input's name in the shader code. + For example, if a shader defines an input named src, + the ShaderInput instance representing the src input + is available as the src property, as this example shows:

+ + myShader.data.src.image = new BitmapData(50, 50, true, 0xFF990000); + +

For some uses of a Shader instance, you do not + need to specify an input image, because it is automatically specified by the + operation. You only need to specify an input when a Shader is used for the following:

+ +
  • Shader fill
  • ShaderFilter, only for the second or additional inputs + if the shader is defined to use more than one input. (The object to which the + filter is applied is automatically used as the first input.)
  • Shader blend mode, only for the third or additional inputs if the shader is + defined to use more than two inputs. (The objects being blended + are automatically used as the first and second inputs.)
  • ShaderJob background execution
+ +

If the shader is being executed using a ShaderJob instance to process a + ByteArray containing a linear array of data, set the ShaderInput instance's + height to 1 and width to the number of 32-bit floating + point values in the ByteArray. In that case, the input in the shader must be defined with + the image1 data type.

+ +

Generally, developer code does not create a ShaderInput instance + directly. A ShaderInput instance is created for each of a shader's inputs + when the Shader instance is created.

+ +
flash.display.ShaderDataflash.display.Shader.dataflash.display.ShaderJobShaderInput + Creates a ShaderInput instance. + Creates a ShaderInput instance. Developer code does + not call the ShaderInput constructor + directly. A ShaderInput instance is created for each of a shader's inputs + when the Shader instance is created. + + channels + The number of channels that a shader input expects.int + The number of channels that a shader input expects. This property must be + accounted for when the input data is a ByteArray or + Vector.<Number> instance. + + height + The height of the shader input.int + The height of the shader input. This property is only used when the input data + is a ByteArray or Vector.<Number> instance. When the input is a BitmapData + instance the height is automatically determined. + + index + The zero-based index of the input in the shader, indicating the order + of the input definitions in the shader.int + The zero-based index of the input in the shader, indicating the order + of the input definitions in the shader. + + input + + The input data that is used when the shader executes.Object + + The input data that is used when the shader executes. This property can be + a BitmapData instance, a ByteArray instance, or a Vector.<Number> instance. + +

If a ByteArray value is assigned to the input property, the following + conditions must be met:

+ +
  • The height and width properties must be set.
  • The byte array's contents must only consist of 32-bit floating-point values. + These values can be written using the ByteArray.writeFloat() method.
  • The total length in bytes of the ByteArray must be exactly width times + height times channels times 4.
  • The byte array's endian property must be Endian.LITTLE_ENDIAN.
+ +

If a Vector.<Number> instance is assigned to the input property, the + length of the Vector must be equal to width times height times + channels.

+ +
width + The width of the shader input.int + The width of the shader input. This property is only used when the input data + is a ByteArray or Vector.<Number> instance. When the input is a BitmapData + instance the width is automatically determined. + +
ColorCorrection +The ColorCorrection class provides values for the flash.display.Stage.colorCorrection property.Object +The ColorCorrection class provides values for the flash.display.Stage.colorCorrection property. + +flash.display.Stage.colorCorrectionDEFAULT +Uses the host's default color correction.defaultString +Uses the host's default color correction. For the web player the host is usually a browser, and Flash Player +tries to use the same color correction as the web page hosting the SWF file. + +OFF +Turns off color correction regardless of the player host environment.offString +Turns off color correction regardless of the player host environment. +This setting provides faster performance. + +ON +Turns on color correction regardless of the player host environment, if available.onString +Turns on color correction regardless of the player host environment, if available. + +Shader + A Shader instance represents a Pixel Bender shader kernel in ActionScript.Object + A Shader instance represents a Pixel Bender shader kernel in ActionScript. To use + a shader in your application, you create a Shader instance for it. You + then use that Shader instance in the appropriate way according to the effect + you want to create. For example, to use the shader as a filter, you + assign the Shader instance to the shader property of a + ShaderFilter object. + +

A shader defines a function that executes on all the pixels in an image, + one pixel at a time. The result of each call to the function is the output + color at that pixel coordinate in the image. A shader can specify one or more + input images, which are images whose content can be used in determining the + output of the function. A shader can also specify one or more parameters, + which are input values that can be used in calculating the function output. In + a single shader execution, the input and parameter values are constant. The only + thing that varies is the coordinate of the pixel whose color is the function result. + Shader function calls for multiple output + pixel coordinates execute in parallel to improve shader execution performance.

+ +

The shader bytecode can be loaded at run time using a URLLoader instance. + The following example demonstrates loading a shader bytecode file at run time + and linking it to a Shader instance.

+ + + var loader:URLLoader = new URLLoader(); + loader.dataFormat = URLLoaderDataFormat.BINARY; + loader.addEventListener(Event.COMPLETE, onLoadComplete); + loader.load(new URLRequest("myShader.pbj")); + + var shader:Shader; + + function onLoadComplete(event:Event):void { + // Create a new shader and set the loaded data as its bytecode + shader = new Shader(); + shader.byteCode = loader.data; + + // You can also pass the bytecode to the Shader() constructor like this: + // shader = new Shader(loader.data); + + // do something with the shader + } + + +

You can also embed the shader into the SWF at compile time using the + [Embed] metadata tag. The [Embed] metadata tag + is only available if you use the Flex SDK to compile the SWF. The + [Embed] tag's source parameter points to + the shader file, and its mimeType parameter is + "application/octet-stream", as in this example:

+ + + [Embed(source="myShader.pbj", mimeType="application/octet-stream)] + var MyShaderClass:Class; + + // ... + + // create a new shader and set the embedded shader as its bytecode + var shaderShader = new Shader(); + shader.byteCode = new MyShaderClass(); + + // You can also pass the bytecode to the Shader() constructor like this: + // var shader:Shader = new Shader(new MyShaderClass()); + + // do something with the shader + + +

In either case, you link the raw shader (the URLLoader.data property + or an instance of the [Embed] data class) to the Shader instance. As + the previous examples demonstrate, you can do this in two ways. You can + pass the shader bytecode as an argument + to the Shader() constructor. Alternatively, you can set it as the Shader + instance's byteCode property.

+ +

Once a Shader instance is created, it can be used in one of several + ways:

+ +
  • A shader fill: The output of the shader is used as a fill for + content drawn with the drawing API. Pass the Shader instance as + an argument to the Graphics.beginShaderFill() method.
  • A shader filter: The output of the shader is used as a graphic filter + applied to a display object. Assign the Shader instance to the + shader property of a ShaderFilter instance.
  • A blend mode: The output of the shader is rendered as the blending + between two overlapping display objects. Assign the Shader instance + to the blendShader property of the upper of the + two display objects.
  • Background shader processing: The shader executes in the background, + avoiding the possibility of freezing the display, and dispatches an + event when processing is complete. Assign the Shader instance to + the shader property of a ShaderJob instance.
+ +

Shader fills, filters, and blends are not supported under GPU rendering.

+

Mobile Browser Support: This feature is not supported in mobile browsers.

+

AIR profile support: This feature is supported + on all desktop operating systems, but it is not supported on all mobile devices. It is not supported on AIR + for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
The following example loads a shader bytecode file at run time and creates + a Shader instance linked to it. + +

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same + directory as the output directory for the application. The Pixel Bender source code for the DoNothing shader + is available in the ShaderData class example.

+ + +package { + import flash.display.Shader; + import flash.display.Sprite; + import flash.events.Event; + import flash.net.URLLoader; + import flash.net.URLLoaderDataFormat; + import flash.net.URLRequest; + + public class LoadedShaderExample extends Sprite { + + private var loader:URLLoader; + + public function LoadedShaderExample() { + loader = new URLLoader(); + loader.dataFormat = URLLoaderDataFormat.BINARY; + loader.addEventListener(Event.COMPLETE, loadCompleteHandler); + loader.load(new URLRequest("donothing.pbj")); + } + + private function loadCompleteHandler(event:Event):void { + var shader:Shader = new Shader(); + shader.byteCode = loader.data; + + // do something with the Shader instance + } + } +} +
The following example embeds a shader bytecode file by compiling it + into the SWF, and creates a Shader instance linked to it. + +

Note that this example assumes there's a shader bytecode file named "donothing.pbj" in the same + directory as the source code for the application, and that the Flex SDK is used to compile the SWF. + The Pixel Bender source code for the DoNothing shader + is available in the ShaderData class example.

+ + +package { + import flash.display.Shader; + import flash.display.Sprite; + + public class EmbeddedShaderExample extends Sprite { + + [Embed(source="donothing.pbj", mimeType="application/octet-stream")] + private static var DoNothingShader:Class; + + public function EmbeddedShaderExample() { + var shader:Shader = new Shader(); + shader.byteCode = new DoNothingShader(); + + // do something with the Shader instance + } + } +} +
flash.display.DisplayObject.blendShaderflash.display.Graphics.beginShaderFill()flash.display.ShaderJobflash.filters.ShaderFilterflash.net.URLLoaderShader + Creates a new Shader instance.codeflash.utils:ByteArraynullThe raw shader bytecode to link to the Shader. + + + Creates a new Shader instance. + + data + Provides access to parameters, input images, and metadata for the Shader instance.flash.display:ShaderData + Provides access to parameters, input images, and metadata for the Shader instance. + ShaderParameter objects representing parameters for the shader, ShaderInput objects + representing the input images for the shader, and other values representing the + shader's metadata are dynamically added as properties of the data + property object when the Shader instance is created. Those properties can be + used to introspect the shader and to set parameter and input values. + +

For information about accessing and manipulating the dynamic properties of + the data object, see the ShaderData class description.

+ +
flash.display.ShaderDataflash.display.ShaderInputflash.display.ShaderParameter
precisionHint + The precision of math operations performed by the shader.String + The precision of math operations performed by the shader. + +

The set of possible values for the precisionHint property is defined + by the constants in the ShaderPrecision class.

+ +

The default value is ShaderPrecision.FULL. Setting the precision + to ShaderPrecision.FAST can speed up math operations at the expense + of precision.

+ +

Full precision mode (ShaderPrecision.FULL) computes all math + operations to the full width of the IEEE 32-bit floating standard and provides + consistent behavior on all platforms. In this mode, some math operations such + as trigonometric and exponential functions can be slow.

+ +

Fast precision mode (ShaderPrecision.FAST) is designed for + maximum performance but does not work consistently on different platforms + and individual CPU configurations. In many cases, this level of precision + is sufficient to create graphic effects without visible artifacts.

+ +

The precision mode selection affects the following shader operations. + These operations are faster on an Intel processor + with the SSE instruction set:

+ +
  • sin(x)
  • cos(x)
  • tan(x)
  • asin(x)
  • acos(x)
  • atan(x)
  • atan(x, y)
  • exp(x)
  • exp2(x)
  • log(x)
  • log2(x)
  • pow(x, y)
  • reciprocal(x)
  • sqrt(x)
+ +
flash.display.ShaderPrecision
byteCode + The raw shader bytecode for this Shader instance.flash.utils:ByteArray + The raw shader bytecode for this Shader instance. + +
LineScaleMode +The LineScaleMode class provides values for the scaleMode +parameter in the Graphics.lineStyle() method.Object +The LineScaleMode class provides values for the scaleMode +parameter in the Graphics.lineStyle() method. + + +flash.display.Graphics.lineStyle()HORIZONTAL + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line scales only vertically.horizontalString + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line scales only vertically. For example, + consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.VERTICAL. The circle on the left + is scaled only vertically, and the circle on the right is scaled both vertically and horizontally. + +

+ +
NONE + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line never scales.noneString + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line never scales. + + NORMAL + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line always scales when the object is scaled (the default).normalString + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line always scales when the object is scaled (the default). + + VERTICAL + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line scales only horizontally.verticalString + With this setting used as the scaleMode parameter of the lineStyle() + method, the thickness of the line scales only horizontally. For example, + consider the following circles, drawn with a one-pixel line, and each with the + scaleMode parameter set to LineScaleMode.HORIZONTAL. The circle on the left + is scaled only horizontally, and the circle on the right is scaled both vertically and horizontally. + +

+ +
IGraphicsData + This interface is used to define objects that can be used as parameters in the flash.display.Graphics + methods, including fills, strokes, and paths. + This interface is used to define objects that can be used as parameters in the flash.display.Graphics + methods, including fills, strokes, and paths. Use the implementor classes of this interface to + create and manage drawing property data, and to reuse the same data for different instances. + Then, use the methods of the Graphics class to render the drawing + objects. + flash.display.Graphics.drawGraphicsData()MovieClip + The MovieClip class inherits from the following classes: Sprite, DisplayObjectContainer, + InteractiveObject, DisplayObject, and EventDispatcher.The basic display object for ActionScript created objects. + + + flash.display:Sprite + The MovieClip class inherits from the following classes: Sprite, DisplayObjectContainer, + InteractiveObject, DisplayObject, and EventDispatcher. + +

Unlike the Sprite object, a MovieClip object has a timeline.

+ +

>In Flash Professional, the methods for the MovieClip class provide the same functionality + as actions that target movie clips. Some additional methods do not have equivalent + actions in the Actions toolbox in the Actions panel in the Flash authoring tool.

+ +

Children instances placed on the Stage in Flash Professional cannot be accessed by code from within the + constructor of a parent instance since they have not been created at that point in code execution. + Before accessing the child, the parent must instead either create the child instance + by code or delay access to a callback function that listens for the child to dispatch + its Event.ADDED_TO_STAGE event.

+ +

If you modify any of the following properties of a MovieClip object that contains a motion tween, + the playhead is stopped in that MovieClip object: alpha, blendMode, + filters, height, opaqueBackground, rotation, + scaleX, scaleY, scale9Grid, scrollRect, + transform, visible, width, x, + or y. However, it does not stop the playhead in any child MovieClip objects of that + MovieClip object.

+

Note:Flash Lite 4 supports the MovieClip.opaqueBackground property only if + FEATURE_BITMAPCACHE is defined. The default configuration of Flash Lite 4 does not define + FEATURE_BITMAPCACHE. To enable the MovieClip.opaqueBackground property for a suitable device, + define FEATURE_BITMAPCACHE in your project.

+ +
The following example uses the MovieClipExample class to illustrate how + to monitor various properties of a MovieClip. This task is accomplished by performing the following steps: + +
  1. The constructor function defines a text field, which is used to display values of properties + of the MovieClipExample object (which extends MovieClip).
  2. The return value of the getPropertiesString() method is used as text for the + outputText text field. The getPropertiesString() method returns + a string that is populated with values of the following properties of the movie clip: + currentFrame, currentLabel, currentScene, + framesLoaded, totalFrames, and trackAsMenu.
  3. Two lines of code in the constructor function adjust the width and + height properties of the outputText text field.
  4. The last line of the constructor function adds the outputText text field + to the display list.
+ + +package { + import flash.display.MovieClip; + import flash.text.TextField; + + public class MovieClipExample extends MovieClip { + + public function MovieClipExample() { + var outputText:TextField = new TextField(); + outputText.text = getPropertiesString(); + outputText.width = stage.stageWidth; + outputText.height = outputText.textHeight; + addChild(outputText); + } + + private function getPropertiesString():String { + var str:String = "" + + "currentFrame: " + currentFrame + "\n" + + "currentLabel: " + currentLabel + "\n" + + "currentScene: " + currentScene + "\n" + + "framesLoaded: " + framesLoaded + "\n" + + "totalFrames: " + totalFrames + "\n" + + "trackAsMenu: " + trackAsMenu + "\n"; + return str; + } + } +} +
MovieClip + Creates a new MovieClip instance. + Creates a new MovieClip instance. After creating the MovieClip, call the + addChild() or addChildAt() method of a + display object container that is onstage. + + gotoAndPlay + Starts playing the SWF file at the specified frame.frameObjectA number representing the frame number, or a string representing the label of the + frame, to which the playhead is sent. If you specify a number, it is relative to the + scene you specify. If you do not specify a scene, the current scene determines the global frame number to play. If you do specify a scene, the playhead + jumps to the frame number in the specified scene. + + sceneStringnullThe name of the scene to play. This parameter is optional. + + + Starts playing the SWF file at the specified frame. This happens after all + remaining actions in the frame have finished executing. To specify a scene + as well as a frame, specify a value for the scene parameter. + + The following code uses the gotoAndPlay() method to direct the playhead of + the mc1 movie clip to advance five frames ahead of its current location: + +mc1.gotoAndPlay(mc1.currentFrame + 5); + The following code uses the gotoAndPlay() method to direct the playhead of + the mc1 movie clip to the frame labeled "intro" in the scene named + "Scene 12": + +mc1.gotoAndPlay("intro", "Scene 12"); +gotoAndStop + Brings the playhead to the specified frame of the movie clip and stops it there.If the scene or frame specified are + not found in this movie clip. + + ArgumentErrorArgumentErrorframeObjectA number representing the frame number, or a string representing the label of the + frame, to which the playhead is sent. If you specify a number, it is relative to the + scene you specify. If you do not specify a scene, the current scene determines the global frame number at which to go to and stop. If you do specify a scene, + the playhead goes to the frame number in the specified scene and stops. + + sceneStringnullThe name of the scene. This parameter is optional. + + + Brings the playhead to the specified frame of the movie clip and stops it there. This happens after all + remaining actions in the frame have finished executing. If you want to specify a scene in addition to a frame, + specify a scene parameter. + + The following code uses the gotoAndStop() method and the + currentFrame property to direct the playhead of the mc1 movie clip to + advance five frames ahead of its current location and stop: + +mc1.gotoAndStop(mc1.currentFrame + 5); + The following code uses the gotoAndStop() to direct the playhead of + the mc1 movie clip to the frame labeled "finale" in the scene named + "Scene 12" and stop the playhead: + +mc1.gotoAndStop("finale", "Scene 12"); +nextFrame + Sends the playhead to the next frame and stops it. + Sends the playhead to the next frame and stops it. This happens after all + remaining actions in the frame have finished executing. + + In the following example, two SimpleButton objects control the timeline. The prev + button moves the playhead to the previous frame, and the nextBtn button moves the playhead + to the next frame: + + +import flash.events.MouseEvent; + +mc1.stop(); +prevBtn.addEventListener(MouseEvent.CLICK, goBack); +nextBtn.addEventListener(MouseEvent.CLICK, goForward); + +function goBack(event:MouseEvent):void { + mc1.prevFrame(); +} + +function goForward(event:MouseEvent):void { + mc1.nextFrame(); +} +prevFrame()nextScene + Moves the playhead to the next scene of the MovieClip instance. + Moves the playhead to the next scene of the MovieClip instance. This happens after all + remaining actions in the frame have finished executing. + + In the following example, two SimpleButton objects control the timeline. The prevBtn + button moves the playhead to the previous scene, and the nextBtn button moves the playhead + to the next scene: + + +import flash.events.MouseEvent; + +mc1.stop(); +prevBtn.addEventListener(MouseEvent.CLICK, goBack); +nextBtn.addEventListener(MouseEvent.CLICK, goForward); + +function goBack(event:MouseEvent):void { + mc1.prevScene(); +} + +function goForward(event:MouseEvent):void { + mc1.nextScene(); +} +play + Moves the playhead in the timeline of the movie clip. + Moves the playhead in the timeline of the movie clip. + + The following code uses the stop() method to stop a movie clip + named mc1 and to resume playing when the user clicks the text field named + continueText: + + +import flash.text.TextField; +import flash.events.MouseEvent; + +var continueText:TextField = new TextField(); +continueText.text = "Play movie..."; +addChild(continueText); + +mc1.stop(); +continueText.addEventListener(MouseEvent.CLICK, resumeMovie); + +function resumeMovie(event:MouseEvent):void { + mc1.play(); +} +gotoAndPlay()prevFrame + Sends the playhead to the previous frame and stops it. + Sends the playhead to the previous frame and stops it. This happens after all + remaining actions in the frame have finished executing. + + In the following example, two SimpleButton objects control the timeline. The prev + button moves the playhead to the previous frame, and the nextBtn button moves the playhead + to the next frame: + + +import flash.events.MouseEvent; + +mc1.stop(); +prevBtn.addEventListener(MouseEvent.CLICK, goBack); +nextBtn.addEventListener(MouseEvent.CLICK, goForward); + +function goBack(event:MouseEvent):void { + mc1.prevFrame(); +} + +function goForward(event:MouseEvent):void { + mc1.nextFrame(); +} +prevScene + Moves the playhead to the previous scene of the MovieClip instance. + Moves the playhead to the previous scene of the MovieClip instance. This happens after all + remaining actions in the frame have finished executing. + + In the following example, two SimpleButton objects control the timeline. The prevBtn + button moves the playhead to the previous scene, and the nextBtn button moves the playhead + to the next scene: + + +import flash.events.MouseEvent; + +mc1.stop(); +prevBtn.addEventListener(MouseEvent.CLICK, goBack); +nextBtn.addEventListener(MouseEvent.CLICK, goForward); + +function goBack(event:MouseEvent):void { + mc1.prevScene(); +} + +function goForward(event:MouseEvent):void { + mc1.nextScene(); +} +stop + Stops the playhead in the movie clip. + Stops the playhead in the movie clip. + + currentFrameLabel + The label at the current frame in the timeline of the MovieClip instance.String + The label at the current frame in the timeline of the MovieClip instance. + If the current frame has no label, currentLabel is null. + + currentFrame + Specifies the number of the frame in which the playhead is located in the timeline of + the MovieClip instance.int + Specifies the number of the frame in which the playhead is located in the timeline of + the MovieClip instance. If the movie clip has multiple scenes, this value is the + frame number in the current scene. + + The following code uses the gotoAndStop() method and the + currentFrame property to direct the playhead of the mc1 movie clip to + advance five frames ahead of its current location and stop: + +mc1.gotoAndStop(mc1.currentFrame + 5); +currentLabel + The current label in which the playhead is located in the timeline of the MovieClip instance.String + The current label in which the playhead is located in the timeline of the MovieClip instance. + If the current frame has no label, currentLabel is set to the name of the previous frame + that includes a label. If the current frame and previous frames do not include a label, + currentLabel returns null. + + The following code illustrates how to access the currentLabel + property of a MovieClip object named mc1: + +trace(mc1.currentLabel); +currentLabels + Returns an array of FrameLabel objects from the current scene.Array + Returns an array of FrameLabel objects from the current scene. If the MovieClip instance does + not use scenes, the array includes all frame labels from the entire MovieClip instance. + + The following code illustrates how to use the currentLabels + property of a MovieClip object named mc1: + +import flash.display.FrameLabel; + +var labels:Array = mc1.currentLabels; + +for (var i:uint = 0; i < labels.length; i++) { + var label:FrameLabel = labels[i]; + trace("frame " + label.frame + ": " + label.name); +} +flash.display.FrameLabelcurrentScene + The current scene in which the playhead is located in the timeline of the MovieClip instance.flash.display:Scene + The current scene in which the playhead is located in the timeline of the MovieClip instance. + + The following code illustrates how to use the currentScene + property of a MovieClip object named mc1: + +import flash.display.Scene; + +var scene:Scene = mc1.currentScene; +trace(scene.name + ": " + scene.numFrames + " frames"); +Sceneenabled + A Boolean value that indicates whether a movie clip is enabled.Boolean + A Boolean value that indicates whether a movie clip is enabled. The default value of enabled + is true. If enabled is set to false, the movie clip's + Over, Down, and Up frames are disabled. The movie clip + continues to receive events (for example, mouseDown, + mouseUp, keyDown, and keyUp). + +

The enabled property governs only the button-like properties of a movie clip. You + can change the enabled property at any time; the modified movie clip is immediately + enabled or disabled. If enabled is set to false, the object is not + included in automatic tab ordering.

+ +
The following code illustrates how to use the enabled property + to disable the button-like properties of a MovieClip object named mc1: + +mc1.enabled = false; +
framesLoaded + The number of frames that are loaded from a streaming SWF file.int + The number of frames that are loaded from a streaming SWF file. You can use the framesLoaded + property to determine whether the contents of a specific frame and all the frames before it + loaded and are available locally in the browser. You can also use it to monitor the downloading + of large SWF files. For example, you might want to display a message to users indicating that + the SWF file is loading until a specified frame in the SWF file finishes loading. + +

If the movie clip contains multiple scenes, the framesLoaded property returns the number + of frames loaded for all scenes in the movie clip.

+ +
The following code illustrates how to use the framesLoaded + property and the totalFrames property to determine if a streaming MovieClip + object named mc1 is fully loaded: + +if (mc1.framesLoaded == mc1.totalFrames) { + trace("OK."); +} +
Loader class
scenes + An array of Scene objects, each listing the name, the number of frames, + and the frame labels for a scene in the MovieClip instance.Array + An array of Scene objects, each listing the name, the number of frames, + and the frame labels for a scene in the MovieClip instance. + + The following code illustrates how to use the scenes + property of a MovieClip object named mc1: + +import flash.display.Scene; + +for (var i:uint = 0; i < mc1.scenes.length; i++) { + var scene:Scene = mc1.scenes[i]; + trace("scene " + scene.name + ": " + scene.numFrames + " frames"); +} +ScenetotalFrames + The total number of frames in the MovieClip instance.int + The total number of frames in the MovieClip instance. + +

If the movie clip contains multiple frames, the totalFrames property returns + the total number of frames in all scenes in the movie clip.

+ +
The following code illustrates the use of the totalFrames + property of a MovieClip object named mc1: + + trace(mc1.totalFrames); +
trackAsMenu + Indicates whether other display objects that are SimpleButton or MovieClip objects can receive + mouse release events or other user input release events.Boolean + Indicates whether other display objects that are SimpleButton or MovieClip objects can receive + mouse release events or other user input release events. The trackAsMenu property lets you create menus. You + can set the trackAsMenu property on any SimpleButton or MovieClip object. + The default value of the trackAsMenu property is false. + +

You can change the trackAsMenu property at any time; the modified movie + clip immediately uses the new behavior.

+ +
The following code illustrates how to use the trackAsMenu + property to enable mouse release events for a MovieClip object named mc1: + + mc1.trackAsMenu = true; +
SWFVersion + The SWFVersion class is an enumeration of constant values that indicate the + file format version of a loaded SWF file.Object + The SWFVersion class is an enumeration of constant values that indicate the + file format version of a loaded SWF file. + + The SWFVersion constants are provided for use in checking the + swfVersion property of a flash.display.LoaderInfo object. + + flash.display.LoaderInfo.swfVersionFLASH10 + SWF file format version 10.0.10uint + SWF file format version 10.0. + + FLASH11 + SWF file format version 11.0.11uint + SWF file format version 11.0. + + FLASH1 + SWF file format version 1.0.1uint + SWF file format version 1.0. + + FLASH2 + SWF file format version 2.0.2uint + SWF file format version 2.0. + + FLASH3 + SWF file format version 3.0.3uint + SWF file format version 3.0. + + FLASH4 + SWF file format version 4.0.4uint + SWF file format version 4.0. + + FLASH5 + SWF file format version 5.0.5uint + SWF file format version 5.0. + + FLASH6 + SWF file format version 6.0.6uint + SWF file format version 6.0. + + FLASH7 + SWF file format version 7.0.7uint + SWF file format version 7.0. + + FLASH8 + SWF file format version 8.0.8uint + SWF file format version 8.0. + + FLASH9 + SWF file format version 9.0.9uint + SWF file format version 9.0. + + NativeWindowResize +The NativeWindowResize class defines constants for the possible values + of the edgeOrCorner parameter of the NativeWindow + startResize() method.Defines constants used when resizing a window in response to a user action. + +Object +The NativeWindowResize class defines constants for the possible values + of the edgeOrCorner parameter of the NativeWindow + startResize() method. +

A constant is defined to name each edge and corner of a window.

+ +
flash.display.NativeWindow.startResize()BOTTOM_LEFT +The bottom-left corner of the window.BLString +The bottom-left corner of the window. + +BOTTOM_RIGHT +The bottom-right corner of the window.BRString +The bottom-right corner of the window. + +BOTTOM +The bottom edge of the window.BString +The bottom edge of the window. + +LEFT +The left edge of the window.LString +The left edge of the window. + +NONE +Used for keyboard resizing on systems (such as Windows) that support keyboard resizing.String +Used for keyboard resizing on systems (such as Windows) that support keyboard resizing. +On Windows, this is similar to choosing the Size command from the Alt+Space menu. +When calling NativeWindow.startResize(NativeWindowResize.NONE), +a Windows user can resize the window using the keyboard arrow keys. + +RIGHT +The right edge of the window.RString +The right edge of the window. + +TOP_LEFT +The top-left corner of the window.TLString +The top-left corner of the window. + +TOP_RIGHT +The top-right corner of the window.TRString +The top-right corner of the window. + +TOP +The top edge of the window.TString +The top edge of the window. + +
BitmapDataChannel +The BitmapDataChannel class is an enumeration of constant values that indicate which channel to +use: red, blue, green, or alpha transparency.Object +The BitmapDataChannel class is an enumeration of constant values that indicate which channel to +use: red, blue, green, or alpha transparency. + +

When you call some methods, you can use the bitwise OR operator (|) +to combine BitmapDataChannel constants to indicate multiple color channels.

+ +

The BitmapDataChannel constants are provided for use as values in the following:

+ +
  • The sourceChannel and destChannel parameters of the + flash.display.BitmapData.copyChannel() method
  • The channelOptions parameter of the + flash.display.BitmapData.noise() method
  • The flash.filters.DisplacementMapFilter.componentX and + flash.filters.DisplacementMapFilter.componentY properties
+ +
flash.display.BitmapData.copyChannel()flash.display.BitmapData.noise()flash.filters.DisplacementMapFilter.componentXflash.filters.DisplacementMapFilter.componentYALPHA + The alpha channel.8uint + The alpha channel. + + BLUE + The blue channel.4uint + The blue channel. + + GREEN + The green channel.2uint + The green channel. + + RED + The red channel.1uint + The red channel. + +
GraphicsSolidFill + Defines a solid fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject + Defines a solid fill. + +

+ Use a GraphicsSolidFill object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsSolidFill object is the equivalent of calling the Graphics.beginFill() method. +

+ +
flash.display.Graphics.beginFill()flash.display.Graphics.drawGraphicsData()GraphicsSolidFill + Creates a new GraphicsSolidFill object.coloruint0The color value. Valid values are in the hexadecimal format 0xRRGGBB. + alphaNumber1.0The alpha transparency value. Valid values are 0 (fully transparent) to 1 (fully opaque). + + + Creates a new GraphicsSolidFill object. + + alpha + Indicates the alpha transparency value of the fill.1.0Number + Indicates the alpha transparency value of the fill. Valid values are 0 (fully transparent) to 1 (fully opaque). + The default value is 1. Display objects with alpha set to 0 are active, even though they are invisible. + + + color + The color of the fill.0uint + The color of the fill. Valid values are in the hexadecimal format 0xRRGGBB. The default value is 0xFF0000 (or the uint 0). + + +
IBitmapDrawable + The IBitmapDrawable interface is implemented by objects that can be passed as the source + parameter of the draw() method of the BitmapData class. + The IBitmapDrawable interface is implemented by objects that can be passed as the source + parameter of the draw() method of the BitmapData class. These objects are of type BitmapData + or DisplayObject. + + flash.display.BitmapData.draw()flash.display.BitmapDataflash.display.DisplayObjectCapsStyle + The CapsStyle class is an enumeration of constant values that specify the caps style to use in drawing lines.Object + The CapsStyle class is an enumeration of constant values that specify the caps style to use in drawing lines. + The constants are provided for use as values in the caps parameter of the + flash.display.Graphics.lineStyle() method. You can specify the following three types of caps: + +

+ +
The following example uses the CapsStyleExample class to draw three + parallel lines, each with a different line cap style. +
  1. The properties of each line are set as follows: +
    • The line length is set to 80 pixels.
    • The border color is set to orange.
    • The border size is set to 30 pixels.
    • The highlight color is set to gray.
    • The highlight size is set to 0 pixels.
    • The alpha is set to 1, making it solid.
    • The pixel hinting is set to false (strokes not hinted to full pixels).
    • The line scale mode is set to normal, which scales the thickness.
    • The joint style of the border caps are set to MITER.
    • The miter limit is set to 1, indicating that the miter is cut off close to the line.
  2. The class constructor creates three vertical lines, starting at x = 0, y = 0 by calling + the drawLine() method three times using the three different line cap styles (none, + round, and square). Each of the three calls to the drawLine() method uses the cap style and + properties listed previously to draw a vertical line and associated line highlight. The calls + first create a new child Shape object and then use methods of the Graphics + class to set the line style and draw the lines and highlights. Each instance of child + is added to the display list and drawn on the stage.
  3. The connected line segments are redrawn by using the refreshLayout() method at y = 80 + pixels and starting at x = 80 pixels, with a 25-pixel separation between the line segments.
+ +package { + import flash.display.CapsStyle; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.JointStyle; + import flash.display.LineScaleMode; + import flash.display.Shape; + import flash.display.Sprite; + + public class CapsStyleExample extends Sprite { + private var lineLength:uint = 80; + private var borderColor:uint = 0xFFCC00; + private var borderSize:uint = 30; + private var highlightColor:uint = 0x666666; + private var highlightSize:uint = 0; + private var gutter:uint = 25; + private var borderAlpha:uint = 1; + private var borderPixelHinting:Boolean = false; + private var borderScaleMode:String = LineScaleMode.NORMAL; + private var borderJointStyle:String = JointStyle.MITER; + private var borderMiterLimit:uint = 1; + + public function CapsStyleExample() { + drawLine(CapsStyle.NONE); + drawLine(CapsStyle.ROUND); + drawLine(CapsStyle.SQUARE); + refreshLayout(); + } + + private function drawLine(capsStyle:String):void { + var child:Shape = new Shape(); + child.graphics.lineStyle(borderSize, + borderColor, + borderAlpha, + borderPixelHinting, + borderScaleMode, + capsStyle, + borderJointStyle, + borderMiterLimit); + child.graphics.lineTo(0, 0); + child.graphics.lineTo(0, lineLength); + child.graphics.endFill(); + + child.graphics.moveTo(0, 0); + child.graphics.lineStyle(highlightSize, highlightColor); + child.graphics.lineTo(0, 0); + child.graphics.lineTo(0, lineLength); + + addChild(child); + } + + private function refreshLayout():void { + var ln:uint = numChildren; + var child:DisplayObject; + var lastChild:DisplayObject = getChildAt(0); + lastChild.x = lineLength; + lastChild.y = lineLength; + for (var i:uint = 1; i < ln; i++) { + child = getChildAt(i); + child.x = gutter + lastChild.x + lastChild.width; + child.y = lineLength; + lastChild = child; + } + } + } +} +
flash.display.Graphics.lineStyle()NONE + + Used to specify no caps in the caps parameter of the + flash.display.Graphics.lineStyle() method.noneString + + Used to specify no caps in the caps parameter of the + flash.display.Graphics.lineStyle() method. + + ROUND + + Used to specify round caps in the caps parameter of the + flash.display.Graphics.lineStyle() method.roundString + + Used to specify round caps in the caps parameter of the + flash.display.Graphics.lineStyle() method. + + SQUARE + + Used to specify square caps in the caps parameter of the + flash.display.Graphics.lineStyle() method.squareString + + Used to specify square caps in the caps parameter of the + flash.display.Graphics.lineStyle() method. + +
StageScaleMode +The StageScaleMode class provides values for the Stage.scaleMode property.Object +The StageScaleMode class provides values for the Stage.scaleMode property. + +flash.display.Stage.scaleModeEXACT_FIT +Specifies that the entire application be visible in the specified area without trying to preserve +the original aspect ratio.exactFitString +Specifies that the entire application be visible in the specified area without trying to preserve +the original aspect ratio. Distortion can occur. +NO_BORDER +Specifies that the entire application fill the specified area, without distortion but possibly with +some cropping, while maintaining the original aspect ratio of the application.noBorderString +Specifies that the entire application fill the specified area, without distortion but possibly with +some cropping, while maintaining the original aspect ratio of the application. +NO_SCALE +Specifies that the size of the application be fixed, so that it remains unchanged even as the size +of the player window changes.noScaleString +Specifies that the size of the application be fixed, so that it remains unchanged even as the size +of the player window changes. Cropping might occur if the player window is smaller than the content. +SHOW_ALL +Specifies that the entire application be visible in the specified area without distortion while +maintaining the original aspect ratio of the application.showAllString +Specifies that the entire application be visible in the specified area without distortion while +maintaining the original aspect ratio of the application. Borders can appear on two sides of the application. + +SpreadMethod +The SpreadMethod class provides values for the spreadMethod parameter +in the beginGradientFill() and lineGradientStyle() methods of the Graphics class.Object +The SpreadMethod class provides values for the spreadMethod parameter +in the beginGradientFill() and lineGradientStyle() methods of the Graphics class. + +

The following example shows the same gradient fill using various spread methods:

+ +SpreadMethod.PADSpreadMethod.REFLECTSpreadMethod.REPEAT + + +
flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()PAD +Specifies that the gradient use the pad spread method.padString +Specifies that the gradient use the pad spread method. +REFLECT +Specifies that the gradient use the reflect spread method.reflectString +Specifies that the gradient use the reflect spread method. +REPEAT +Specifies that the gradient use the repeat spread method.repeatString +Specifies that the gradient use the repeat spread method. +
FocusDirection + The FocusDirection class enumerates values to be used for the + direction parameter of the assignFocus() method + of a Stage object and for the direction property of a FocusEvent object.Object + The FocusDirection class enumerates values to be used for the + direction parameter of the assignFocus() method + of a Stage object and for the direction property of a FocusEvent object. + + flash.events.FocusEvent.directionflash.display.Stage.assignFocus()BOTTOM + Indicates that focus should be given to the object at the end of the reading order.bottomString + Indicates that focus should be given to the object at the end of the reading order. + + NONE + Indicates that focus object within the interactive object should not change.noneString + Indicates that focus object within the interactive object should not change. + + TOP + Indicates that focus should be given to the object at the beginning of the reading order.topString + Indicates that focus should be given to the object at the beginning of the reading order. + + StageAlign +The StageAlign class provides constant values to use for the Stage.align property.Object +The StageAlign class provides constant values to use for the Stage.align property. + +flash.display.Stage.alignBOTTOM_LEFT +Specifies that the Stage is aligned in the bottom-left corner.BLString +Specifies that the Stage is aligned in the bottom-left corner. +BOTTOM_RIGHT +Specifies that the Stage is aligned in the bottom-right corner.BRString +Specifies that the Stage is aligned in the bottom-right corner. +BOTTOM +Specifies that the Stage is aligned at the bottom.BString +Specifies that the Stage is aligned at the bottom. +LEFT +Specifies that the Stage is aligned on the left.LString +Specifies that the Stage is aligned on the left. +RIGHT +Specifies that the Stage is aligned to the right.RString +Specifies that the Stage is aligned to the right. +TOP_LEFT +Specifies that the Stage is aligned in the top-left corner.TLString +Specifies that the Stage is aligned in the top-left corner. +TOP_RIGHT +Specifies that the Stage is aligned in the top-right corner.TRString +Specifies that the Stage is aligned in the top-right corner. +TOP +Specifies that the Stage is aligned at the top.TString +Specifies that the Stage is aligned at the top. +ColorCorrectionSupport +The ColorCorrectionSupport class provides values for the flash.display.Stage.colorCorrectionSupport property.Object +The ColorCorrectionSupport class provides values for the flash.display.Stage.colorCorrectionSupport property. + +flash.display.Stage.colorCorrectionSupportDEFAULT_OFF +Color correction is supported, but off by default.defaultOffString +Color correction is supported, but off by default. + +DEFAULT_ON +Color correction is supported, and on by default.defaultOnString +Color correction is supported, and on by default. + +UNSUPPORTED +Color correction is not supported by the host environment.unsupportedString +Color correction is not supported by the host environment. + +GraphicsShaderFill + Defines a shader fill.flash.display:IGraphicsFillflash.display:IGraphicsDataObject + Defines a shader fill. + +

+ Use a GraphicsShaderFill object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsShaderFill object is the equivalent of calling the Graphics.beginShaderFill() method. +

+ +
flash.display.Graphics.beginShaderFill()flash.display.Graphics.drawGraphicsData()GraphicsShaderFill + Creates a new GraphicsShaderFill object.shaderflash.display:ShadernullThe shader to use for the fill. This Shader instance is not required to + specify an image input. However, if an image input is specified in the shader, the input + must be provided manually by setting the input property of the corresponding ShaderInput + property of the Shader.data property. + + matrixflash.geom:MatrixnullA matrix object (of the flash.geom.Matrix class), which you can use to + define transformations on the shader. + + + Creates a new GraphicsShaderFill object. + + flash.geom.Matrixflash.display.Shadermatrix + A matrix object (of the flash.geom.Matrix class), which you can use to + define transformations on the shader.flash.geom:Matrix + A matrix object (of the flash.geom.Matrix class), which you can use to + define transformations on the shader. For example, you can use the following matrix + to rotate a shader by 45 degrees (pi/4 radians): + + + matrix = new flash.geom.Matrix(); + matrix.rotate(Math.PI / 4); + + +

The coordinates received in the shader are based on the matrix that is specified + for the matrix parameter. For a default (null) matrix, the + coordinates in the shader are local pixel coordinates which can be used to sample an + input.

+ +
flash.geom.Matrix
shader + The shader to use for the fill.flash.display:Shader + The shader to use for the fill. This Shader instance is not required to + specify an image input. However, if an image input is specified in the shader, the input + must be provided manually by setting the input property of the corresponding ShaderInput + property of the Shader.data property. + +

When you pass a Shader instance as an argument the shader is copied internally and the + drawing fill operation uses that internal copy, not a reference to the original shader. Any changes + made to the shader, such as changing a parameter value, input, or bytecode, are not applied + to the copied shader that's used for the fill.

+ +
flash.display.Shader
Shape + This class is used to create lightweight shapes using the ActionScript drawing application program interface (API).A display object used for shapes. + + flash.display:DisplayObject + This class is used to create lightweight shapes using the ActionScript drawing application program interface (API). + The Shape class includes a graphics property, which lets you access methods from the Graphics class. + +

The Sprite class also includes a graphicsproperty, and it includes other features not available to the + Shape class. For example, a Sprite object is a display object container, whereas a Shape object is not (and cannot contain + child display objects). For this reason, Shape objects consume less memory than Sprite objects that contain the + same graphics. However, a Sprite object supports user input events, while a Shape object does not.

+ +
The following example uses the ShapeExample class to draw a circle, + a rounded rectangle, and a square. This task is accomplished by performing the following steps: + +
  1. Declare a size property for later use in determining the size of each shape.
  2. Declare properties that set the background color to orange, the border color to + dark gray, the border size to 0 pixels, the corner radius to 9 pixels, and set the space + between the stage edge and the other objects to be 5 pixels.
  3. Use the properties declared in the preceding steps along with the built-in methods of the + Graphics class to draw the circle, rounded rectangle, and square at coordinates x = 0, y = 0.
  4. Redraw each of the shapes along the top of the stage, starting at x = 5, y = 5, with + a 5-pixel spacing between shapes by using the refreshLayout() method.
+ + +package { + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.JointStyle; + import flash.display.LineScaleMode; + import flash.display.Shape; + import flash.display.Sprite; + + public class ShapeExample extends Sprite { + private var size:uint = 80; + private var bgColor:uint = 0xFFCC00; + private var borderColor:uint = 0x666666; + private var borderSize:uint = 0; + private var cornerRadius:uint = 9; + private var gutter:uint = 5; + + public function ShapeExample() { + doDrawCircle(); + doDrawRoundRect(); + doDrawRect(); + refreshLayout(); + } + + private function refreshLayout():void { + var ln:uint = numChildren; + var child:DisplayObject; + var lastChild:DisplayObject = getChildAt(0); + lastChild.x = gutter; + lastChild.y = gutter; + for (var i:uint = 1; i < ln; i++) { + child = getChildAt(i); + child.x = gutter + lastChild.x + lastChild.width; + child.y = gutter; + lastChild = child; + } + } + + private function doDrawCircle():void { + var child:Shape = new Shape(); + var halfSize:uint = Math.round(size/2); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawCircle(halfSize, halfSize, halfSize); + child.graphics.endFill(); + addChild(child); + } + + private function doDrawRoundRect():void { + var child:Shape = new Shape(); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawRoundRect(0, 0, size, size, cornerRadius); + child.graphics.endFill(); + addChild(child); + } + + private function doDrawRect():void { + var child:Shape = new Shape(); + child.graphics.beginFill(bgColor); + child.graphics.lineStyle(borderSize, borderColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + addChild(child); + } + } +} +
flash.display.Graphicsflash.display.SpriteShape + Creates a new Shape object. + Creates a new Shape object. + + graphics + Specifies the Graphics object belonging to this Shape object, where vector + drawing commands can occur.flash.display:GraphicsSpecifies the Graphics object for the Shape object. + + + Specifies the Graphics object belonging to this Shape object, where vector + drawing commands can occur. + +
ShaderParameterType + This class defines the constants that represent the possible values for + the ShaderParameter class's type property.Object + This class defines the constants that represent the possible values for + the ShaderParameter class's type property. Each constant + represents one of the data types available in Flash Player for + parameters in the Pixel Bender shader language. + + flash.display.ShaderParameter.typeBOOL2 + Indicates that the shader parameter is defined as a + bool2 value, equivalent to an Array of two Boolean instances + in ActionScript.bool2String + Indicates that the shader parameter is defined as a + bool2 value, equivalent to an Array of two Boolean instances + in ActionScript. + + BOOL3 + Indicates that the shader parameter is defined as a + bool3 value, equivalent to an Array of three Boolean instances + in ActionScript.bool3String + Indicates that the shader parameter is defined as a + bool3 value, equivalent to an Array of three Boolean instances + in ActionScript. + + BOOL4 + Indicates that the shader parameter is defined as a + bool4 value, equivalent to an Array of four Boolean instances + in ActionScript.bool4String + Indicates that the shader parameter is defined as a + bool4 value, equivalent to an Array of four Boolean instances + in ActionScript. + + BOOL + Indicates that the shader parameter is defined as a + bool value, equivalent to a single Boolean instance + in ActionScript.boolString + Indicates that the shader parameter is defined as a + bool value, equivalent to a single Boolean instance + in ActionScript. + +

Note that even though the parameter only expects a single value, + the ShaderParameter.value property is an Array, so the single value + must be the only element of an Array assigned to the + value property, like this:

+ + + // assumes the shader has a parameter named "param" + // whose data type is bool + myShader.data.param.value = [true]; + + +
FLOAT2 + Indicates that the shader parameter is defined as a + float2 value, equivalent to an Array of two Number instances + in ActionScript.float2String + Indicates that the shader parameter is defined as a + float2 value, equivalent to an Array of two Number instances + in ActionScript. + + flash.display.ShaderParameter.typeFLOAT3 + Indicates that the shader parameter is defined as a + float3 value, equivalent to an Array of three Number instances + in ActionScript.float3String + Indicates that the shader parameter is defined as a + float3 value, equivalent to an Array of three Number instances + in ActionScript. + + FLOAT4 + Indicates that the shader parameter is defined as a + float4 value, equivalent to an Array of four Number instances + in ActionScript.float4String + Indicates that the shader parameter is defined as a + float4 value, equivalent to an Array of four Number instances + in ActionScript. + + FLOAT + Indicates that the shader parameter is defined as a + float value, equivalent to a single Number instance + in ActionScript.floatString + Indicates that the shader parameter is defined as a + float value, equivalent to a single Number instance + in ActionScript. + +

Note that even though the parameter only expects a single value, + the ShaderParameter.value property is an Array, so the single value + must be the only element of an Array assigned to the + value property, like this:

+ + + // assumes the shader has a parameter named "param" + // whose data type is float + myShader.data.param.value = [22.5]; + + +
flash.display.ShaderParameter.type
INT2 + Indicates that the shader parameter is defined as an + int2 value, equivalent to an Array of two int or uint + instances in ActionScript.int2String + Indicates that the shader parameter is defined as an + int2 value, equivalent to an Array of two int or uint + instances in ActionScript. + + INT3 + Indicates that the shader parameter is defined as an + int3 value, equivalent to an Array of three int or uint + instances in ActionScript.int3String + Indicates that the shader parameter is defined as an + int3 value, equivalent to an Array of three int or uint + instances in ActionScript. + + INT4 + Indicates that the shader parameter is defined as an + int4 value, equivalent to an Array of four int or uint + instances in ActionScript.int4String + Indicates that the shader parameter is defined as an + int4 value, equivalent to an Array of four int or uint + instances in ActionScript. + + INT + Indicates that the shader parameter is defined as an + int value, equivalent to a single int or uint instance + in ActionScript.intString + Indicates that the shader parameter is defined as an + int value, equivalent to a single int or uint instance + in ActionScript. + +

Note that even though the parameter only expects a single value, + the ShaderParameter.value property is an Array, so the single value + must be the only element of an Array assigned to the + value property, like this:

+ + + // assumes the shader has a parameter named "param" + // whose data type is int + myShader.data.param.value = [275]; + + +
MATRIX2X2 + Indicates that the shader parameter is defined as a + float2x2 value, equivalent to a 2-by-2 matrix.matrix2x2String + Indicates that the shader parameter is defined as a + float2x2 value, equivalent to a 2-by-2 matrix. This matrix is represented as an + Array of four Number instances in ActionScript. + + MATRIX3X3 + Indicates that the shader parameter is defined as a + float3x3 value, equivalent to a 3-by-3 matrix.matrix3x3String + Indicates that the shader parameter is defined as a + float3x3 value, equivalent to a 3-by-3 matrix. This matrix is represented as an + Array of nine Number instances in ActionScript. + + MATRIX4X4 + Indicates that the shader parameter is defined as a + float4x4 value, equivalent to a 4-by-4 matrix.matrix4x4String + Indicates that the shader parameter is defined as a + float4x4 value, equivalent to a 4-by-4 matrix. This matrix is represented as an + Array of 16 Number instances in ActionScript. + +
GraphicsPathWinding +The GraphicsPathWinding class provides values for the flash.display.GraphicsPath.winding property +and the flash.display.Graphics.drawPath() method +to determine the direction to draw a path.Object +The GraphicsPathWinding class provides values for the flash.display.GraphicsPath.winding property +and the flash.display.Graphics.drawPath() method +to determine the direction to draw a path. +A clockwise path is positively wound, and +a counter-clockwise path is negatively wound: +

+

When paths intersect or overlap, the winding +direction determines the rules for filling the areas created by the intersection or overlap:

+

+ +
flash.display.GraphicsPath.windingflash.display.Graphics.drawPath()EVEN_ODD +Establishes the even-odd winding type.evenOddString +Establishes the even-odd winding type. The even-odd winding type is the rule used by all of the +original drawing API and is the default type for the flash.display.Graphics.drawPath() method. +Any overlapping paths will alternate between open and closed fills. If two squares drawn with the same fill +intersect, the area of the intersection is not filled. Adjacent areas are not the same (neither both filled nor both unfilled). + +NON_ZERO +Establishes the non-zero winding type.nonZeroString +Establishes the non-zero winding type. The non-zero winding type determines that +when paths of opposite winding intersect, the intersection area is unfilled (as with the even-odd winding type). +For paths of the same winding, the intersection area is filled. + +
ActionScriptVersion + The ActionScriptVersion class is an enumeration of constant values that + indicate the language version of a loaded SWF file.Object + The ActionScriptVersion class is an enumeration of constant values that + indicate the language version of a loaded SWF file. + + The language version constants are provided for use in checking the + actionScriptVersion property of a flash.display.LoaderInfo object. + + flash.display.LoaderInfo.actionScriptVersionACTIONSCRIPT2 + ActionScript language version 2.0 and earlier.2uint + ActionScript language version 2.0 and earlier. + + ACTIONSCRIPT3 + ActionScript language version 3.0.3uint + ActionScript language version 3.0. + + GraphicsPath + A collection of drawing commands and the coordinate parameters for those commands.flash.display:IGraphicsPathflash.display:IGraphicsDataObject + A collection of drawing commands and the coordinate parameters for those commands. +

+ Use a GraphicsPath object with the Graphics.drawGraphicsData() method. + Drawing a GraphicsPath object is the equivalent of calling the Graphics.drawPath() method. +

+

The GraphicsPath class also has its own set of methods (curveTo(), lineTo(), moveTo() + wideLineTo() and wideMoveTo()) similar to those in the Graphics class + for making adjustments to the GraphicsPath.commands and GraphicsPath.data vector arrays.

+ +
flash.display.Graphics.drawGraphicsData()flash.display.Graphics.drawPath()GraphicsPath + Creates a new GraphicsPath object.commandsnullA Vector of integers representing commands defined by the GraphicsPathCommand class. + datanullA Vector of Numbers where each pair of numbers is treated as a point (an x, y pair). + windingStringevenOddSpecifies the winding rule using a value defined in the GraphicsPathWinding class. + + + Creates a new GraphicsPath object. + + flash.display.GraphicsPathCommandflash.display.GraphicsPathWindingcurveTo + Adds a new "curveTo" command to the commands vector and + new coordinates to the data vector.controlXNumberA number that specifies the horizontal position of the control + point relative to the registration point of the parent display object. + controlYNumberA number that specifies the vertical position of the control + point relative to the registration point of the parent display object. + anchorXNumberA number that specifies the horizontal position of the next anchor + point relative to the registration point of the parent display object. + anchorYNumberA number that specifies the vertical position of the next anchor + point relative to the registration point of the parent display object. + + + + Adds a new "curveTo" command to the commands vector and + new coordinates to the data vector. + + flash.display.GraphicsPathCommand.CURVE_TOflash.display.Graphics.curveTo()lineTo + Adds a new "lineTo" command to the commands vector and + new coordinates to the data vector.xNumberThe x coordinate of the destination point for the line. + yNumberThe y coordinate of the destination point for the line. + + + Adds a new "lineTo" command to the commands vector and + new coordinates to the data vector. + + flash.display.GraphicsPathCommand.LINE_TOflash.display.Graphics.lineTo()moveTo + Adds a new "moveTo" command to the commands vector and + new coordinates to the data vector.xNumberThe x coordinate of the destination point. + yNumberThe y coordinate of the destination point. + + + Adds a new "moveTo" command to the commands vector and + new coordinates to the data vector. + + flash.display.GraphicsPathCommand.MOVE_TOflash.display.Graphics.moveTo()wideLineTo + Adds a new "wideLineTo" command to the commands vector and + new coordinates to the data vector.xNumberThe x-coordinate of the destination point for the line. + yNumberThe y-coordinate of the destination point for the line. + + + Adds a new "wideLineTo" command to the commands vector and + new coordinates to the data vector. + + flash.display.GraphicsPathCommand.WIDE_LINE_TOwideMoveTo + Adds a new "wideMoveTo" command to the commands vector and + new coordinates to the data vector.xNumberThe x-coordinate of the destination point. + yNumberThe y-coordinate of the destination point. + + + Adds a new "wideMoveTo" command to the commands vector and + new coordinates to the data vector. + + flash.display.GraphicsPathCommand.WIDE_MOVE_TOcommands + The Vector of drawing commands as integers representing the path. + The Vector of drawing commands as integers representing the path. Each command can be one of the values defined + by the GraphicsPathCommand class. + + flash.display.GraphicsPathCommanddata + The Vector of Numbers containing the parameters used with the drawing commands. + The Vector of Numbers containing the parameters used with the drawing commands. + winding + Specifies the winding rule using a value defined in the GraphicsPathWinding class.String + Specifies the winding rule using a value defined in the GraphicsPathWinding class. + + flash.display.GraphicsPathWinding
MorphShape + The MorphShape class represents MorphShape objects on the display list.flash.display:DisplayObject + The MorphShape class represents MorphShape objects on the display list. + You cannot create MorphShape objects directly in ActionScript; they are created when you create a shape tween + in the Flash authoring tool. + + PixelSnapping + +The PixelSnapping class is an enumeration of constant values for setting the pixel snapping options +by using the pixelSnapping property of a Bitmap object.Object + +The PixelSnapping class is an enumeration of constant values for setting the pixel snapping options +by using the pixelSnapping property of a Bitmap object. + + +flash.display.Bitmap.pixelSnappingALWAYS + A constant value used in the pixelSnapping property of a Bitmap object + to specify that the bitmap image is always snapped to the nearest + pixel, independent of any transformation.alwaysString + A constant value used in the pixelSnapping property of a Bitmap object + to specify that the bitmap image is always snapped to the nearest + pixel, independent of any transformation. + + AUTO + A constant value used in the pixelSnapping property of a Bitmap object + to specify that the bitmap image is snapped to the nearest pixel if it is drawn with no rotation + or skew and it is drawn at a scale factor of 99.9% to 100.1%.autoString + A constant value used in the pixelSnapping property of a Bitmap object + to specify that the bitmap image is snapped to the nearest pixel if it is drawn with no rotation + or skew and it is drawn at a scale factor of 99.9% to 100.1%. If these conditions are satisfied, + the image is drawn at 100% scale, snapped to the nearest pixel. Internally, this setting allows the image + to be drawn as fast as possible by using the vector renderer. + NEVER + A constant value used in the pixelSnapping property of a Bitmap object + to specify that no pixel snapping occurs.neverString + A constant value used in the pixelSnapping property of a Bitmap object + to specify that no pixel snapping occurs. + + GraphicsPathCommand + Defines the values to use for specifying path-drawing commands.Object + Defines the values to use for specifying path-drawing commands. + +

The values in this class are used by the Graphics.drawPath() method, + or stored in the commands vector of a GraphicsPath object.

+ +
flash.display.Graphics.drawPath()flash.display.GraphicsPath.commandsCURVE_TO + Specifies a drawing command that draws a curve from the current drawing position to the x- and y-coordinates + specified in the data vector, using a control point.3int + Specifies a drawing command that draws a curve from the current drawing position to the x- and y-coordinates + specified in the data vector, using a control point. + This command produces the same effect as the Graphics.lineTo() method, and + uses two points in the data vector control and anchor: (cx, cy, ax, ay ). + + flash.display.Graphics.curveTo()LINE_TO + Specifies a drawing command that draws a line from the current drawing position to the x- and y-coordinates + specified in the data vector.2int + Specifies a drawing command that draws a line from the current drawing position to the x- and y-coordinates + specified in the data vector. + This command produces the same effect as the Graphics.lineTo() method, and + uses one point in the data vector: (x,y). + + flash.display.Graphics.lineTo()MOVE_TO + Specifies a drawing command that moves the current drawing position to the x- and y-coordinates specified in the data vector.1int + Specifies a drawing command that moves the current drawing position to the x- and y-coordinates specified in the data vector. + This command produces the same effect as the Graphics.moveTo() method, and + uses one point in the data vector: (x,y). + + flash.display.Graphics.moveTo()NO_OP + Represents the default "do nothing" command.0int + Represents the default "do nothing" command. + WIDE_LINE_TO + Specifies a "line to" drawing command, but uses two sets of coordinates (four values) instead of one set.5int + Specifies a "line to" drawing command, but uses two sets of coordinates (four values) instead of one set. + This command allows you to switch between "line to" and "curve to" commands without changing the number of data values used per command. + This command uses two sets in the data vector: one dummy location and one (x,y) location. + +

The WIDE_LINE_TO and WIDE_MOVE_TO command variants consume the same number of parameters + as does the CURVE_TO command.

+ +
LINE_TOflash.display.Graphics.lineTo()
WIDE_MOVE_TO + Specifies a "move to" drawing command, but uses two sets of coordinates (four values) instead of one set.4int + Specifies a "move to" drawing command, but uses two sets of coordinates (four values) instead of one set. + This command allows you to switch between "move to" and "curve to" commands without changing the number of data values used per command. + This command uses two sets in the data vector: one dummy location and one (x,y) location. + +

The WIDE_LINE_TO and WIDE_MOVE_TO command variants consume the same number of parameters + as does the CURVE_TO command.

+ +
MOVE_TOflash.display.Graphics.moveTo()
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.errors.xml b/language-server/playerglobal_docs/flash.errors.xml new file mode 100644 index 0000000..864f042 --- /dev/null +++ b/language-server/playerglobal_docs/flash.errors.xml @@ -0,0 +1,527 @@ +flash.errorsScriptTimeoutError + + The ScriptTimeoutError exception is thrown when the script timeout interval is reached.Error + The ScriptTimeoutError exception is thrown when the script timeout interval is reached. + The script timeout interval is 15 seconds. There are two XML attributes + that you can add to the mx:Application tag: scriptTimeLimit + (the number of seconds until script timeout) and scriptRecursionLimit + (the depth of recursive calls permitted). + +

Two ScriptTimeoutError exceptions are thrown. The first exception you can catch and exit + cleanly. If there is no exception handler, the uncaught exception terminates execution. The + second exception is thrown but cannot be caught by user code; it goes to the uncaught + exception handler. It is uncatchable to prevent the player from hanging + indefinitely.

+ +
The following example uses the sample ScriptTimeoutErrorExample class to show + the error generated in the event of script timeout. This is accomplished with the following + steps: +
  1. A keepLooking Boolean property is declared.
  2. The constructor calls the lockMachine() method within an error handling code + segment that catches ScriptTimeoutError objects.
  3. The lockMachine() method contains an endless while loop.
  4. After awhile, the ScriptTimeoutError is thrown. The constructor catches it, + outputs an error message through the trace statement and resets the keepLooking + Boolean to false, which terminates the while loop in lockMachine().
+ +package { + import flash.display.Sprite; + import flash.errors.ScriptTimeoutError; + + public class ScriptTimeoutErrorExample extends Sprite { + private var keepLooping:Boolean = true; + + public function ScriptTimeoutErrorExample() { + try { + lockMachine(); + } + catch(e:ScriptTimeoutError) { + trace(e); // ScriptTimeoutError: Error #1502: A script has executed for longer than 15 seconds + keepLooping = false; + } + } + + private function lockMachine():void { + while(keepLooping){ + } + } + } +} +
ScriptTimeoutError + Creates a new ScriptTimeoutError object.messageStringA string associated with the error object. + + + Creates a new ScriptTimeoutError object. + +
SQLError + A SQLError instance provides detailed information about a failed operation.Error + A SQLError instance provides detailed information about a failed operation. + +

In asynchronous execution mode, when an error occurs + with a SQL database operation the SQLConnection or SQLStatement instance + dispatches a SQLErrorEvent object. Information about the error in the form of a + SQLError instance can be accessed from the SQLErrorEvent object's error + property.

+ +

In synchronous execution mode, when an error occurs with a SQL + database operation the SQLConnection or SQLStatement instance throws a + SQLError exception, which can be handled by enclosing the error-throwing code in + a try..catch block.

+ +

This class provides properties containing the error details (specifying the specific type of + error that occured), a text message + containing the details of the error, and the operation that caused the + error to occur.

+ +
flash.events.SQLErrorEventflash.data.SQLConnectionflash.data.SQLStatementSQLError + Creates a SQLError instance that can be thrown or used with a + SQLErrorEvent instance's error property.operationStringIndicates the specific operation that caused + the failure. The value is one of the constants defined in the + SQLErrorOperation class. + + detailsStringThe details for the current error. + + messageStringThe description of the error that + occurred. + + idint0A reference number associated with the specific error message. + + detailIDint-1A reference number associated with the detail error message. + + detailArgsArraynullAn ordered array of substitution values that can be used + to construct a locale specific detail error message. + + + Creates a SQLError instance that can be thrown or used with a + SQLErrorEvent instance's error property. + + flash.errors.SQLErrorOperationtoString + + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined.The error message. + + String + + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined. + + detailArguments + An array of String values that can be used to construct a locale specific + detail error message.Array + An array of String values that can be used to construct a locale specific + detail error message. + +

This property contains the value or values that are substituted into + the details property error message to indicate the specific + database object or objects (table name, column name, and so forth) + associated with the error. For example, suppose an error with the following + details property error message occurs in an application:

+ + there is already another table or index with this name: 'my_table' + +

In that case, the SQLError instance's detailArguments + property would contain a single element with the value "my_table".

+ +

Using the detailID property an + application can identify the specific details error message. The + application can provide alternate text for the end user in the language + of his or her locale. The argument values in the detailArguments array + can be substituted in the appropriate position in the error message string. This + is useful for applications that wish to display the details + property error message for this error directly to end users in a specific locale.

+ +

For a list of the detailID values and their corresponding + English error details message and arguments, see + "SQL error detail messages, ids, and arguments."

+ +
detailID + A reference number associated with the specific detail message.int + A reference number associated with the specific detail message. + This value is used to support locale specific translations of the + details property error message. + +

This property provides a unique identifier for each details + message. (For any type of error with a specific errorID there are + multiple errors with unique detailID values.) Using this + identifier together with the value or values in the + detailArguments array, an application can provide + locale specific detail error messages. This is useful for applications + that wish to display the details property error message for + this error directly to end users in a specific locale.

+ +

For a list of the detailID values and their corresponding + English error details message and arguments, see + "SQL error detail messages, ids, and arguments."

+ +
details + Details of the current error.String + Details of the current error. This provides additional specific + information about the error that occurred. + + operation + A value indicating the operation that was being attempted when the error occurred.String + A value indicating the operation that was being attempted when the error occurred. + This value is one of the constants defined in the SQLErrorOperation class. + + flash.errors.SQLErrorOperation
SQLErrorOperation + This class contains the constants that represent the possible values for the + SQLError.operation property.Object + This class contains the constants that represent the possible values for the + SQLError.operation property. These values indicate the attempted operation + that caused the error to occur. + +

Each value represents one of the operations of the SQLConnection class + or the SQLStatement class.

+ +
flash.errors.SQLError.operationflash.data.SQLConnectionflash.data.SQLStatementANALYZE + Indicates that the SQLConnection.analyze() method was called.analyzeString + Indicates that the SQLConnection.analyze() method was called. + + flash.data.SQLConnection.analyze()ATTACH + Indicates that the SQLConnection.attach() method was called.attachString + Indicates that the SQLConnection.attach() method was called. + + flash.data.SQLConnection.attach()BEGIN + Indicates that the SQLConnection.begin() method was called.beginString + Indicates that the SQLConnection.begin() method was called. + + flash.data.SQLConnection.begin()CLOSE + Indicates that the SQLConnection.close() method was called.closeString + Indicates that the SQLConnection.close() method was called. + + flash.data.SQLConnection.close()COMMIT + Indicates that the SQLConnection.commit() method was called.commitString + Indicates that the SQLConnection.commit() method was called. + + flash.data.SQLConnection.commit()COMPACT + Indicates that the SQLConnection.compact() method was called.compactString + Indicates that the SQLConnection.compact() method was called. + + flash.data.SQLConnection.compact()DEANALYZE + Indicates that the SQLConnection.deanalyze() method was called.deanalyzeString + Indicates that the SQLConnection.deanalyze() method was called. + + flash.data.SQLConnection.deanalyze()DETACH + Indicates that the SQLConnection.detach() method was called.detachString + Indicates that the SQLConnection.detach() method was called. + + flash.data.SQLConnection.detach()EXECUTE + Indicates that either the SQLStatement.execute() method + or the SQLStatement.next() method was called.executeString + Indicates that either the SQLStatement.execute() method + or the SQLStatement.next() method was called. + + flash.data.SQLStatement.execute()OPEN + Indicates that either the SQLConnection.open() method or the SQLConnection.openAsync() method was called.openString + Indicates that either the SQLConnection.open() method or the SQLConnection.openAsync() method was called. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()REENCRYPT + Indicates that the SQLConnection.reencrypt() method was called.reencryptString + Indicates that the SQLConnection.reencrypt() method was called. + + flash.data.SQLConnection.reencrypt()RELEASE_SAVEPOINT + Indicates that the SQLConnection.releaseSavepoint() method was called.releaseSavepointString + Indicates that the SQLConnection.releaseSavepoint() method was called. + + flash.data.SQLConnection.releaseSavepoint()ROLLBACK_TO_SAVEPOINT + Indicates that the SQLConnection.rollbackToSavepoint() method was called.rollbackToSavepointString + Indicates that the SQLConnection.rollbackToSavepoint() method was called. + + flash.data.SQLConnection.rollbackToSavepoint()ROLLBACK + Indicates that the SQLConnection.rollback() method was called.rollbackString + Indicates that the SQLConnection.rollback() method was called. + + flash.data.SQLConnection.rollback()SCHEMA + Indicates that the SQLConnection.loadSchema() method was called.schemaString + Indicates that the SQLConnection.loadSchema() method was called. + + flash.data.SQLConnection.loadSchema()SET_SAVEPOINT + Indicates that the SQLConnection.setSavepoint() method was called.setSavepointString + Indicates that the SQLConnection.setSavepoint() method was called. + + flash.data.SQLConnection.setSavepoint()
MemoryError + The MemoryError exception is thrown when a memory allocation request fails.Error + The MemoryError exception is thrown when a memory allocation request fails. + +

On a desktop machine, memory allocation failures are rare unless an allocation + request is extremely large. For example, a 32-bit Windows program can access only 2GB of + address space, so a request for 10 billion bytes is impossible.

+ +

By default, Flash Player does not impose a limit on how much memory an + ActionScript program can allocate.

+ +
The following example shows one method of generating a MemoryError. + +package { + import flash.display.Sprite; + import flash.errors.MemoryError; + import flash.utils.setInterval; + + public class MemoryErrorExample extends Sprite { + private var crashingStr:String; + private var intervalId:Number; + + public function MemoryErrorExample() { + crashingStr = "abcdefghijklmnopqrstuvwxyz"; + intervalId = setInterval(exhaustMemory, 50); + } + + public function exhaustMemory():void { + try { + crashingStr += crashingStr; + } + catch(e:MemoryError) { + trace(e); + } + } + } +} +
MemoryError + Creates a new MemoryError object.messageStringA string associated with the error object. + + + Creates a new MemoryError object. + +
StackOverflowError + ActionScript throws a StackOverflowError exception when the stack available to the script + is exhausted.Error + ActionScript throws a StackOverflowError exception when the stack available to the script + is exhausted. ActionScript uses a stack to store information about each method call made in + a script, such as the local variables that the method uses. The amount of stack space + available varies from system to system. + +

A StackOverflowError exception might indicate that infinite recursion has occurred, in + which case a termination case needs to be added to the function. It also might indicate + that the recursive algorithm has a proper terminating condition but has exhausted the stack + anyway. In this case, try to express the algorithm iteratively instead.

+ +
The following example uses the sample StackOverflowErrorExample class to show + the error generated in the event of a stack overflow. This is accomplished using the following + steps: +
  1. The constructor calls the method lockMachine() within an error handling code + segment that catches StackOverflowError objects.
  2. The lockMachine() method calls itself until the stack overflows.
  3. After the StackOverflowError is thrown, the constructor catches it and then outputs an + error message through the trace statement.
+ +package { + import flash.display.Sprite; + import flash.errors.StackOverflowError; + + public class StackOverflowErrorExample extends Sprite { + public function StackOverflowErrorExample() { + try { + lockMachine(); + } + catch(e:StackOverflowError) { + trace(e); // StackOverflowError: Error #1023: Stack overflow. + } + } + + private function lockMachine():void { + lockMachine(); + } + } +} +
StackOverflowError + Creates a new StackOverflowError object.messageStringA string associated with the error object. + + + Creates a new StackOverflowError object. +
DRMManagerError + The DRMManager dispatches a DRMManagerError event to report errors.Error + The DRMManager dispatches a DRMManagerError event to report errors. + + flash.net.drm.DRMManagerDRMManagerError + Creates a new instance of the DRMManagerError class.messageStringThe error description + idintThe general error number + subErrorIDintThe specific error number + + + Creates a new instance of the DRMManagerError class. + + toString + + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined.The error message. + + String + + + Returns the string "Error" by default or the value contained in the Error.message property, + if defined. + + subErrorID + The specific error number.int + The specific error number. + + IOError + The IOError exception is thrown when some type of input or output failure occurs.Error + The IOError exception is thrown when some type of input or output failure occurs. + For example, an IOError exception is thrown if a read/write operation is attempted on + a socket that has not connected or that has become disconnected. + + + The following example throws an IOError exception when it attempts to close + a Sound stream that has never been loaded. + +package { + import flash.display.Sprite; + import flash.errors.IOError; + import flash.media.Sound; + + public class IOErrorExample extends Sprite + { + public function IOErrorExample() + { + var music:Sound = new Sound(); + try { + music.close(); + trace("Stream closed."); + } catch (error:IOError) { + trace("The stream could not be closed, or the stream was not open."); + } + } + } +} +IOError + Creates a new IOError object.messageStringA string associated with the error object. + + + + Creates a new IOError object. + + IllegalOperationError + The IllegalOperationError exception is thrown when a method is not implemented or the + implementation doesn't cover the current usage.Error + The IllegalOperationError exception is thrown when a method is not implemented or the + implementation doesn't cover the current usage. + +

Examples of illegal operation error exceptions include:

+
  • A base class, such as DisplayObjectContainer, provides more functionality than a Stage + can support (such as masks)
  • Certain accessibility methods are called when the player is compiled without accessibility + support
  • The mms.cfg setting prohibits a FileReference action
  • ActionScript tries to run a FileReference.browse() call when a browse dialog box is already open
  • ActionScript tries to use an unsupported protocol for a FileReference object (such as FTP)
  • Authoring-only features are invoked from a run-time player
  • An attempt is made to set the name of a Timeline-placed object
+ +
The following example shows the use of an IllegalOperationError handler. + +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.errors.IllegalOperationError; + + public class IllegalOperationErrorExample extends Sprite { + public function IllegalOperationErrorExample() { + var child:Sprite = new Sprite(); + try { + addChild(child); + } + catch(e:IllegalOperationError) { + trace(e); + } + } + + public override function addChild(child:DisplayObject):DisplayObject { + throw new IllegalOperationError("addChild cannot be performed on the IllegalOperationErrorExample class"); + } + } +} +
IllegalOperationError + Creates a new IllegalOperationError object.messageStringA string associated with the error object. + + + Creates a new IllegalOperationError object. + +
EOFError + An EOFError exception is thrown when you attempt to read past the end of the available data.flash.errors:IOError + An EOFError exception is thrown when you attempt to read past the end of the available data. For example, an + EOFError is thrown when one of the read methods in the IDataInput interface is + called and there is insufficient data to satisfy the read request. + + The following example uses the EOFErrorExample class to show + the error generated if an attempt is made to read past the end of the available + data. This is accomplished with the following steps: +
  1. The constructor creates a ByteArray object byteArr and writes a Boolean + value of false into the byte stream using writeBoolean().
  2. The position of byteArr is reset to 0 (start of the data stream).
  3. A single byte is removed from the data stream using readBoolean(). The + data stream now contains no data.
  4. Within an error handling code segment set to catch EOFError objects, readBoolean() + is called a second time and the EOFError is caught and passed to a trace() + statement, which outputs the error message associated with EOFError objects.
+ +package { + import flash.display.Sprite; + import flash.errors.EOFError; + import flash.utils.ByteArray; + + public class EOFErrorExample extends Sprite { + public function EOFErrorExample() { + var byteArr:ByteArray = new ByteArray(); + + byteArr.writeBoolean(false); + trace(byteArr.length); // 1 + + byteArr.position = 0; + try { + trace(byteArr.readBoolean()); // false + } + catch(e:EOFError) { + trace(e); + } + try { + trace(byteArr.readBoolean()); + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + } + } +} +
flash.utils.ByteArrayflash.utils.IDataInputflash.net.Socketflash.net.URLStreamEOFError + Creates a new EOFError object.messageStringA string associated with the error object. + + + Creates a new EOFError object. + +
InvalidSWFError + The Flash runtimes throw this exception when they encounter a corrupted SWF file.Error + The Flash runtimes throw this exception when they encounter a corrupted SWF file. + InvalidSWFError + Creates a new InvalidSWFError object.messageStringA string associated with the error object. + + idint0 + Creates a new InvalidSWFError object. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.events.xml b/language-server/playerglobal_docs/flash.events.xml new file mode 100644 index 0000000..24071fa --- /dev/null +++ b/language-server/playerglobal_docs/flash.events.xml @@ -0,0 +1,9149 @@ +flash.eventsNetMonitorEvent + + A NetMonitor object dispatches NetMonitorEvent objects when a NetStream object is created.flash.events:Event + A NetMonitor object dispatches NetMonitorEvent objects when a NetStream object is created. + + netStreamCreateflash.events:NetMonitorEvent:NET_STREAM_CREATEflash.events:NetMonitorEventNetMonitorEvent + Creates an event object that contains information about netStreamCreate events.typeStringThe type of the event. Event listeners can access this information through the + inherited type property. There is only one type of event: + NetMonitorEvent.NET_STREAM_CREATE. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + netStreamflash.net:NetStreamnullThe new NetStream object that has been created. Event listeners can access + this information through the netStream property. + + Constructor for NetMonitorEvent objects. + + Creates an event object that contains information about netStreamCreate events. + Event objects are passed as parameters to Event listeners. + + NetMonitorEvent.NET_STREAM_CREATEclone + Creates a copy of an NetMonitorEvent object and sets the value of each property to match that of + the original.A new NetMonitorEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of an NetMonitorEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the NetMonitorEvent object.A string that contains all the properties of NetMonitorEvent object. + String + Returns a string that contains all the properties of the NetMonitorEvent object. The following + format is used: +

[NetMonitorEvent type=value bubbles=value cancelable=value + netStream=value]

+ +
NET_STREAM_CREATE + The NetMonitorEvent.NET_STREAM_CREATE constant defines the value of the type property of an netStreamCreate event object.netStreamCreateString + The NetMonitorEvent.NET_STREAM_CREATE constant defines the value of the type property of an netStreamCreate event object. +

The netStreamCreate event has the following properties:

+ PropertyValuenetStreamNetStream object that has been created.bubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object beginning or ending a session. + +
netStream + The new NetStream object.flash.net:NetStream + The new NetStream object. + +
TimerEvent + A Timer object dispatches a TimerEvent objects whenever the Timer object reaches the interval + specified by the Timer.delay property.Event objects for Timer events. + flash.events:Event + A Timer object dispatches a TimerEvent objects whenever the Timer object reaches the interval + specified by the Timer.delay property. + + The following example uses the TimerExample class to show how a + listener method timerHandler() can be instantiated and set to listen for a new TimerEvent + to be dispatched, which happens when the Timer's start() method is called. + +package { + import flash.utils.Timer; + import flash.events.TimerEvent; + import flash.display.Sprite; + + public class TimerEventExample extends Sprite { + + public function TimerEventExample() { + var myTimer:Timer = new Timer(1000, 2); + myTimer.addEventListener(TimerEvent.TIMER, timerHandler); + myTimer.start(); + } + + public function timerHandler(event:TimerEvent):void { + trace("timerHandler: " + event); + } + } +} +flash.utils.TimertimerCompleteflash.events:TimerEvent:TIMER_COMPLETEflash.events:TimerEventflash.utils.Timer.timerCompletetimerflash.events:TimerEvent:TIMERflash.events:TimerEventflash.utils.Timer.timerTimerEvent + Creates an Event object with specific information relevant to timer events.typeString The type of the event. Event listeners can access this information through the inherited type property. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + + Constructor for TimerEvent objects. + + Creates an Event object with specific information relevant to timer events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the TimerEvent object and sets each property's value to match that of the original.A new TimerEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the TimerEvent object and sets each property's value to match that of the original. + toString + Returns a string that contains all the properties of the TimerEvent object.A string that contains all the properties of the TimerEvent object. + String + Returns a string that contains all the properties of the TimerEvent object. The string is in the following format: +

[TimerEvent type=value bubbles=value cancelable=value]

+
updateAfterEvent + Instructs Flash Player or the AIR runtime to render + after processing of this event completes, if the display list has been modified. + Instructs Flash Player or the AIR runtime to render + after processing of this event completes, if the display list has been modified. + + The following is an example for the TimerEvent.updateAfterEvent() method. + +function onTimer(event:TimerEvent):void { + if (40 < my_mc.x && my_mc.x < 375) { + my_mc.x-= 50; + } else { + my_mc.x=374; + } + event.updateAfterEvent(); +} + +var moveTimer:Timer=new Timer(50,250); +moveTimer.addEventListener(TimerEvent.TIMER,onTimer); +moveTimer.start(); +TIMER_COMPLETE + Defines the value of the type property of a timerComplete event object.timerCompleteString + Defines the value of the type property of a timerComplete event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Timer object that has completed its requests. +
flash.utils.Timer.timerComplete
TIMER + Defines the value of the type property of a timer event object.timerString + Defines the value of the type property of a timer event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Timer object that has reached its interval. +
flash.utils.Timer.timer
IOErrorEvent +An IOErrorEvent object is dispatched when an error causes input or output operations to fail.Event objects for IOErrorEvent events. +flash.events:ErrorEvent +An IOErrorEvent object is dispatched when an error causes input or output operations to fail. + +

You can check for error events that do not have any listeners by using the debugger +version of Flash Player or the AIR Debug Launcher (ADL). The string defined by the +text parameter of the IOErrorEvent constructor is displayed.

+ +
The following example uses the IOErrorEventExample class to show how an error + event object is dispatched when an attempt is made to load a nonexistent file. The example carries out the following tasks: +
  1. The class constructor creates a new instance of a URLLoader object and assigns it to the variable + loader.
  2. The URLLoader instance instantiates an event listener of type ioError, which has + an associated subscriber method ioErrorHandler(), which simply prints information about + the event using trace().
  3. Next, the constructor creates a new instance of a URLRequest object, request, + passing MissingFile.xml so that the name and location of the missing file are + known.
  4. The request variable is then passed to loader.load(), which attempts to load the + missing file. Since the file is missing, the event handler dispatches an ioError event.
+ +

Notes: +

  • You need to compile the SWF file with "Local Playback Security" set to "Access Local Files Only".
  • Make sure that you do not have a file named "MissingFile.xml" at the same level as your SWF file.
+

+ +package { + import flash.display.Sprite; + import flash.events.IOErrorEvent; + import flash.net.URLLoader; + import flash.net.URLRequest; + + public class IOErrorEventExample extends Sprite { + public function IOErrorEventExample() { + var loader:URLLoader = new URLLoader(); + loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + + var request:URLRequest = new URLRequest("MissingFile.xml"); + loader.load(request); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
IO_ERRORioErrorflash.events:IOErrorEvent:IO_ERRORflash.events:IOErrorEventflash.display.LoaderInfo.ioErrorflash.media.Sound.ioErrorflash.net.SecureSocket.ioErrorflash.net.Socket.ioErrorflash.net.FileReference.ioErrorflash.net.NetConnection.ioErrorflash.net.NetStream.ioErrorflash.net.URLLoader.ioErrorflash.net.URLStream.ioErrorflash.net.XMLSocket.ioErrorIOErrorEventflash.events:IOErrorEvent:STANDARD_ERROR_IO_ERRORflash.events:IOErrorEventIOErrorEventflash.events:IOErrorEvent:STANDARD_INPUT_IO_ERRORflash.events:IOErrorEventIOErrorEventflash.events:IOErrorEvent:STANDARD_OUTPUT_IO_ERRORflash.events:IOErrorEventIOErrorEvent + Creates an Event object that contains specific information about ioError events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of input/output error event: IOErrorEvent.IO_ERROR. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error (supported in Adobe AIR only). + + Constructor for IOErrorEvent objects. + + Creates an Event object that contains specific information about ioError events. + Event objects are passed as parameters to Event listeners. + + IO_ERRORclone + Creates a copy of the IOErrorEvent object and sets the value of each property to match that of the original.A new IOErrorEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the IOErrorEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the IOErrorEvent object.A string that contains all the properties of the IOErrorEvent object. + + String + Returns a string that contains all the properties of the IOErrorEvent object. The string is in the following format: +

[IOErrorEvent type=value bubbles=value cancelable=value text=value errorID=value] + The errorId is only available in Adobe AIR

+ +
IO_ERROR + Defines the value of the type property of an ioError event object.ioErrorString + Defines the value of the type property of an ioError event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.errorIDA reference number associated with the specific error (AIR only).targetThe network object experiencing the input/output error.textText to be displayed as an error message. + +
flash.display.LoaderInfo.ioErrorflash.media.Sound.ioErrorflash.net.SecureSocket.ioErrorflash.net.Socket.ioErrorflash.net.FileReference.ioErrorflash.net.NetConnection.ioErrorflash.net.NetStream.ioErrorflash.net.URLLoader.ioErrorflash.net.URLStream.ioErrorflash.net.XMLSocket.ioError
STANDARD_ERROR_IO_ERROR + The standardErrorIoError event is dispatched when an error occurs while + reading data from the standardError stream of a NativeProcess object.standardErrorIoErrorString + The standardErrorIoError event is dispatched when an error occurs while + reading data from the standardError stream of a NativeProcess object. +

This event has the following properties:

+ PropertyValuebubblesNo.cancelableNo. There is no default behavior to cancel.errorIDThe reference number associated with the specific error.targetThe object on which the error occurred.textText to be displayed as an error message. + +
STANDARD_INPUT_IO_ERROR + The standardInputIoError event is dispatched when an error occurs while + writing data to the standardInput of a NativeProcess object.standardInputIoErrorString + The standardInputIoError event is dispatched when an error occurs while + writing data to the standardInput of a NativeProcess object. +

This event has the following properties:

+ PropertyValuebubblesNo.cancelableNo. There is no default behavior to cancel.errorIDThe reference number associated with the specific error.targetThe object on which the error occurred.textText to be displayed as an error message. + +
STANDARD_OUTPUT_IO_ERROR + The standardOutputIoError event is dispatched when an error occurs while + reading data from the standardOutput stream of a NativeProcess object.standardOutputIoErrorString + The standardOutputIoError event is dispatched when an error occurs while + reading data from the standardOutput stream of a NativeProcess object. +

This event has the following properties:

+ PropertyValuebubblesNo.cancelableNo. There is no default behavior to cancel.errorIDThe reference number associated with the specific error.targetThe object on which the error occurred.textText to be displayed as an error message. + +
NetStatusEvent +A NetConnection, NetStream, or SharedObject object dispatches NetStatusEvent objects when a it reports its status.Event objects for NetStatusEvent events. +flash.events:Event +A NetConnection, NetStream, or SharedObject object dispatches NetStatusEvent objects when a it reports its status. +There is only one type of status event: NetStatusEvent.NET_STATUS. + + The following example uses a Video object with the NetConnection and + NetStream classes to load and play an FLV file. +

In this example, the netStatusHandler method is registered as a listener for + the NetStatusEvent event NetConnection.netStatus. + When the status (success or failure) of the NetConnection.connect() attempt + is determined, the netStatus event triggers this method. If the + attempt to connect to the NetConnection object is successful (in other words, + if the info property of the NetStatusEvent object dispatched by the netStatus + event has a code property that indicates success), the code creates the Video and NetStream + objects and calls the Video.attachNetStream() and NetStream.play() methods.

+ +

Note: To run this example, you need an FLV file + whose name and location match the variable passed to videoURL; + in this case, an FLV file called Video.flv that is in the same directory as the SWF file.

+ + + package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + + public class NetStatusEventExample extends Sprite { + private var videoURL:String = "Video.flv"; + private var connection:NetConnection; + private var stream:NetStream; + + public function NetStatusEventExample() { + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Unable to locate video: " + videoURL); + break; + } + } + + private function connectStream():void { + var stream:NetStream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + var video:Video = new Video(); + video.attachNetStream(stream); + stream.play(videoURL); + addChild(video); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function asyncErrorHandler(event:AsyncErrorEvent):void { + // ignore AsyncErrorEvent events. + } + + } + } +
flash.net.NetConnectionflash.net.NetStreamflash.net.SharedObjectNetStatusEvent.NET_STATUSnetStatusflash.events:NetStatusEvent:NET_STATUSflash.events:NetStatusEventflash.events.NetStatusEvent.infoflash.net.NetConnection.netStatusflash.net.NetStream.netStatusflash.net.SharedObject.netStatusNetStatusEvent + Creates an Event object that contains information about netStatus events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of status event: NetStatusEvent.NET_STATUS. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + infoObjectnullAn object containing properties that describe the object's status. Event listeners can access this object through the info property. + + Constructor for NetStatusEvent objects. + + Creates an Event object that contains information about netStatus events. + Event objects are passed as parameters to event listeners. + + flash.events.NetStatusEvent.NET_STATUSclone + Creates a copy of the NetStatusEvent object and sets the value of each property to match that of the original.A new NetStatusEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the NetStatusEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the NetStatusEvent object.A string that contains all the properties of the NetStatusEvent object. + + String + Returns a string that contains all the properties of the NetStatusEvent object. The string is in the following format: +

[NetStatusEvent type=value bubbles=value cancelable=value info=value]

+ +
NET_STATUS + Defines the value of the type property of a netStatus event object.netStatusString + Defines the value of the type property of a netStatus event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.infoAn object with properties that describe the object's status or error condition.targetThe NetConnection or NetStream object reporting its status. + +
flash.events.NetStatusEvent.infoflash.net.NetConnection.netStatusflash.net.NetStream.netStatusflash.net.SharedObject.netStatus
info + An object with properties that describe the object's status or error condition.Object + An object with properties that describe the object's status or error condition. + +

The information object could have a code property containing a string + that represents a specific event or a level property containing a string + that is either "status" or "error".

+ +

The information object could also be something different. The code and + level properties might not work for some implementations and some servers + might send different objects.

+ +

P2P connections send messages to a NetConnection with a stream parameter + in the information object that indicates which NetStream the message pertains to.

+ +

For example, Flex Data Services sends Message + objects that cause coercion errors if you try to access the code or + level property.

+ +

The following table describes the possible string values of the code and level + properties.

+ Code propertyLevel propertyMeaning"NetConnection.Call.BadVersion""error"Packet encoded in an unidentified format."NetConnection.Call.Failed""error"The NetConnection.call() method was not able to invoke the server-side + method or command."NetConnection.Call.Prohibited""error"An Action Message Format (AMF) operation is prevented for + security reasons. Either the AMF URL is not in the same domain as the file containing the code + calling the NetConnection.call() method, or the AMF server does not have a policy file + that trusts the domain of the the file containing the code calling the NetConnection.call() method. "NetConnection.Connect.AppShutdown""error"The server-side application is shutting down."NetConnection.Connect.Closed""status"The connection was closed successfully."NetConnection.Connect.Failed""error"The connection attempt failed."NetConnection.Connect.IdleTimeout""status"Flash Media Server disconnected the client because the client was idle longer than the configured value for <MaxIdleTime>. On Flash Media Server, <AutoCloseIdleClients> is disabled by default. When enabled, the default timeout value is 3600 seconds (1 hour). For more information, see + Close idle connections. "NetConnection.Connect.InvalidApp""error"The application name specified in the call to NetConnection.connect() is invalid."NetConnection.Connect.NetworkChange""status"

Flash Player has detected a network change, for example, a dropped wireless connection, a successful wireless connection,or a network cable loss.

+

Use this event to check for a network interface change. Don't use this event to implement your NetConnection reconnect logic. Use "NetConnection.Connect.Closed" to implement your NetConnection reconnect logic.

"NetConnection.Connect.Rejected""error"The connection attempt did not have permission to access the application."NetConnection.Connect.Success""status"The connection attempt succeeded."NetGroup.Connect.Failed""error"The NetGroup connection attempt failed. The info.group property indicates which NetGroup failed."NetGroup.Connect.Rejected""error"The NetGroup is not authorized to function. The info.group property indicates which NetGroup was denied."NetGroup.Connect.Succcess""status"The NetGroup is successfully constructed and authorized to function. The info.group property indicates which NetGroup has succeeded."NetGroup.LocalCoverage.Notify""status"Sent when a portion of the group address space for which this node is responsible changes."NetGroup.MulticastStream.PublishNotify""status"Sent when a new named stream is detected in NetGroup's Group. The info.name:String property is the name of the detected stream."NetGroup.MulticastStream.UnpublishNotify""status"Sent when a named stream is no longer available in the Group. The info.name:String property is name of the stream which has disappeared."NetGroup.Neighbor.Connect""status"Sent when a neighbor connects to this node. The info.neighbor:String property is the group address of the neighbor. The info.peerID:String property is the peer ID of the neighbor."NetGroup.Neighbor.Disconnect""status"Sent when a neighbor disconnects from this node. The info.neighbor:String property is the group address of the neighbor. The info.peerID:String property is the peer ID of the neighbor."NetGroup.Posting.Notify""status"Sent when a new Group Posting is received. The info.message:Object property is the message. The info.messageID:String property is this message's messageID."NetGroup.Replication.Fetch.Failed""status"Sent when a fetch request for an object (previously announced with NetGroup.Replication.Fetch.SendNotify) fails or is denied. A new attempt for the object will be made if it is still wanted. The info.index:Number property is the index of the object that had been requested."NetGroup.Replication.Fetch.Result""status"Sent when a fetch request was satisfied by a neighbor. The info.index:Number property is the object index of this result. The info.object:Object property is the value of this object. This index will automatically be removed from the Want set. If the object is invalid, this index can be re-added to the Want set with NetGroup.addWantObjects()."NetGroup.Replication.Fetch.SendNotify""status"Sent when the Object Replication system is about to send a request for an object to a neighbor.The info.index:Number property is the index of the object that is being requested."NetGroup.Replication.Request""status"Sent when a neighbor has requested an object that this node has announced with NetGroup.addHaveObjects(). This request must eventually be answered with either NetGroup.writeRequestedObject() or NetGroup.denyRequestedObject(). Note that the answer may be asynchronous. The info.index:Number property is the index of the object that has been requested. The info.requestID:int property is the ID of this request, to be used by NetGroup.writeRequestedObject() or NetGroup.denyRequestedObject()."NetGroup.SendTo.Notify""status"Sent when a message directed to this node is received. The info.message:Object property is the message. The info.from:String property is the groupAddress from which the message was received. The info.fromLocal:Boolean property is TRUE if the message was sent by this node (meaning the local node is the nearest to the destination group address), and FALSE if the message was received from a different node. To implement recursive routing, the message must be resent with NetGroup.sendToNearest() if info.fromLocal is FALSE."NetStream.Buffer.Empty""status"Flash Player is not receiving data quickly enough to fill the buffer. Data flow is interrupted until the buffer refills, at which time a NetStream.Buffer.Full message is sent and the stream begins playing again."NetStream.Buffer.Flush""status"Data has finished streaming, and the remaining buffer is emptied."NetStream.Buffer.Full""status"The buffer is full and the stream begins playing."NetStream.Connect.Closed""status"The P2P connection was closed successfully. The info.stream property indicates which stream has closed."NetStream.Connect.Failed""error"The P2P connection attempt failed. The info.stream property indicates which stream has failed."NetStream.Connect.Rejected""error"The P2P connection attempt did not have permission to access the other peer. The info.stream property indicates which stream was rejected."NetStream.Connect.Success""status"The P2P connection attempt succeeded. The info.stream property indicates which stream has succeeded."NetStream.DRM.UpdateNeeded""status"A NetStream object is attempting to play protected content, but the required + Flash Access module is either not present, not permitted by the effective content policy, + or not compatible with the current player. To update the module or player, use the + update() method of flash.system.SystemUpdater. "NetStream.Failed""error"(Flash Media Server) + An error has occurred for a reason other than those listed + in other event codes. "NetStream.MulticastStream.Reset""status"A multicast subscription has changed focus to a different stream published with the same name in the same group. Local overrides of multicast stream parameters are lost. Reapply the local overrides or the new stream's default parameters will be used."NetStream.Pause.Notify""status"The stream is paused."NetStream.Play.Failed""error"An error has occurred in playback for a reason other than those listed elsewhere + in this table, such as the subscriber not having read access."NetStream.Play.FileStructureInvalid""error"(AIR and Flash Player 9.0.115.0) The application detects an invalid file structure and will not try to play this type of file. "NetStream.Play.InsufficientBW""warning"(Flash Media Server) + The client does not have sufficient bandwidth to play + the data at normal speed. "NetStream.Play.NoSupportedTrackFound""error"(AIR and Flash Player 9.0.115.0) The application does not detect any supported tracks (video, audio or data) and will not try to play the file."NetStream.Play.PublishNotify""status"The initial publish to a stream is sent to all subscribers."NetStream.Play.Reset""status"Caused by a play list reset."NetStream.Play.Start""status"Playback has started."NetStream.Play.Stop""status"Playback has stopped."NetStream.Play.StreamNotFound""error"The file passed to the NetStream.play() method can't be found."NetStream.Play.Transition""status"(Flash Media Server 3.5) The server received the command to transition to another stream as a result of bitrate stream switching. This code indicates a success status event for the NetStream.play2() call to initiate a stream switch. If the switch does not succeed, the server sends a NetStream.Play.Failed event instead. + When the stream switch occurs, an onPlayStatus event with a code of "NetStream.Play.TransitionComplete" is dispatched. For Flash Player 10 and later."NetStream.Play.UnpublishNotify""status"An unpublish from a stream is sent to all subscribers."NetStream.Publish.BadName""error"Attempt to publish a stream which is already being published by someone else."NetStream.Publish.Idle""status"The publisher of the stream is idle and not transmitting data."NetStream.Publish.Start""status"Publish was successful."NetStream.Record.AlreadyExists""status"The stream being recorded maps to a file that is already being recorded to by another stream. This can happen due to misconfigured virtual directories."NetStream.Record.Failed""error"An attempt to record a stream failed."NetStream.Record.NoAccess""error"Attempt to record a stream that is still playing or the client has no access right."NetStream.Record.Start""status"Recording has started."NetStream.Record.Stop""status"Recording stopped."NetStream.Seek.Failed""error"The seek fails, which happens if the stream is not seekable."NetStream.Seek.InvalidTime""error"For video downloaded progressively, the user has tried to seek or play + past the end of the video data that has downloaded thus far, or past + the end of the video once the entire file has downloaded. The info.details property of the event object contains a time code + that indicates the last valid position to which the user can seek."NetStream.Seek.Notify""status"

The seek operation is complete.

+

Sent when NetStream.seek() is called on a stream in AS3 NetStream Data Generation Mode. The info object is extended to include info.seekPoint which is the same value passed to NetStream.seek().

"NetStream.Step.Notify""status"The step operation is complete."NetStream.Unpause.Notify""status"The stream is resumed."NetStream.Unpublish.Success""status"The unpublish operation was successfuul."SharedObject.BadPersistence""error"A request was made for a shared object with persistence flags, but the request cannot be granted because the object has already been created with different flags."SharedObject.Flush.Failed""error"The "pending" status is resolved, but the SharedObject.flush() failed."SharedObject.Flush.Success""status"The "pending" status is resolved and the SharedObject.flush() call succeeded."SharedObject.UriMismatch""error"An attempt was made to connect to a NetConnection object that has a different URI (URL) than the shared object.
+

If you consistently see errors regarding the buffer, try changing the buffer using the NetStream.bufferTime property.

+ + +
The following example shows an event handler function + that tests for the "NetStream.Seek.InvalidTime" error. + The "NetStream.Seek.InvalidTime" error + happens when the user attempts to seek beyond the end of the downloaded stream. The example + tests the value of the event object's info.code property. In case the error occurs, + the eventObj.info.details property is assigned to a variable + to use as a parameter for the stream's seek() method. The eventObj.info.details + contains the last valid position available to handle the error. So, the user goes to a valid location + at the end of the downloaded stream. + +function videoStatus(eventObj:NetStatusEvent):Void +{ + switch(eventObj.info.code) + { + case "NetStream.Seek.InvalidTime": + { + var validSeekTime:Number = eventObj.info.details; + nStream.seek(validSeekTime); + break; + } + } +} +
NetConnection classNetStream classNetGroup class
UncaughtErrorEvents + The UncaughtErrorEvents class provides a way to receive uncaught + error events.flash.events:EventDispatcher + The UncaughtErrorEvents class provides a way to receive uncaught + error events. An instance of this class dispatches an + uncaughtError event when a runtime error occurs and the + error isn't detected and handled in your code. + +

Use the following properties to access an UncaughtErrorEvents instance:

+ +
  • LoaderInfo.uncaughtErrorEvents: to + detect uncaught errors in code defined in the same SWF.
  • Loader.uncaughtErrorEvents: to detect uncaught + errors in code defined in the SWF loaded by a Loader object.
+ +

To catch an error directly and prevent an uncaught error event, + do the following:

+ +
  • Use a try..catch + block to isolate code that potentially throws a synchronous error
  • When performing an operation that dispatches an event when an error occurs, + register a listener for that error event
+ +

If the content loaded by a Loader object is an AVM1 (ActionScript 2) SWF file, + uncaught errors in the AVM1 SWF file do not result in an uncaughtError + event. In addition, JavaScript errors in HTML content loaded in an HTMLLoader object + (including a Flex HTML control) do not result in an uncaughtError event.

+ +
LoaderInfo.uncaughtErrorEventsLoader.uncaughtErrorEventsUncaughtErrorEventuncaughtError + Dispatched when an error occurs and developer code doesn't detect and handle + the error.flash.events.UncaughtErrorEvent.UNCAUGHT_ERRORflash.events.UncaughtErrorEvent + Dispatched when an error occurs and developer code doesn't detect and handle + the error. + + UncaughtErrorEvents + Creates an UncaughtErrorEvents instance. + Creates an UncaughtErrorEvents instance. Developer code shouldn't create + UncaughtErrorEvents instances directly. To access an UncaughtErrorEvents + object, use one of the following properties: + +
  • LoaderInfo.uncaughtErrorEvents: to + detect uncaught errors in code defined in the same SWF.
  • Loader.uncaughtErrorEvents: to detect uncaught + errors in code defined in the SWF loaded by a Loader object.
+ +
LoaderInfo.uncaughtErrorEventsLoader.uncaughtErrorEvents
MouseEvent + A MouseEvent object is dispatched into the event flow whenever mouse events occur.Event objects for Mouse events. + + flash.events:Event + A MouseEvent object is dispatched into the event flow whenever mouse events occur. + A mouse event is usually generated by a user input device, such as a mouse or a trackball, + that uses a pointer. + +

When nested nodes are involved, mouse events target the deepest possible nested node that + is visible in the display list. This node is called the target node. To have a + target node's ancestor receive notification of a mouse event, use + EventDispatcher.addEventListener() on the ancestor node with the + type parameter set to the specific mouse event you want to detect.

+ +
The following example uses the MouseEventExample and + ChildSprite classes to show how mouse events are dispatched using a simple image. + This example carries out the following tasks: +
  1. The example declares properties for the size (100 x 100 pixels) and the background color + (orange) for later use in drawing the square.
  2. The constructor creates a new ChildSprite object child. Its constructor first + draws an orange 100 x 100 pixel square at coordinates (0,0) by calling its draw() + method and then adds seven event listeners/subscribers. +
    • click/clickHandler(): Dispatched when the user single-clicks with the left mouse button + over the square.
    • doubleClick/doubleClickHandler(): Dispatched when the user double-clicks the left mouse button + over the square.
    • mouseDown/mouseDownHandler(): When the ChildSprite + object (the orange square) is clicked, a trace() message is printed to the screen, and then + ChildSprite.draw() is called, which draws a dark yellow square in place + of the light blue one drawn in mouseOverHandler(). The mouseDownHandler() method also adds a + mouseMoveevent listener and the mouseMoveHandler() subscriber (described below), + which processes the mouse moves. Then the startDrag() method is called, which + allows the Sprite object to be dragged.
    • mouseOut/mouseOutHandler(): Dispatched whenever the pointer leaves the + square area. The draw() method is called to return the square to its normal + size and color.
    • mouseOver/mouseOverHandler(): Dispatched when the mouse pointer is over the square. + This method redraws the square so that it is larger and its background color is dark yellow.
    • mouseUp/mouseUpHandler(): When the user releases the mouse button, the mouseMove + event listener is removed and stopDrag is called, which freezes the square in place.
    • mouseMove/mouseMoveHandler(): Called as part of the mouseDownHandler() function, and dispatched when the user is pressing the left mouse button and dragging the square.
    • mouseWheel/mouseWheelHandler(): Dispatched when the user rotates the mouse + wheel over the square.
  3. The ChildSprite instance child is then added to the display list by means of + addChild(), which promptly draws the orange square.
+ +

Notes:

+
  • The MouseEventExample class should be the document root.
  • Some of the event methods listed above declare a local variable sprite, which + is assigned the cast of event.target to type Sprite.
+ +package { + import flash.display.Sprite; + + public class MouseEventExample extends Sprite { + private var size:uint = 100; + private var bgColor:uint = 0xFFCC00; + + public function MouseEventExample() { + var child:ChildSprite = new ChildSprite(); + addChild(child); + } + } +} + +import flash.display.Sprite; +import flash.events.MouseEvent; + +class ChildSprite extends Sprite { + private var size:uint = 50; + private var overSize:uint = 60; + private var backgroundColor:uint = 0xFFCC00; + private var overColor:uint = 0xCCFF00; + private var downColor:uint = 0x00CCFF; + + public function ChildSprite() { + draw(size, size, backgroundColor); + doubleClickEnabled = true; + addEventListener(MouseEvent.CLICK, clickHandler); + addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler); + addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); + addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); + addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler); + } + + private function draw(w:uint, h:uint, bgColor:uint):void { + graphics.clear(); + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, w, h); + graphics.endFill(); + } + + private function clickHandler(event:MouseEvent):void { + trace("clickHandler"); + } + + private function doubleClickHandler(event:MouseEvent):void { + trace("doubleClickHandler"); + } + + private function mouseDownHandler(event:MouseEvent):void { + trace("mouseDownHandler"); + draw(overSize, overSize, downColor); + + var sprite:Sprite = Sprite(event.target); + sprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + sprite.startDrag(); + } + + private function mouseMoveHandler(event:MouseEvent):void { + trace("mouseMoveHandler"); + event.updateAfterEvent(); + } + + private function mouseOutHandler(event:MouseEvent):void { + trace("mouseOutHandler"); + draw(size, size, backgroundColor); + } + + private function mouseOverHandler(event:MouseEvent):void { + trace("mouseOverHandler"); + draw(overSize, overSize, overColor); + } + + private function mouseWheelHandler(event:MouseEvent):void { + trace("mouseWheelHandler delta: " + event.delta); + } + + private function mouseUpHandler(event:MouseEvent):void { + trace("mouseUpHandler"); + var sprite:Sprite = Sprite(event.target); + sprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + sprite.stopDrag(); + draw(overSize, overSize, overColor); + } +} +
clickflash.events:MouseEvent:CLICKflash.events:MouseEventflash.display.InteractiveObject.clickcontextMenuflash.events:MouseEvent:CONTEXT_MENUflash.events:MouseEventdoubleClickflash.events:MouseEvent:DOUBLE_CLICKflash.events:MouseEventflash.display.InteractiveObject.doubleClickmiddleClickflash.events:MouseEvent:MIDDLE_CLICKflash.events:MouseEventflash.display.InteractiveObject.middleClickmiddleMouseDownflash.events:MouseEvent:MIDDLE_MOUSE_DOWNflash.events:MouseEventflash.display.InteractiveObject.middleMouseDownmiddleMouseUpflash.events:MouseEvent:MIDDLE_MOUSE_UPflash.events:MouseEventflash.display.InteractiveObject.middleMouseUpmouseDownflash.events:MouseEvent:MOUSE_DOWNflash.events:MouseEventflash.display.InteractiveObject.mouseDownmouseMoveflash.events:MouseEvent:MOUSE_MOVEflash.events:MouseEvent The following example is a simple drawing program. The user can draw on the + main Sprite object or on a smaller rectangular Sprite object. + +

In the constructor, a rectangle innerRect Sprite object is created + and the line style is set to green. The line style for drawing on the + MouseEvent_MOUSE_MOVEExample Sprite container is set to red. Separate event + listeners for the MouseEvent.MOUSE_UP and MouseEvent.MOUSE_DOWN + events are added for the application's main Sprite object and innerRect + Sprite object. In both cases, the mouse down event listener methods move the current drawing + position to the mouse pointer's location and add a listener for the MouseEvent.MOUSE_MOVE + event. When the mouse pointer is moved, the invoked event listener methods follows the pointer and draw + a line using the graphics.LineTo() method. (Note: The innerRect + Sprite object obscures the red lines of the main Sprite object that are drawn behind the rectangle.) + When the MouseEvent.MOUSE_UP event occurs, the listener for the MOUSE_MOVE + event is removed and drawing is stopped.

+ + +package { + import flash.display.Sprite; + import flash.display.Graphics; + import flash.events.MouseEvent; + + public class MouseEvent_MOUSE_MOVEExample extends Sprite { + private var innerRect:Sprite = new Sprite(); + + public function MouseEvent_MOUSE_MOVEExample() { + + graphics.lineStyle(3, 0xFF0000, 1); + stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + + innerRect.graphics.lineStyle(1, 0x00FF00, 1); + innerRect.graphics.beginFill(0xFFFFFF); + innerRect.graphics.drawRect(10, 10, 200, 200); + innerRect.graphics.endFill(); + innerRect.addEventListener(MouseEvent.MOUSE_DOWN, innerRectMouseDownHandler); + innerRect.addEventListener(MouseEvent.MOUSE_UP, innerRectMouseUpHandler); + addChild(innerRect); + } + + private function mouseDownHandler(event:MouseEvent):void { + graphics.moveTo(event.stageX, event.stageY); + stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function mouseMoveHandler(event:MouseEvent):void { + graphics.lineTo(event.stageX, event.stageY); + } + + private function mouseUpHandler(event:MouseEvent):void { + stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function innerRectMouseDownHandler(event:MouseEvent):void { + innerRect.graphics.moveTo(event.localX, event.localY); + innerRect.addEventListener(MouseEvent.MOUSE_MOVE, innerRectMouseMoveHandler); + } + + private function innerRectMouseMoveHandler(event:MouseEvent):void { + innerRect.graphics.lineTo(event.localX, event.localY); + } + + private function innerRectMouseUpHandler(event:MouseEvent):void { + innerRect.removeEventListener(MouseEvent.MOUSE_MOVE, innerRectMouseMoveHandler); + } + } +} +
flash.display.InteractiveObject.mouseMove
mouseOutflash.events:MouseEvent:MOUSE_OUTflash.events:MouseEventflash.display.InteractiveObject.mouseOutmouseOverflash.events:MouseEvent:MOUSE_OVERflash.events:MouseEventflash.display.InteractiveObject.mouseOvermouseUpflash.events:MouseEvent:MOUSE_UPflash.events:MouseEventflash.display.InteractiveObject.mouseUpmouseWheelflash.events:MouseEvent:MOUSE_WHEELflash.events:MouseEventflash.display.InteractiveObject.mouseWheelrightClickflash.events:MouseEvent:RIGHT_CLICKflash.events:MouseEventflash.display.InteractiveObject.rightClickRightMouseDownflash.events:MouseEvent:RIGHT_MOUSE_DOWNflash.events:MouseEventflash.display.InteractiveObject.rightMouseDownrightMouseUpflash.events:MouseEvent:RIGHT_MOUSE_UPflash.events:MouseEventflash.display.InteractiveObject.rightMouseUprollOutflash.events:MouseEvent:ROLL_OUTflash.events:MouseEventflash.display.InteractiveObject.rollOutrollOverflash.events:MouseEvent:ROLL_OVERflash.events:MouseEventflash.display.InteractiveObject.rollOverMouseEvent + Creates an Event object that contains information about mouse events.typeString The type of the event. Possible values are: MouseEvent.CLICK, + MouseEvent.DOUBLE_CLICK, MouseEvent.MOUSE_DOWN, + MouseEvent.MOUSE_MOVE, MouseEvent.MOUSE_OUT, + MouseEvent.MOUSE_OVER, MouseEvent.MOUSE_UP, + MouseEvent.MIDDLE_CLICK, MouseEvent.MIDDLE_MOUSE_DOWN, MouseEvent.MIDDLE_MOUSE_UP, + MouseEvent.RIGHT_CLICK, MouseEvent.RIGHT_MOUSE_DOWN, MouseEvent.RIGHT_MOUSE_UP, + MouseEvent.MOUSE_WHEEL, MouseEvent.ROLL_OUT, and MouseEvent.ROLL_OVER. + + bubblesBooleantrue Determines whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + localXNumberunknownThe horizontal coordinate at which the event occurred relative to the containing sprite. + localYNumberunknownThe vertical coordinate at which the event occurred relative to the containing sprite. + relatedObjectflash.display:InteractiveObjectnullThe complementary InteractiveObject instance that is affected by the event. For example, when a mouseOut event occurs, relatedObject represents the display list object to which the pointing device now points. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated (Windows or Linux only). + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + buttonDownBooleanfalseIndicates whether the primary mouse button is pressed. + deltaint0Indicates how many lines should be scrolled for each unit the user rotates the mouse wheel. A positive delta value indicates an upward scroll; a negative value indicates a downward scroll. Typical values are 1 to 3, but faster rotation may produce larger values. This parameter is used only for the MouseEvent.mouseWheel event. + commandKeyBooleanfalse(AIR only) Indicates whether the Command key is activated (Mac only). This parameter is used only for the MouseEvent.click, + MouseEvent.mouseDown, MouseEvent.mouseUp, MouseEvent.middleClick, MouseEvent.middleMouseDown, + MouseEvent.middleMouseUp, MouseEvent.rightClick, MouseEvent.rightMouseDown, MouseEvent.rightMouseUp, + and MouseEvent.doubleClick events. This parameter is for Adobe AIR only; do not set it for Flash Player content. + controlKeyBooleanfalse(AIR only) Indicates whether the Control or Ctrl key is activated. This parameter is used only for the MouseEvent.click, + MouseEvent.mouseDown, MouseEvent.mouseUp, MouseEvent.middleClick, MouseEvent.middleMouseDown, + MouseEvent.middleMouseUp, MouseEvent.rightClick, MouseEvent.rightMouseDown, MouseEvent.rightMouseUp, + and MouseEvent.doubleClick events. This parameter is for Adobe AIR only; do not set it for Flash Player content. + clickCountint0(AIR only) Indicates whether or not the mouse event is part of a multi-click sequence. This parameter will be zero for all mouse events other than + MouseEvent.mouseDown, MouseEvent.mouseUp, MouseEvent.middleMouseDown, MouseEvent.middleMouseUp, + MouseEvent.rightMouseDown and MouseEvent.rightMouseUp. Listening for single clicks, double clicks, or any multi-click sequence + is possible with the clickCount parameter. This parameter is for Adobe AIR only; do not set it for Flash Player content. + + Constructor for MouseEvent objects. + + + Creates an Event object that contains information about mouse events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the MouseEvent object and sets the value of each property to match that of the original.A new MouseEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the MouseEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the MouseEvent object.A string that contains all the properties of the MouseEvent object. + + String + Returns a string that contains all the properties of the MouseEvent object. The string is in the following format: +

[MouseEvent type=value bubbles=value cancelable=value ... delta=value]

+ +
updateAfterEvent + Instructs Flash Player or Adobe AIR to render after processing of this event completes, if the display list has been modified. + Instructs Flash Player or Adobe AIR to render after processing of this event completes, if the display list has been modified. + + CLICK + Defines the value of the type property of a click event object.clickString + Defines the value of the type property of a click event object. + +

This event has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDownFor click events, this value is always false.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.click
CONTEXT_MENU + The MouseEvent.CONTEXT_MENU constant defines the value of the + type property of a contextMenu event object.contextMenuString + The MouseEvent.CONTEXT_MENU constant defines the value of the + type property of a contextMenu event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the right mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
DOUBLE_CLICK + Defines the value of the type property of a doubleClick event object.doubleClickString + Defines the value of the type property of a doubleClick event object. The doubleClickEnabled property + must be true for an object to generate the doubleClick event. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDownFor double-click events, this value is always false.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.doubleClick
MIDDLE_CLICK + Defines the value of the type property of a middleClick event object.middleClickString + Defines the value of the type property of a middleClick event object. + +

This event has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDownFor middle-click events, this property is always false.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.middleClick
MIDDLE_MOUSE_DOWN + Defines the value of the type property of a middleMouseDown event object.middleMouseDownString + Defines the value of the type property of a middleMouseDown event object. +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the middle mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.middleMouseDown
MIDDLE_MOUSE_UP + Defines the value of the type property of a middleMouseUp event object.middleMouseUpString + Defines the value of the type property of a middleMouseUp event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the middle mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.middleMouseUp
MOUSE_DOWN + Defines the value of the type property of a mouseDown event object.mouseDownString + Defines the value of the type property of a mouseDown event object. +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows and Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
Please see the MOUSE_MOVE constant's example for an illustration of how to use this constant. + +
flash.display.InteractiveObject.mouseDown
MOUSE_MOVE + Defines the value of the type property of a mouseMove event object.mouseMoveString + Defines the value of the type property of a mouseMove event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
The following example is a simple drawing program. The user can draw on the + main Sprite object or on a smaller rectangular Sprite object. + +

In the constructor, a rectangle innerRect Sprite object is created + and the line style is set to green. The line style for drawing on the + MouseEvent_MOUSE_MOVEExample Sprite container is set to red. Separate event + listeners for the MouseEvent.MOUSE_UP and MouseEvent.MOUSE_DOWN + events are added for the application's main Sprite object and innerRect + Sprite object. In both cases, the mouse down event listener methods move the current drawing + position to the mouse pointer's location and add a listener for the MouseEvent.MOUSE_MOVE + event. When the mouse pointer is moved, the invoked event listener methods follows the pointer and draw + a line using the graphics.LineTo() method. (Note: The innerRect + Sprite object obscures the red lines of the main Sprite object that are drawn behind the rectangle.) + When the MouseEvent.MOUSE_UP event occurs, the listener for the MOUSE_MOVE + event is removed and drawing is stopped.

+ + +package { + import flash.display.Sprite; + import flash.display.Graphics; + import flash.events.MouseEvent; + + public class MouseEvent_MOUSE_MOVEExample extends Sprite { + private var innerRect:Sprite = new Sprite(); + + public function MouseEvent_MOUSE_MOVEExample() { + + graphics.lineStyle(3, 0xFF0000, 1); + stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); + stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + + innerRect.graphics.lineStyle(1, 0x00FF00, 1); + innerRect.graphics.beginFill(0xFFFFFF); + innerRect.graphics.drawRect(10, 10, 200, 200); + innerRect.graphics.endFill(); + innerRect.addEventListener(MouseEvent.MOUSE_DOWN, innerRectMouseDownHandler); + innerRect.addEventListener(MouseEvent.MOUSE_UP, innerRectMouseUpHandler); + addChild(innerRect); + } + + private function mouseDownHandler(event:MouseEvent):void { + graphics.moveTo(event.stageX, event.stageY); + stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function mouseMoveHandler(event:MouseEvent):void { + graphics.lineTo(event.stageX, event.stageY); + } + + private function mouseUpHandler(event:MouseEvent):void { + stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function innerRectMouseDownHandler(event:MouseEvent):void { + innerRect.graphics.moveTo(event.localX, event.localY); + innerRect.addEventListener(MouseEvent.MOUSE_MOVE, innerRectMouseMoveHandler); + } + + private function innerRectMouseMoveHandler(event:MouseEvent):void { + innerRect.graphics.lineTo(event.localX, event.localY); + } + + private function innerRectMouseUpHandler(event:MouseEvent):void { + innerRect.removeEventListener(MouseEvent.MOUSE_MOVE, innerRectMouseMoveHandler); + } + } +} +
flash.display.InteractiveObject.mouseMove
MOUSE_OUT + Defines the value of the type property of a mouseOut event object.mouseOutString + Defines the value of the type property of a mouseOut event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.relatedObjectThe display list object to which the pointing device now points.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.mouseOut
MOUSE_OVER + Defines the value of the type property of a mouseOver event object.mouseOverString + Defines the value of the type property of a mouseOver event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.relatedObjectThe display list object to which the pointing device was pointing.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.mouseOver
MOUSE_UP + Defines the value of the type property of a mouseUp event object.mouseUpString + Defines the value of the type property of a mouseUp event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
Please see the MOUSE_MOVE constant's example for an illustration of how to use this constant. + +
flash.display.InteractiveObject.mouseUp
MOUSE_WHEEL + Defines the value of the type property of a mouseWheel event object.mouseWheelString + Defines the value of the type property of a mouseWheel event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.deltaThe number of lines that that each notch on the mouse wheel represents.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.mouseWheel
RIGHT_CLICK + Defines the value of the type property of a rightClick event object.rightClickString + Defines the value of the type property of a rightClick event object. + +

This event has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDownFor right-click events, this property is always false.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.rightClick
RIGHT_MOUSE_DOWN + Defines the value of the type property of a rightMouseDown event object.rightMouseDownString + Defines the value of the type property of a rightMouseDown event object. +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDownFor right-click events, this property is always true.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.rightMouseDown
RIGHT_MOUSE_UP + Defines the value of the type property of a rightMouseUp event object.rightMouseUpString + Defines the value of the type property of a rightMouseUp event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblestruebuttonDowntrue if the right mouse button is pressed; false otherwise.cancelablefalse; the default behavior cannot be canceled.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.clickCountCount of the number of mouse clicks to indicate whether the event is part of a multi-click sequence.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.rightMouseUp
ROLL_OUT + Defines the value of the type property of a rollOut event object.rollOutString + Defines the value of the type property of a rollOut event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblesfalsebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.relatedObjectThe display list object to which the pointing device now points.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.rollOut
ROLL_OVER + Defines the value of the type property of a rollOver event object.rollOverString + Defines the value of the type property of a rollOver event object. + +

This event has the following properties:

+ PropertyValuealtKeytrue if the Alt key is active (Windows).bubblesfalsebuttonDowntrue if the primary mouse button is pressed; false otherwise.cancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.relatedObjectThe display list object to which the pointing device was pointing.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the pointing device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.rollOver
altKey + Indicates whether the Alt key is active (true) or inactive (false).Boolean + Indicates whether the Alt key is active (true) or inactive (false). + Supported for Windows only. On other operating systems, this property is always set to false. + + buttonDown + Indicates whether the primary mouse button is pressed (true) or not (false).Boolean + Indicates whether the primary mouse button is pressed (true) or not (false). + + clickCount + Indicates whether or not the mouse down event is part of a multi-click sequence.int + Indicates whether or not the mouse down event is part of a multi-click sequence. + This parameter will be zero for all mouse events other than MouseEvent.mouseDown, + MouseEvent.mouseUp, MouseEvent.middleMouseDown, MouseEvent.middleMouseUp, + MouseEvent.rightMouseDown, and MouseEvent.rightMouseUp. Listening + for single clicks, double clicks, or any multi-click sequence is possible with the clickCount parameter. + + For example, an initial MouseEvent.mouseDown and MouseEvent.mouseUp will have a + clickCount of 1, and the second MouseEvent.mouseDown and MouseEvent.mouseUp + in a double-click sequence will have a + clickCount of 2. If the mouse moves sufficiently or the multi-click sequence is + interrupted for some reason, then the next MouseEvent.mouseDown will have a clickCount of 1. + + The doubleClick event will continue to fire as expected. + + commandKey + Indicates whether the command key is activated (Mac only.) + + The value of property commandKey + will have the same value as property ctrlKey on the Mac.Boolean + Indicates whether the command key is activated (Mac only.) + +

The value of property commandKey + will have the same value as property ctrlKey on the Mac. + Always false on Windows or Linux.

+ +
controlKey + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux.Boolean + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux. + + ctrlKey + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false).Boolean + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false). + On Macintosh, indicates whether either the Control key or the Command key is activated. + + delta + Indicates how many lines should be scrolled for each unit the user rotates the + mouse wheel.int + Indicates how many lines should be scrolled for each unit the user rotates the + mouse wheel. A positive delta value indicates an upward scroll; a negative + value indicates a downward scroll. Typical values are 1 to 3, but faster + rotation may produce larger values. This setting depends on the device + and operating system and is usually configurable by the user. This + property applies only to the MouseEvent.mouseWheel event. + + isRelatedObjectInaccessible + If true, the relatedObject property is set to null for + reasons related to security sandboxes.Boolean + If true, the relatedObject property is set to null for + reasons related to security sandboxes. If the nominal value of relatedObject is a reference to a + DisplayObject in another sandbox, relatedObject is set to + null unless there is permission in both directions across this sandbox boundary. Permission is + established by calling Security.allowDomain() from a SWF file, or by providing + a policy file from the server of an image file, and setting the LoaderContext.checkPolicyFile + property when loading the image. + + MouseEvent.relatedObjectSecurity.allowDomain()LoaderContext.checkPolicyFilelocalX + The horizontal coordinate at which the event occurred relative to the containing sprite.Number + The horizontal coordinate at which the event occurred relative to the containing sprite. + + Please see the MOUSE_MOVE constant's example for an illustration of how to use this property. + + localY + The vertical coordinate at which the event occurred relative to the containing sprite.Number + The vertical coordinate at which the event occurred relative to the containing sprite. + + Please see the MOUSE_MOVE constant's example for an illustration of how to use this property. + + relatedObject + A reference to a display list object that is related to the event.flash.display:InteractiveObject + A reference to a display list object that is related to the event. For example, when a mouseOut event occurs, + relatedObject represents the display list object to which the pointing device now points. + This property applies to the mouseOut, mouseOver, rollOut, and rollOver events. +

The value of this property can be null in two circumstances: if there no related object, + or there is a related object, but it is in a security sandbox to which you don't have access. + Use the isRelatedObjectInaccessible() property to determine which of these reasons applies.

+ +
MouseEvent.isRelatedObjectInaccessible
shiftKey + Indicates whether the Shift key is active (true) or inactive + (false).Boolean + Indicates whether the Shift key is active (true) or inactive + (false). + + stageX + The horizontal coordinate at which the event occurred in global Stage coordinates.Number + The horizontal coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localX property is set. + + Please see the MOUSE_MOVE constant's example for an illustration of how to use this property. + + stageY + The vertical coordinate at which the event occurred in global Stage coordinates.Number + The vertical coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localY property is set. + + Please see the MOUSE_MOVE constant's example for an illustration of how to use this property. + +
IEventDispatcher +The IEventDispatcher interface defines methods for adding or removing event listeners, checks +whether specific types of event listeners are registered, and dispatches events. +The IEventDispatcher interface defines methods for adding or removing event listeners, checks +whether specific types of event listeners are registered, and dispatches events. + +

Event targets are an important part of the Flash® Player and Adobe AIR event model. The event target +serves as the focal point for how events flow through the display list hierarchy. +When an event such as a mouse click or a keypress occurs, an event +object is dispatched into the event flow from the root of the display list. The event object makes a +round-trip journey to the event target, which is conceptually divided into three phases: +the capture phase includes the journey from the root to the last node before the event +target's node; the target phase includes only the event target node; and the bubbling +phase includes any subsequent nodes encountered on the return trip to the root of the +display list.

+ +

In general, the easiest way for a user-defined class to gain event dispatching +capabilities is to extend EventDispatcher. If this is impossible (that is, if the class is +already extending another class), you can instead implement the IEventDispatcher interface, +create an EventDispatcher member, and write simple hooks to route calls into the aggregated +EventDispatcher.

+ +
The following example uses the IEventDispatcherExample and + DecoratedDispatcher sample classes to show how the IEventDispatcher class can be + implemented and used. The example accomplishes this by implementing each method of + DecoratedDispatcher in the same manner as in EventDispatcher. + Within the constructor for IEventDispatcherExample, a new instance (named decorDispatcher) of the DecoratedDispatcher class is constructed + and the decorDispatcher variable is used to call + addEventListener() with the custom event doSomething, which is + then handled by didSomething(), which prints a line of text using + trace(). + +package { + import flash.events.Event; + import flash.display.Sprite; + + public class IEventDispatcherExample extends Sprite { + public function IEventDispatcherExample() { + var decorDispatcher:DecoratedDispatcher = new DecoratedDispatcher(); + decorDispatcher.addEventListener("doSomething", didSomething); + decorDispatcher.dispatchEvent(new Event("doSomething")); + } + + public function didSomething(evt:Event):void { + trace(">> didSomething"); + } + } +} + +import flash.events.IEventDispatcher; +import flash.events.EventDispatcher; +import flash.events.Event; + +class DecoratedDispatcher implements IEventDispatcher { + private var dispatcher:EventDispatcher; + + public function DecoratedDispatcher() { + dispatcher = new EventDispatcher(this); + } + + public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void{ + dispatcher.addEventListener(type, listener, useCapture, priority); + } + + public function dispatchEvent(evt:Event):Boolean{ + return dispatcher.dispatchEvent(evt); + } + + public function hasEventListener(type:String):Boolean{ + return dispatcher.hasEventListener(type); + } + + public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void{ + dispatcher.removeEventListener(type, listener, useCapture); + } + + public function willTrigger(type:String):Boolean { + return dispatcher.willTrigger(type); + } +} +
addEventListener + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.typeStringThe type of event. + listenerFunctionThe listener function that processes the event. This function must accept an event object + as its only parameter and must return nothing, as this example shows: +

function(evt:Event):void

+ The function can have any name. +
useCaptureBooleanfalseDetermines whether the listener works in the capture phase or the target + and bubbling phases. If useCapture is set to true, the + listener processes the event only during the capture phase and not in the target or + bubbling phase. If useCapture is false, the listener processes the event only + during the target or bubbling phase. To listen for the event in all three phases, call + addEventListener() twice, once with useCapture set to true, + then again with useCapture set to false. + priorityint0The priority level of the event listener. Priorities are designated by a 32-bit integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners of priority n-1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0. + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or weak. A strong + reference (the default) prevents your listener from being garbage-collected. A weak + reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbge-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's priority, you + must first call removeEventListener(). Then you can register the listener again with the new + priority level.

+

After the listener is registered, subsequent calls to + addEventListener() with a different value for either type or useCapture result in the + creation of a separate listener registration. For example, if you first register a + listener with useCapture set to true, it listens only during the capture phase. If you + call addEventListener() again using the same listener object, but with useCapture set to + false, you have two separate listeners: one that listens during the capture phase, and + another that listens during the target and bubbling phases.

+

You cannot register an event listener for only the target phase or the bubbling phase. Those phases are coupled during registration because bubbling applies only to the ancestors of the target node.

+

When you no longer need an event listener, remove it by calling EventDispatcher.removeEventListener(); otherwise, memory problems might result. Objects + with registered event listeners are not automatically removed from memory because the + garbage collector does not remove objects that still have references.

+

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event + listeners attached to it move along with it.

+

If the event listener is being registered on a node while an event is also being processed on + this node, the event listener is not triggered during the current phase but may be + triggered during a later phase in the event flow, such as the bubbling phase.

+

If an event listener is removed from a node while an event is being processed on the node, it is still triggered by the current actions. After it is removed, the event listener is never invoked again + (unless it is registered again for future processing).

+ +
dispatchEvent + Dispatches an event into the event flow.A value of true unless preventDefault() is called on the event, + in which case it returns false. + + Booleaneventflash.events:EventThe event object dispatched into the event flow. + + Dispatches an event into the event flow. The event target is the + EventDispatcher object upon which dispatchEvent() is called. + + hasEventListener + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event.A value of true if a listener of the specified type is registered; false otherwise. + BooleantypeStringThe type of event. + + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event. This allows you to determine where an EventDispatcher object has altered handling of an event type in the event flow hierarchy. To determine whether + a specific event type will actually trigger an event listener, use IEventDispatcher.willTrigger(). +

The difference between hasEventListener() and willTrigger() is that hasEventListener() examines only the object to which it belongs, whereas willTrigger() examines the entire event flow for the event specified by the type parameter.

+ +
willTrigger()
removeEventListener + Removes a listener from the EventDispatcher object.typeStringThe type of event. + listenerFunctionThe listener object to remove. + useCaptureBooleanfalseSpecifies whether the listener was registered for the capture phase or the target and bubbling phases. If the listener was registered for both the capture phase and the target and bubbling phases, two calls to removeEventListener() are required to remove both: one call with useCapture set to true, and another call with useCapture set to false. + + + Removes a listener from the EventDispatcher object. If there is no matching listener + registered with the EventDispatcher object, a call to this method has no effect. + + willTrigger + Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.A value of true if a listener of the specified type will be triggered; false otherwise. + + BooleantypeStringThe type of event. + + Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. This method returns true if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants. +

The difference between hasEventListener() and willTrigger() is that hasEventListener() examines only the object to which it belongs, whereas willTrigger() examines the entire event flow for the event specified by the type parameter.

+ +
SQLErrorEvent + A SQLErrorEvent instance is dispatched by a SQLConnection instance or SQLStatement instance + when an error occurs while performing a database operation in asynchronous execution mode.flash.events:ErrorEvent + A SQLErrorEvent instance is dispatched by a SQLConnection instance or SQLStatement instance + when an error occurs while performing a database operation in asynchronous execution mode. + The SQLErrorEvent instance + that's passed as an event object to listeners provides access to + information about the cause of the error and the operation that was being attempted. + +

The specific details of the failure can be found on the SQLError object + in the SQLErrorEvent instance's error property.

+ +
flash.errors.SQLErrorflash.data.SQLConnectionflash.data.SQLStatementerrorflash.events:SQLErrorEvent:ERRORflash.events:SQLErrorEventflash.data.SQLConnectionflash.data.SQLStatementflash.errors.SQLErrorSQLErrorEvent + Creates a SQLErrorEvent object to pass as an argument to event listeners.typeString The type of the event, accessible in the type property. + The SQLErrorEvent defines one event type, the error event, + represented by the SQLErrorEvent.ERROR constant. + + bubblesBooleanfalse Determines whether the event object participates in the bubbling + stage of the event flow. The default value is false. + + cancelableBooleanfalseDetermines whether the Event object can be cancelled. + The default value is false. + + errorflash.errors:SQLErrornullThe SQLError object that contains the details of the error. + + Used to create new SQLErrorEvent object. + + + Creates a SQLErrorEvent object to pass as an argument to event listeners. + + flash.errors.SQLError;ERRORclone + Creates a copy of the SQLErrorEvent object and sets the value of each property + to match that of the original.A new SQLErrorEvent object with property values that match those of + the original. + + flash.events:Event + Creates a copy of the SQLErrorEvent object and sets the value of each property + to match that of the original. + + toString + Returns a string that contains all the properties of the SQLErrorEvent object.A string that contains all the properties of the SQLErrorEvent object. + + String + Returns a string that contains all the properties of the SQLErrorEvent object. + The string is in the following format: + +

[SQLErrorEvent type=value bubbles=value + cancelable=value error=value]

+ +

The error value has the following + format: SQLError : message value code=value operation=value

+ +
ERROR + The SQLErrorEvent.ERROR constant defines the value of the + type property of an error event dispatched when a call + to a method of a SQLConnection or SQLStatement instance completes + with an error.errorString + The SQLErrorEvent.ERROR constant defines the value of the + type property of an error event dispatched when a call + to a method of a SQLConnection or SQLStatement instance completes + with an error. + + The error event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.errorA SQLError object containing information about the type of error that occurred and the operation that caused the error.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection or SQLStatement object reporting the error. + + flash.data.SQLConnectionflash.data.SQLStatementflash.errors.SQLErrorerror + A SQLError object containing detailed information about the cause of the error.flash.errors:SQLError + A SQLError object containing detailed information about the cause of the error. + +
ErrorEvent +An object dispatches an ErrorEvent object when an error causes an asynchronous operation +to fail.Event objects for ErrorEvent events. + + flash.events:TextEvent +An object dispatches an ErrorEvent object when an error causes an asynchronous operation +to fail. + +

The ErrorEvent class defines only one type of error event: +ErrorEvent.ERROR. The ErrorEvent class also serves as the base class for +several other error event classes, including the AsyncErrorEvent, IOErrorEvent, +SecurityErrorEvent, SQLErrorEvent, and UncaughtErrorEvent classes.

+ +

You can check for error events that do not have any listeners by +registering a listener for the uncaughtError (UncaughtErrorEvent.UNCAUGHT_ERROR) +event.

+ +

An uncaught error also causes an error dialog box displaying the error event to appear +when content is running in the debugger version of Flash +Player or the AIR Debug Launcher (ADL) application.

+ +
The following example demonstrates the use of a single error handler (errorHandler()) + that captures multiple types of error events. If there is an ioError event, the handler + attempts to load from the network, which then throws a securityError. + +

Note: This example does not work if you have a file named + MissingFile.xml in the same directory as your SWF file.

+ +package { + import flash.display.Sprite; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.events.*; + + public class ErrorEventExample extends Sprite { + private var loader:URLLoader; + private var request:URLRequest; + + public function ErrorEventExample() { + loader = new URLLoader(); + loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler); + + request = new URLRequest(); + loadFromFileSystem(); + } + + private function loadFromFileSystem():void { + request.url = "MissingFile.xml"; + loader.load(request); + } + + private function loadFromNetwork():void { + request.url = "http://www.[yourDomain].com/MissingFile.xml"; + loader.load(request); + } + + private function errorHandler(event:ErrorEvent):void { + trace("errorHandler: " + event); + if(event is IOErrorEvent) { + loadFromNetwork(); + } + } + } +} +
UncaughtErrorEventerrorflash.events:ErrorEvent:ERRORflash.events:ErrorEventErrorEvent + Creates an Event object that contains information about error events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: ErrorEvent.ERROR. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error (supported in Adobe AIR only). + + Constructor for ErrorEvent objects. + + + Creates an Event object that contains information about error events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the ErrorEvent object and sets the value of each property to match that of the original.A new ErrorEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the ErrorEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the ErrorEvent object.A string that contains all the properties of the ErrorEvent object. + + String + Returns a string that contains all the properties of the ErrorEvent object. The string is in the following format: +

[ErrorEvent type=value bubbles=value cancelable=value text=value errorID=value]

+

Note: The errorId value returned by the toString() method is only available for Adobe AIR. + While Flash Player 10.1 supports the errorID property, calling toString() on the ErrorEvent object does + not provide the errorId value in Flash Player.

+ +
ERROR + Defines the value of the type property of an error event object.errorString + Defines the value of the type property of an error event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object experiencing a network operation failure.textText to be displayed as an error message. + +
errorID + Contains the reference number associated with the specific error.int + Contains the reference number associated with the specific error. + For a custom ErrorEvent object, this number is the value from the id + parameter supplied in the constructor. + +
SoftKeyboardTrigger + The SoftKeyboardTrigger class defines the possible values for the triggerType property + of the SoftKeyboardEvent class.Defines the possible values for the triggerType property of the SoftKeyboardEvent class. + Object + The SoftKeyboardTrigger class defines the possible values for the triggerType property + of the SoftKeyboardEvent class. These values indicate what type of action triggered a SoftKeyboard + activation event. + + CONTENT_TRIGGERED + A function call triggered the event.contentTriggeredStringIndicates that a function call invoked the event. + + A function call triggered the event. + + USER_TRIGGERED + A user action triggered the event.userTriggeredStringIndicates that a user action invoked the event. + + A user action triggered the event. Typical user actions that can trigger this event include + explicitly closing the keyboard, or pressing the Back key. + + TransformGestureEvent + The TransformGestureEvent class lets you handle complex movement input events (such as moving fingers across a touch screen) + that the device or operating system interprets as a gesture.provides event handling support for touch movement interaction + + flash.events:GestureEvent + The TransformGestureEvent class lets you handle complex movement input events (such as moving fingers across a touch screen) + that the device or operating system interprets as a gesture. A gesture can have one or more touch points. + When a user interacts with a device such as a mobile phone or tablet with a touch screen, the user typically + touches and moves across the screen with his or her fingers or a pointing device. You can develop applications that respond to + this user interaction with the GestureEvent, PressAndTapGestureEvent, and TransformGestureEvent classes. Create event listeners using the event types defined here, or in + the related GestureEvent and TouchEvent classes. And, use the properties and methods of these classes + to construct event handlers that respond to the user touching the device. +

A device or operating system interprets gesture input. So, different devices or operating systems have different requirements for + individual gesture types. A swipe on one device might require different input movement than a swipe on another device. Refer to the hardware + or operating system documentation to discover how the device or operating system interprets contact as a specific gesture.

+

Use the Multitouch class to determine the current environment's support for touch interaction, and to + manage the support of touch interaction if the current environment supports it.

+

Note: When objects are nested on the display list, touch events target the deepest possible + nested object that is visible in the display list. This object is called the target node. To have a target node's + ancestor (an object containing the target node in the display list) receive notification of a touch event, use + EventDispatcher.addEventListener() on the ancestor node with the type parameter set to the specific + touch event you want to detect.

+

While the user is in contact with the device, the TransformGestureEvent object's scale, rotation, and offset properties are incremental values + from the previous gesture event. For example, as a gesture increases the size of a display object, the scale values might go in sequence 1.03, + 1.01, 1.01, 1.02 indicating the display object scaled 1.0717 times its original size by the end of the gesture.

+

For TransformGestureEvent objects, properties not modified by the current gesture are set to identity values. For example, a pan gesture does not have a rotation + or scale transformation, so the rotation value of the event object is 0, the scaleX and scaleY properties are 1.

+
The following example shows event handling for the GESTURE_ROTATE events. + While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onRotate(evt:TransformGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} + The following example shows how to handle transform gesture events. This example assumes an image is on your local system + called "african_elephant.jpg" and in the same directory as the TransformGestureExample2 class. + This example comes from Christian Cantrell, and is explained in more detail in his quickstart: + Multi-touch and gesture support on the Flash Platform. + + package +{ + import flash.display.Bitmap; + import flash.display.Sprite; + import flash.events.TransformGestureEvent; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.ui.Multitouch; + import flash.ui.MultitouchInputMode; + + [SWF(width=320, height=460, frameRate=24, backgroundColor=0x000000)] + public class TransformGestureExample2 extends Sprite + { + [Embed(source="african_elephant.jpg")] + public var ElephantImage:Class; + public var scaleDebug:TextField; + public var rotateDebug:TextField; + + public function TransformGestureExample2() + { + // Debug + var tf:TextFormat = new TextFormat(); + tf.color = 0xffffff; + tf.font = "Helvetica"; + tf.size = 11; + this.scaleDebug = new TextField(); + this.scaleDebug.width = 310; + this.scaleDebug.defaultTextFormat = tf; + this.scaleDebug.x = 2; + this.scaleDebug.y = 2; + this.stage.addChild(this.scaleDebug); + this.rotateDebug = new TextField(); + this.rotateDebug.width = 310; + this.rotateDebug.defaultTextFormat = tf; + this.rotateDebug.x = 2; + this.rotateDebug.y = 15; + this.stage.addChild(this.rotateDebug); + + var elephantBitmap:Bitmap = new ElephantImage(); + var elephant:Sprite = new Sprite(); + + elephant.addChild(elephantBitmap); + + elephant.x = 160; + elephant.y = 230; + + elephantBitmap.x = (300 - (elephantBitmap.bitmapData.width / 2)) * -1; + elephantBitmap.y = (400 - (elephantBitmap.bitmapData.height / 2)) *-1; + + this.addChild(elephant); + + Multitouch.inputMode = MultitouchInputMode.GESTURE; + elephant.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom); + elephant.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate); + } + + private function onZoom(e:TransformGestureEvent):void + { + this.scaleDebug.text = (e.scaleX + ", " + e.scaleY); + var elephant:Sprite = e.target as Sprite; + elephant.scaleX *= e.scaleX; + elephant.scaleY *= e.scaleY; + } + + private function onRotate(e:TransformGestureEvent):void + { + var elephant:Sprite = e.target as Sprite; + this.rotateDebug.text = String(e.rotation); + elephant.rotation += e.rotation; + } + } +} +
flash.ui.Multitouchflash.events.TouchEventflash.events.GestureEventflash.events.PressAndTapGestureEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()gesturePanflash.events:TransformGestureEvent:GESTURE_PANflash.events:TransformGestureEvent The following example shows event handling for the GESTURE_PAN events. + While the user performs a pan gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onPan(evt:TransformGestureEvent):void { + + evt.target.localX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +flash.display.InteractiveObject.gesturePanflash.events.GesturePhasegestureRotateflash.events:TransformGestureEvent:GESTURE_ROTATEflash.events:TransformGestureEvent The following example shows event handling for the GESTURE_ROTATE events. + While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onRotate(evt:TransformGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +flash.display.InteractiveObject.gestureRotateflash.events.GesturePhasegestureSwipeflash.events:TransformGestureEvent:GESTURE_SWIPEflash.events:TransformGestureEvent The following example shows event handling for the GESTURE_SWIPE events. + While the user performs a swipe gesture on the touch-enabled device, myTextField populates with the phase all, + which is the only phase for swipe events. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onSwipe(evt:TransformGestureEvent):void { + + if (evt.offsetX == 1 ) { + myTextField.text = "right"; + } + if (evt.offsetY == -1) { + myTextField.text = "up"; + } + myTextField.text = evt.phase; + +} +flash.display.InteractiveObject.gestureSwipeflash.events.GesturePhasegestureZoomflash.events:TransformGestureEvent:GESTURE_ZOOMflash.events:TransformGestureEvent The following example shows event handling for the GESTURE_ZOOM events. + While the user performs a zoom gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onZoom(evt:TransformGestureEvent):void { + + evt.target.scaleX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +flash.display.InteractiveObject.gestureZoomflash.events.GesturePhaseTransformGestureEvent + Creates an Event object that contains information about complex multi-touch events, such as + a user sliding his or her finger across a screen.typeString The type of the event. Possible values are: TransformGestureEvent.GESTURE_PAN, + TransformGestureEvent.GESTURE_ROTATE, TransformGestureEvent.GESTURE_SWIPE and TransformGestureEvent.GESTURE_ZOOM. + + bubblesBooleantrue Determines whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + phaseStringnullThis values tracks the beginning, progress, and end of a touch gesture. Possible values are: GesturePhase.BEGIN, + GesturePhase.END, and GesturePhase.UPDATE. + localXNumber0The horizontal coordinate at which the event occurred relative to the containing display object. + localYNumber0The vertical coordinate at which the event occurred relative to the containing display object. + scaleXNumber1.0The horizontal scale of the display object. + scaleYNumber1.0The vertical scale of the display object. + rotationNumber0The current rotation angle, in degrees, of the display object along the z-axis. + offsetXNumber0The horizontal translation of the display object from its original position. + offsetYNumber0The vertical translation of the display object from its original position. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated (Windows or Linux only). + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + commandKeyBooleanfalse(AIR only) Indicates whether the Command key is activated (Mac only). This parameter is for Adobe AIR only; do not set it for Flash Player content. + controlKeyBooleanfalse(AIR only) Indicates whether the Control or Ctrl key is activated. This parameter is for Adobe AIR only; do not set it for Flash Player content. + + Constructor for TransformGestureEvent objects. + + Creates an Event object that contains information about complex multi-touch events, such as + a user sliding his or her finger across a screen. + Event objects are passed as parameters to event listeners. + + + flash.ui.Multitouchflash.events.TouchEventflash.events.GestureEventflash.events.PressAndTapGestureEventflash.events.GesturePhaseflash.events.MouseEventflash.events.EventDispatcher.addEventListener()clone + Creates a copy of the TransformGestureEvent object and sets the value of each property to match that of the original.A new TransformGestureEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the TransformGestureEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the TransformGestureEvent object.A string that contains all the properties of the TransformGestureEvent object. + + String + Returns a string that contains all the properties of the TransformGestureEvent object. The string is in the following format: +

[TransformGestureEvent type=value bubbles=value cancelable=value ... ]

+ +
GESTURE_PAN + Defines the value of the type property of a GESTURE_PAN touch event object.gesturePanString + Defines the value of the type property of a GESTURE_PAN touch event object. + +

The dispatched TransformGestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.phaseThe current phase in the event flow; a value from the GesturePhase class.localXThe horizontal coordinate at which the event occurred relative to the containing display object.localYThe vertical coordinate at which the event occurred relative to the containing display object.scaleXThe horizontal scale of the display object since the previous gesture event. For pan gestures this value is 1.scaleYThe vertical scale of the display object since the previous gesture event. For pan gestures this value is 1.rotationThe current rotation angle, in degrees, of the display object along the z-axis, since the previous gesture event. + For pan gestures this value is 0.offsetXThe horizontal translation of the display object from its position at the previous gesture event.offsetYThe vertical translation of the display object from its position at the previous gesture event.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
The following example shows event handling for the GESTURE_PAN events. + While the user performs a pan gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onPan(evt:TransformGestureEvent):void { + + evt.target.localX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
flash.display.InteractiveObject.gesturePanflash.events.GesturePhase
GESTURE_ROTATE + Defines the value of the type property of a GESTURE_ROTATE touch event object.gestureRotateString + Defines the value of the type property of a GESTURE_ROTATE touch event object. + +

The dispatched TransformGestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.phaseThe current phase in the event flow; a value from the GesturePhase class.localXThe horizontal coordinate at which the event occurred relative to the containing display object.localYThe vertical coordinate at which the event occurred relative to the containing display object.scaleXThe horizontal scale of the display object since the previous gesture event.scaleYThe vertical scale of the display object since the previous gesture event.rotationThe current rotation angle, in degrees, of the display object along the z-axis, since the previous gesture event.offsetXThe horizontal translation of the display object from its position at the previous gesture event.offsetYThe vertical translation of the display object from its position at the previous gesture event.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
The following example shows event handling for the GESTURE_ROTATE events. + While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onRotate(evt:TransformGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
flash.display.InteractiveObject.gestureRotateflash.events.GesturePhase
GESTURE_SWIPE + Defines the value of the type property of a GESTURE_SWIPE touch event object.gestureSwipeString + Defines the value of the type property of a GESTURE_SWIPE touch event object. + +

The dispatched TransformGestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.phaseThe current phase in the event flow. For swipe events, + this value is always all corresponding to the value GesturePhase.ALL once the event is dispatched.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.scaleXThe horizontal scale of the display object. For swipe gestures this value is 1scaleYThe vertical scale of the display object. For swipe gestures this value is 1rotationThe current rotation angle, in degrees, of the display object along the z-axis. For swipe gestures this value is 0offsetXIndicates horizontal direction: 1 for right and -1 for left.offsetYIndicates vertical direction: 1 for down and -1 for up.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
The following example shows event handling for the GESTURE_SWIPE events. + While the user performs a swipe gesture on the touch-enabled device, myTextField populates with the phase all, + which is the only phase for swipe events. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onSwipe(evt:TransformGestureEvent):void { + + if (evt.offsetX == 1 ) { + myTextField.text = "right"; + } + if (evt.offsetY == -1) { + myTextField.text = "up"; + } + myTextField.text = evt.phase; + +} +
flash.display.InteractiveObject.gestureSwipeflash.events.GesturePhase
GESTURE_ZOOM + Defines the value of the type property of a GESTURE_ZOOM touch event object.gestureZoomString + Defines the value of the type property of a GESTURE_ZOOM touch event object. + +

The dispatched TransformGestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.phaseThe current phase in the event flow; a value from the GesturePhase class.localXThe horizontal coordinate at which the event occurred relative to the containing display object.localYThe vertical coordinate at which the event occurred relative to the containing display object.scaleXThe horizontal scale of the display object since the previous gesture event.scaleYThe vertical scale of the display object since the previous gesture event.rotationThe current rotation angle, in degrees, of the display object along the z-axis, since the previous gesture event.offsetXThe horizontal translation of the display object from its position at the previous gesture event.offsetYThe vertical translation of the display object from its position at the previous gesture event.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
The following example shows event handling for the GESTURE_ZOOM events. + While the user performs a zoom gesture on the touch-enabled device, myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onZoom(evt:TransformGestureEvent):void { + + evt.target.scaleX++; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +
flash.display.InteractiveObject.gestureZoomflash.events.GesturePhase
offsetX + The horizontal translation of the display object, since the previous gesture event.Number + The horizontal translation of the display object, since the previous gesture event. + + offsetY + The vertical translation of the display object, since the previous gesture event.Number + The vertical translation of the display object, since the previous gesture event. + + rotation + The current rotation angle, in degrees, of the display object along the z-axis, since the previous gesture event.Number + The current rotation angle, in degrees, of the display object along the z-axis, since the previous gesture event. + + scaleX + The horizontal scale of the display object, since the previous gesture event.Number + The horizontal scale of the display object, since the previous gesture event. + + scaleY + The vertical scale of the display object, since the previous gesture event.Number + The vertical scale of the display object, since the previous gesture event. + +
NativeDragEvent + Native drag events are dispatched by the interactive objects involved in a + drag-and-drop operation.flash.events:MouseEvent + Native drag events are dispatched by the interactive objects involved in a + drag-and-drop operation. + +

The initiating object dispatches:

+
  • nativeDragStart — When the drag operation begins.
  • nativeDragUpdate — While the drag operation is in progress.
  • nativeDragComplete — When the user releases the dragged item (whether or not + the drop was accepted).
+ +

The initiating object is the interactive object passed that is to the NativeDragManager object in the call + to NativeDragManager.doDrag() which began the drag operation.

+ +

Potential target interactive objects dispatches:

+
  • nativeDragEnter — When the drag gesture passes within the object boundary.
  • nativeDragOver — While the drag gesture remains within the object boundary.
  • nativeDragExit — When the drag gesture leaves the object boundary.
  • nativeDragDrop — When the user releases the dragged item over the object and the + object has accepted the drop with an earlier call to NativeDragManager.acceptDragDrop().
+ +

Typically a handler for the nativeDragEnter or + nativeDragOver event evaluates the data being dragged, + along with the drag actions allowed, to determine whether an interactive object + can accept a drop. To specify that an interactive object is an eligible target, the + event handler must call the NativeDragManager.acceptDrop()function, + passing in a reference to the object. If the user releases + the mouse button over the designated object, the object becomes the drop target and dispatches + the nativeDragDrop event.

+ +

Any InteractiveObject type object can be a drag initiator or a drop target.

+ +
flash.desktop.NativeDragManagerflash.desktop.Clipboardflash.desktop.NativeDragOptionsflash.desktop.NativeDragActionsflash.display.InteractiveObjectnativeDragCompleteflash.events:NativeDragEvent:NATIVE_DRAG_COMPLETEflash.events:NativeDragEventDispatched by the source InteractiveObject when a drag-and-drop gesture ends. + + flash.display.InteractiveObject.nativeDragCompleteflash.desktop.NativeDragActionsnativeDragDropflash.events:NativeDragEvent:NATIVE_DRAG_DROPflash.events:NativeDragEventDispatched by InteractiveObjects when a drag-and-drop gesture ends over the object. + + flash.display.InteractiveObject.nativeDragDropnativeDragEnterflash.events:NativeDragEvent:NATIVE_DRAG_ENTERflash.events:NativeDragEventDispatched by InteractiveObjects when a drag-and-drop gesture enters the object bounds. + + flash.display.InteractiveObject.nativeDragEnternativeDragExitflash.events:NativeDragEvent:NATIVE_DRAG_EXITflash.events:NativeDragEventDispatched by InteractiveObjects when a drag-and-drop gesture leaves the object bounds. + + flash.display.InteractiveObject.nativeDragExitnativeDragOverflash.events:NativeDragEvent:NATIVE_DRAG_OVERflash.events:NativeDragEventDispatched by InteractiveObjects while a drag-and-drop gesture hovers over the object. + + flash.display.InteractiveObject.nativeDragOvernativeDragStartflash.events:NativeDragEvent:NATIVE_DRAG_STARTflash.events:NativeDragEventDispatched by the source InteractiveObject at the begining of a native drag-and-drop gesture. + + flash.display.InteractiveObject.nativeDragStartnativeDragUpdateflash.events:NativeDragEvent:NATIVE_DRAG_UPDATEflash.events:NativeDragEventDispatched by the source InteractiveObject while a drag-and-drop gesture is underway. + + flash.display.InteractiveObject.nativeDragUpdateNativeDragEvent + Creates an Event object with specific information relevant to native drag-and-drop events.typeString The type of the event. Possible values are: + NativeDragEvent.NATIVE_DRAG_START, + NativeDragEvent.NATIVE_DRAG_UPDATE, + NativeDragEvent.NATIVE_DRAG_ENTER, + NativeDragEvent.NATIVE_DRAG_OVER, + NativeDragEvent.NATIVE_DRAG_EXIT, + NativeDragEvent.NATIVE_DRAG_DROP, + and NativeDragEvent.NATIVE_DRAG_COMPLETE. + + bubblesBooleanfalseIndicates whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleantrueIndicates whether the Event object can be canceled. + localXNumberunknownThe horizontal coordinate at which the event occurred relative to the containing sprite. + localYNumberunknownThe vertical coordinate at which the event occurred relative to the containing sprite. + relatedObjectflash.display:InteractiveObjectnullThe related interactive display object. + clipboardflash.desktop:ClipboardnullThe Clipboard object containing the data to be transfered. + allowedActionsflash.desktop:NativeDragOptionsnullThe NativeDragOptions object defining the allowed actions (move, copy, and link). + dropActionStringnullThe current action. + + controlKeyBooleanfalseIndicates whether the Control key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated. + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + commandKeyBooleanfalseIndicates whether the Command key is activated. + + + Creates an Event object with specific information relevant to native drag-and-drop events. + +

Event objects are passed as parameters to event listeners. Dispatching a native drag event + does not trigger the associated behavior.

+ +
clone + Creates a copy of this NativeDragEvent object.A new NativeDragEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of this NativeDragEvent object. + + toString + Formats the properties of this NativeDragEvent object as a string.The properties of this NativeDragEvent as a string. + String + Formats the properties of this NativeDragEvent object as a string. + +

The string is in the following format:

+

[NativeDragEvent type=value bubbles=value cancelable=value ... commandKey=value]

+ +
NATIVE_DRAG_COMPLETE + NativeDragEvent.NATIVE_DRAG_COMPLETE defines the value of the + type property of a nativeDragComplete event object.nativeDragCompleteStringDispatched by the source InteractiveObject when a drag-and-drop gesture ends. + + + NativeDragEvent.NATIVE_DRAG_COMPLETE defines the value of the + type property of a nativeDragComplete event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelablefalse; there is no default behavior to cancel.clipboardThe Clipboard object containing the dragged data.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragCompleteflash.desktop.NativeDragActions
NATIVE_DRAG_DROP + NativeDragEvent.NATIVE_DRAG_DROP defines the value of the type + property of a nativeDragDrop event object.nativeDragDropStringDispatched by InteractiveObjects when a drag-and-drop gesture ends over the object. + + + NativeDragEvent.NATIVE_DRAG_DROP defines the value of the type + property of a nativeDragDrop event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelabletrue; canceling this event cancels the drag operation.clipboardThe Clipboard object containing the dragged data. The clipboard can be read even if the object dispatching this event is not in the same security domain as the initiator.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragDrop
NATIVE_DRAG_ENTER + NativeDragEvent.NATIVE_DRAG_ENTER defines the value of the + type property of a nativeDragEnter event object.nativeDragEnterStringDispatched by InteractiveObjects when a drag-and-drop gesture enters the object bounds. + + + NativeDragEvent.NATIVE_DRAG_ENTER defines the value of the + type property of a nativeDragEnter event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelablefalse; there is no default behavior to cancel.clipboardThe Clipboard object containing the dragged data. The clipboard can be read only if the object dispatching this event is in the same security domain as the initiator.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragEnter
NATIVE_DRAG_EXIT + NativeDragEvent.NATIVE_DRAG_EXIT defines the value of the type + property of a nativeDragExit event object.nativeDragExitStringDispatched by InteractiveObjects when a drag-and-drop gesture leaves the object bounds. + + + NativeDragEvent.NATIVE_DRAG_EXIT defines the value of the type + property of a nativeDragExit event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelablefalse; there is no default behavior to cancel.clipboardThe Clipboard object containing the dragged data. The clipboard can be read only if the object dispatching this event is in the same security domain as the initiator.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragExit
NATIVE_DRAG_OVER + NativeDragEvent.NATIVE_DRAG_OVER defines the value of the type + property of a nativeDragOver event object.nativeDragOverStringDispatched by InteractiveObjects while a drag-and-drop gesture hovers over the object. + + + NativeDragEvent.NATIVE_DRAG_OVER defines the value of the type + property of a nativeDragOver event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelabletrue; canceling this event cancels the drag operation.clipboardThe Clipboard object containing the dragged data. The clipboard can be read only if the object dispatching this event is in the same security domain as the initiator.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragOver
NATIVE_DRAG_START + NativeDragEvent.NATIVE_DRAG_START defines the value of the type + property of a nativeDragStart event object.nativeDragStartStringDispatched by the source InteractiveObject at the begining of a native drag-and-drop gesture. + + + NativeDragEvent.NATIVE_DRAG_START defines the value of the type + property of a nativeDragStart event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelabletrue; canceling this event cancels the drag operation.clipboardThe Clipboard object containing the dragged data.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragStart
NATIVE_DRAG_UPDATE + NativeDragEvent.NATIVE_DRAG_UPDATE defines the value of the + type property of a nativeDragUpdate event object.nativeDragUpdateStringDispatched by the source InteractiveObject while a drag-and-drop gesture is underway. + + + NativeDragEvent.NATIVE_DRAG_UPDATE defines the value of the + type property of a nativeDragUpdate event object. + +

This event has the following properties:

+ PropertyValueallowedActionsThe NativeDragOptions object specifying the actions relevant to this drag operation.bubblestruecancelablefalse; there is no default behavior to cancel.clipboardThe Clipboard object containing the dragged data.dropActionThe action chosen by the drop target (or none if no action was set). + +
flash.display.InteractiveObject.nativeDragUpdate
allowedActions + The NativeDragOptions object specifying the actions that are allowed by the + display object that initiated this drag operation.flash.desktop:NativeDragOptions + The NativeDragOptions object specifying the actions that are allowed by the + display object that initiated this drag operation. + + flash.desktop.NativeDragOptionsclipboard + The Clipboard object containing the data in this drag operation.flash.desktop:Clipboard + The Clipboard object containing the data in this drag operation. + +

If the object dispatching the event is not in the same security domain + as the initiating object, then the clipboard can be read only in the handler for + a nativeDragDrop event.

+ +
flash.desktop.Clipboard
dropAction + The current action.String + The current action. In the nativeDragComplete event, the dropAction + property reports the final action. + +
PressAndTapGestureEvent + The PressAndTapGestureEvent class lets you handle press-and-tap gesture on touch-enabled devices.provides event handling support for press and tap gesture + + flash.events:GestureEvent + The PressAndTapGestureEvent class lets you handle press-and-tap gesture on touch-enabled devices. + Objects that inherit properties from the InteractiveObject class capture the primary touch point + (press) and a secondary point (tap) in the dispatched event object. + The press-and-tap gesture is typically used to raise a context-sensitive popup menu. + The following example shows event handling for the GESTURE_PRESS_AND_TAP event. + While the user performs a press-and-tap gesture, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(PressAndTapGestureEvent.GESTURE_PRESS_AND_TAP , onPressAndTap ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onPressAndTap(evt:PressAndTapGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +flash.ui.Multitouchflash.display.InteractiveObjectflash.events.TouchEventflash.events.GestureEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()gesturePressAndTapflash.events:PressAndTapGestureEvent:GESTURE_PRESS_AND_TAPflash.events:PressAndTapGestureEventflash.display.InteractiveObject.gesturePressAndTapflash.events.GesturePhasePressAndTapGestureEvent + Creates an Event object that contains information about complex multi-touch events, such as + a user raising a context-sensitive popup menu.typeString The type of the event: PressAndTapGestureEvent.GESTURE_PRESS_AND_TAP. + + bubblesBooleantrue Determines whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + phaseStringnullThis values tracks the beginning, progress, and end of a touch gesture. Possible values are: GesturePhase.BEGIN, + GesturePhase.END, GesturePhase.UPDATE, or GesturePhase.ALL. + localXNumber0The horizontal coordinate at which the event occurred relative to the containing display object. + localYNumber0The vertical coordinate at which the event occurred relative to the containing display object. + tapLocalXNumber0The horizontal coordinate at which the event occurred relative to the containing interactive object. + tapLocalYNumber0The vertical coordinate at which the event occurred relative to the containing interactive object. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated (Windows or Linux only). + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + commandKeyBooleanfalse(AIR only) Indicates whether the Command key is activated (Mac only). This parameter is for Adobe AIR only; do not set it for Flash Player content. + controlKeyBooleanfalse(AIR only) Indicates whether the Control or Ctrl key is activated. This parameter is for Adobe AIR only; do not set it for Flash Player content. + + Constructor for PressAndTapGestureEvent objects. + + Creates an Event object that contains information about complex multi-touch events, such as + a user raising a context-sensitive popup menu. + Event objects are passed as parameters to event listeners. + + + flash.ui.Multitouchflash.events.TouchEventflash.events.GestureEventflash.events.GesturePhaseflash.events.MouseEventflash.events.EventDispatcher.addEventListener()clone + Creates a copy of the PressAndTapGestureEvent object and sets the value of each property to match that of the original.A new PressAndTapGestureEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the PressAndTapGestureEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the PressAndTapGestureEvent object.A string that contains all the properties of the PressAndTapGestureEvent object. + + String + Returns a string that contains all the properties of the PressAndTapGestureEvent object. The string is in the following format: +

[PressAndTapGestureEvent type=value bubbles=value cancelable=value ... ]

+ +
GESTURE_PRESS_AND_TAP + Defines the value of the type property of a GESTURE_PRESS_AND_TAP touch event object.gesturePressAndTapString + Defines the value of the type property of a GESTURE_PRESS_AND_TAP touch event object. + +

The dispatched PressAndTapGestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase as the event passes through the object hierarchy; a numeric value indicating the event is captured (1), at the target (2), or bubbling (3).localXThe horizontal coordinate at which the event occurred relative to the containing display object.localYThe vertical coordinate at which the event occurred relative to the containing display object.phaseThe current phase in the event flow; a value from the GesturePhase class.Possible values are: + GesturePhase.BEGIN, GesturePhase.UPDATE, GesturePhase.END, or GesturePhase.ALL. + A press-and-tap gesture either generates a GesturePhase.BEGIN, GesturePhase.UPDATE, GesturePhase.END sequence + or the gesture generates a single GesturePhase.ALL phase.shiftKeytrue if the Shift key is active; false if it is inactive.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.tapLocalXThe horizontal coordinate at which the event occurred relative to the containing interactive object.tapLocalYThe vertical coordinate at which the event occurred relative to the containing interactive object.tapStageXThe horizontal coordinate at which the tap touch occurred in global Stage coordinates.tapStageYThe vertical coordinate at which the tap touch occurred in global Stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.gesturePressAndTapflash.events.GesturePhase
tapLocalX + The horizontal coordinate at which the event occurred relative to the containing interactive object.Number + The horizontal coordinate at which the event occurred relative to the containing interactive object. + + tapLocalY + The vertical coordinate at which the event occurred relative to the containing interactive object.Number + The vertical coordinate at which the event occurred relative to the containing interactive object. + + tapStageX + The horizontal coordinate at which the tap touch occurred in global Stage coordinates.Number + The horizontal coordinate at which the tap touch occurred in global Stage coordinates. + This property is calculated when the tapLocalX property is set. + + tapStageY + The vertical coordinate at which the tap touch occurred in global Stage coordinates.Number + The vertical coordinate at which the tap touch occurred in global Stage coordinates. + This property is calculated when the tapLocalX property is set. + +
GeolocationEvent +A Geolocation object dispatches GeolocationEvent objects when it receives updates from the location sensor installed on the device.flash.events:Event +A Geolocation object dispatches GeolocationEvent objects when it receives updates from the location sensor installed on the device. + +updateflash.events:GeolocationEvent:UPDATEflash.events:GeolocationEventGeolocationEvent + Creates a GeolocationEvent object that contains information about the + location of the device.typeString Specifies the type of the event. Event listeners can access this information + through the inherited type property. There is only one type of update + event: GeolocationEvent.UPDATE. + + bubblesBooleanfalseIndicates whether the event is a bubbling event. Event listeners can access + this information through the inherited bubbles property. + + cancelableBooleanfalseDetermines whether the event object can be canceled. Event listeners can access + this information through the inherited cancelable property. + + latitudeNumber0Returns the latitude in degrees. The values have the following range: (-90 <= Lat <= +90). + + longitudeNumber0Returns the longitude in degrees. The values have the following range: (-180 <= Long < +180). + + altitudeNumber0Returns the altitude in meters. + + hAccuracyNumber0Returns the horizontal accuracy in meters. + + vAccuracyNumber0Returns the vertical accuracy in meters. + + speedNumber0 Returns the speed in meters/second. + + headingNumber0Returns the direction of movement (with respect to True North) in integer degrees. + + timestampNumber0Specifies the timestamp of the geolocation update. + + Constructor for GeolocationEvent objects. + + + Creates a GeolocationEvent object that contains information about the + location of the device. Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the GeolocationEvent object and sets the value of each property to match that of the original.A new GeolocationEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the GeolocationEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the GeolocationEvent object.A string that contains all the properties of the GeolocationEvent object. + String + Returns a string that contains all the properties of the GeolocationEvent object. + The string is in the following format: + +

[GeolocationEvent type=value bubbles=value cancelable=value status=value]

+ +
UPDATE + Defines the value of the type property of a GeolocationEvent event object.updateString + Defines the value of the type property of a GeolocationEvent event object. +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe Geolocation object receiving data. + + +
altitude + The altitude in meters.Number + The altitude in meters. + +

If altitude is not supported by the device, then this property is set to NaN.

+ +
heading + The direction of movement (with respect to true north) in integer degrees.Number + The direction of movement (with respect to true north) in integer degrees. This is not the same as + "bearing", which returns the direction of movement with respect to another point. + +

Note: On Android devices, heading is not supported. The value of the heading + property is always NaN (Not a Number).

+ +
horizontalAccuracy + The horizontal accuracy in meters.Number + The horizontal accuracy in meters. + + latitude + The latitude in degrees.Number + The latitude in degrees. The latitude values have the following range: (-90 <= latitude <= 90). Negative latitude is + south and positive latitude is north. + + longitude + The longitude in degrees.Number + The longitude in degrees. The longitude values have the following range: (-180 <= longitude < 180). Negative longitude is + west and positive longitude is east. + + speed + The speed in meters/second.Number + The speed in meters/second. + + timestamp + The number of milliseconds at the time of the event since the runtime was initialized.Number + The number of milliseconds at the time of the event since the runtime was initialized. + For example, if the device captures geolocation data 4 seconds after the application initializes, + then the timestamp property of the event is set to 4000. + + verticalAccuracy + The vertical accuracy in meters.Number + The vertical accuracy in meters. + +
MediaEvent + CameraRoll and CameraUI classes dispatch MediaEvent objects when a media stream + is available.flash.events:Event + CameraRoll and CameraUI classes dispatch MediaEvent objects when a media stream + is available. + +

The CameraRoll class dispatches a select-type MediaEvent object when the user selects an image. + The CameraUI class dispatches a complete-type MediaEvent object when an image or video captured from the + device camera is returned.

+ + +
CameraRollCameraUIcompleteflash.events:MediaEvent:COMPLETEflash.events:MediaEventThe complete event type. + selectflash.events:MediaEvent:SELECTflash.events:MediaEventThe select event type. + MediaEvent + Creates an MediaEvent object that contains information about the available media file.typeStringThe type of the event. + bubblesBooleanfalseDetermines whether the Event object bubbles. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + dataflash.media:MediaPromisenullThe MediaPromise object corresponding to the selected image. + + Constructor for MediaEvent objects. + + + Creates an MediaEvent object that contains information about the available media file. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of an MediaEvent object and sets the value of each property to match that of + the original.a new MediaEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of an MediaEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of MediaEvent object.a new MediaEvent object with property values that match those of the original. + + String + Returns a string that contains all the properties of MediaEvent object. The following format is used: + +

[MediaEvent type=value bubbles=value cancelable=value + data=value ]

+ +
COMPLETE + A constant for the complete MediaEvent.completeStringThe complete event type. + + A constant for the complete MediaEvent. + +

Defines the value of the type property of a MediaEvent event object. + This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.dataThe MediaPromise object of the available media instance. + +
SELECT + A constant for the select MediaEvent.selectStringThe select event type. + + A constant for the select MediaEvent. + +

Defines the value of the type property of a MediaEvent event object. + This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.dataThe MediaPromise object of the available media instance. + +
data + The MediaPromise object for the available media file.flash.media:MediaPromise + The MediaPromise object for the available media file. + +
StageVideoEvent + A StageVideo object dispatches a StageVideoEvent object after the attachNetStream() method + of the StageVideo object and the play() method of + the attached NetStream object have both been called.Event objects for StageVideo events. + + flash.events:Event + A StageVideo object dispatches a StageVideoEvent object after the attachNetStream() method + of the StageVideo object and the play() method of + the attached NetStream object have both been called. Also, depending on the platform, + any change in the playing status can result in dispatching the event. + The one type of StageVideoEvent is StageVideoEvent.RENDER_STATE. + + renderStateflash.events:StageVideoEvent:RENDER_STATEflash.events:StageVideoEventflash.events.StageVideoEvent.RENDER_STATEflash.events.StageVideoEvent.RENDER_STATUS_UNAVAILABLEflash.events.StageVideoEvent.RENDER_STATUS_SOFTWAREflash.events.StageVideoEvent.RENDER_STATUS_ACCELERATEDStageVideoEvent + Creates an Event object that contains information about StageVideo events.typeString The type of the event. Event listeners can access this information through the inherited type property. The one type of StageVideoEvent is StageVideoEvent.RENDER_STATE. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + statusStringnullIndicates the status of the target StageVideo object. + colorSpaceStringnullThe color space used by the video being displayed. + + Constructor for StageVideoEvent objects. + + Creates an Event object that contains information about StageVideo events. + Event objects are passed as parameters to event listeners. + + flash.media.StageVideoflash.display.Stage.stageVideosflash.events.StageVideoEvent.RENDER_STATERENDER_STATE + The StageVideoEvent.RENDER_STATE constant defines the value of the type property of a renderState event object.renderStateString + The StageVideoEvent.RENDER_STATE constant defines the value of the type property of a renderState event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.colorSpaceThe available color spaces for displaying the video.currentTargetThe object that is actively processing the StageVideoEvent + object with an event listener.statusIndicates whether the video is being rendered (decoded and displayed) by hardware or software, or not at all.targetThe StageVideo object that changed state. + +
flash.events.StageVideoEvent.RENDER_STATEflash.events.StageVideoEvent.RENDER_STATUS_UNAVAILABLEflash.events.StageVideoEvent.RENDER_STATUS_SOFTWAREflash.events.StageVideoEvent.RENDER_STATUS_ACCELERATED
RENDER_STATUS_ACCELERATED + Indicates that hardware is decoding and displaying the video.acceleratedString + Indicates that hardware is decoding and displaying the video. + +

This value is one of the possible values of the StageVideoEvent object status property.

+ +
status
RENDER_STATUS_SOFTWARE + Indicates that software is decoding and displaying the video.softwareString + Indicates that software is decoding and displaying the video. + +

This value is one of the possible values of the StageVideoEvent object status property.

+ +

For example, if the platform does not support hardware decoding and display of the audio or video codec + of the video, the + StageVideoEvent object has this status value.

+ +
status
RENDER_STATUS_UNAVAILABLE + Indicates that displaying the video using the StageVideo object is not possible.unavailableString + Indicates that displaying the video using the StageVideo object is not possible. + +

This value is one of the possible values of the StageVideoEvent object status property.

+ +

For example, consider a platform that does not support decoding and displaying the video's audio or video codec + with either software or hardware. In this case, the StageVideoEvent object has this status value.

+ +

This status value also is used if no hardware decoders are available. This situation + can occur in AIR for TV. For backward compatibility with its previous releases, AIR for TV + allows you to use a Video object for hardware decoding and display. By using a Video object, you are using + the underlying hardware decoder and therefore you have one less StageVideo object available for use. + Note that using a StageVideo object for hardware video decoding and display is recommended.

+ +
status
colorSpace + The color space used by the video being displayed in the StageVideo object.String + The color space used by the video being displayed in the StageVideo object. + + flash.media.StageVideostatus + The status of the StageVideo object.String + The status of the StageVideo object. + + flash.events.StageVideoEvent.RENDER_STATUS_UNAVAILABLEflash.events.StageVideoEvent.RENDER_STATUS_SOFTWAREflash.events.StageVideoEvent.RENDER_STATUS_ACCELERATED
LocationChangeEvent + An HTMLLoader or StageWebView object dispatches a LocationChangeEvent object when a new page loads.flash.events:Event + An HTMLLoader or StageWebView object dispatches a LocationChangeEvent object when a new page loads. + +

There are two types of LocationChangeEvent:

+
  • LocationChangeEvent.LOCATION_CHANGING: dispatched before a change initiated via the + content displayed in a StageWebView object. Can be canceled.
  • LocationChangeEvent.LOCATION_CHANGE: dispatched after every location change. Cannot be canceled.
+ +
StageWebViewLocationChangeEvent + Creates a LocationChangeEvent object.typeStringbubblesBooleanfalsecancelableBooleanfalselocationStringnull + Creates a LocationChangeEvent object. + + clone + flash.events:Event + toString + Returns a string that contains all the properties of the LocationChangeEvent object.String + Returns a string that contains all the properties of the LocationChangeEvent object. + The string is in the following format: +

[LocationChangeEvent type=value bubbles=value cancelable=value + eventPhase=value location=value

+ +
LOCATION_CHANGE + Dispatched after every location change.locationChangeString + Dispatched after every location change. + + LOCATION_CHANGING + The LOCATION_CHANGING constant defines the value of the type property LocationChangeEvent object + dispatched before a change in page location.locationChangingString + The LOCATION_CHANGING constant defines the value of the type property LocationChangeEvent object + dispatched before a change in page location. + + location + The destination URL of the change.String + The destination URL of the change. + +
NetDataEvent +A NetStream object dispatches a NetDataEvent object when a data message is encountered in the media stream.flash.events:Event +A NetStream object dispatches a NetDataEvent object when a data message is encountered in the media stream. + +

A NetDataEvent is dispatched for the following messages:

+
  • onCuePoint
  • onImageData
  • onMetaData
  • onPlayStatus (for code NetStream.Play.Complete)
  • onTextData
  • onXMPData
+ +
NetDataEvent + Creates an event object that contains information about media data events.typeString The type of the event. Event listeners can access this information through the + inherited type property. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + timestampNumber0timestamp of the data message + infoObjectnulldata message object + + + Creates an event object that contains information about media data events. + Event objects are passed as parameters to Event listeners. + + clone + Creates a copy of an NetDataEvent object and sets the value of each property to match that of + the original.A new NetDataEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of an NetDataEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the NetDataEvent object.A string that contains all the properties of the NetMediaEvent object. + String + Returns a string that contains all the properties of the NetDataEvent object. The following + format is used: +

[NetDataEvent type=value bubbles=value cancelable=value + timestamp=value]

+ +
MEDIA_TYPE_DATA + The NetDataEvent.MEDIA_TYPE_DATA constant defines the value of the type property of the NetDataEvent object + dispatched when a data message in the media stream is encountered by the NetStream object.mediaTypeDataString + The NetDataEvent.MEDIA_TYPE_DATA constant defines the value of the type property of the NetDataEvent object + dispatched when a data message in the media stream is encountered by the NetStream object. + + info + A data object describing the message.Object + A data object describing the message. The info object has two properties: + info.handler and info.args. + info.handler is the handler name, such as "onMetaData" or "onXMPData". + info.args is an array of arguments. + + timestamp + The timestamp of the data message in the media stream.Number + The timestamp of the data message in the media stream. + +
NativeProcessExitEvent + This event is dispatched by the NativeProcess object when the process exits.flash.events:Event + This event is dispatched by the NativeProcess object when the process exits. It is possible that + this event will never be dispatched. For example, if the child process outlives the AIR application that created it, + the event will not dispatch. + + flash.desktop.NativeProcessexitflash.events:NativeProcessExitEvent:EXITflash.events:NativeProcessExitEventNativeProcessExitEvent + Creates a NativeProcessExitEvent which contains specific information regarding a NativeProcess's exit code + + typeString The type of the event, accessible as Event.type. + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage + of the event flow. The default value is false. + cancelableBooleanfalseDetermines whether the Event object can be canceled. The default values is false. + exitCodeNumberunknownNumber that the process returned to the operating system during exit. + + + Creates a NativeProcessExitEvent which contains specific information regarding a NativeProcess's exit code + + clone + Creates a copy of the NativeProcessExitEvent object and sets each property's value to match that of the original.A new NativeProcessExitEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the NativeProcessExitEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the NativeProcessExitEvent object.A string that contains all the properties of the ProgressEvent object. + + String + Returns a string that contains all the properties of the NativeProcessExitEvent object. The string is in the following format: +

[NativeProcessExitEvent type=value bubbles=value cancelable=value exitCode=value]

+ +
EXIT + Defines the value of the type property of a exit event object.exitString + Defines the value of the type property of a exit event object. + + exitCode + The exit code that the native process returned to the host operating system when exiting.Number + The exit code that the native process returned to the host operating system when exiting. + If the AIR application terminates the process by calling the exit() + method of the NativeProcess object, the exitCode property is set to NaN. + NOTE: on windows operating systems if the process has not exited but the runtime is exiting or + an error occurred this value may be set to 259 (STILL_ACTIVE). To avoid confusion of this + condition, do not use 259 as a return code in a native process. + +
DNSResolverEvent + The DNSResolverEvent class represents the results of a Domain Name System (DNS) lookup operation.flash.events:Event + The DNSResolverEvent class represents the results of a Domain Name System (DNS) lookup operation. + +

Use the DNSResolver lookup() method to initiate a DNS query. Resource records + returned by the query are placed in the resourceRecords array of this DNSResolverEvent object.

+ +
DNSResolverlookupflash.events:DNSResolverEvent:LOOKUPflash.events:DNSResolverEventDispatched by a DNSResolver object when a look-up operation finishes. + + DNSResolverEvent + Creates an DNSResolverEvent object that contains the results of a DNS lookup operation.typeString The type of the event. Possible values are:DNSResolverEvent.LOOKUP + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + hostStringThe query string, such as a host name, IP address, or service locator used in the call to + the lookup() method of the DNSResolver class for which the new event is a response. + resourceRecordsArraynullA list of the returned DNS resource records. + + Creates an DNSResolverEvent object that contains the results of a DNS lookup operation. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the DNSResolverEvent object and sets the value of each property to match that of the original.A new ServerSocketConnectEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the DNSResolverEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the DNSResolverEvent object.A string that contains all the properties of the ProgressEvent object. + String + Returns a string that contains all the properties of the DNSResolverEvent object. The string is in the following format: +

[DNSResolverEvent type=value bubbles=value cancelable=value host=value resourceRecords=value]

+ +
LOOKUP + Defines the value of the type property of a lookup event object.lookupStringDispatched by a DNSResolver object when a look-up operation finishes. + + + Defines the value of the type property of a lookup event object. + + host + The query string, such as a host name, IP address, or service locator used in the call to + the lookup() method of the DNSResolver class for which this event is a response.StringThe query string used in the look-up operation. + + + The query string, such as a host name, IP address, or service locator used in the call to + the lookup() method of the DNSResolver class for which this event is a response. + + resourceRecords + An array containing the resource records returned by the DNS lookup operation.Array + An array containing the resource records returned by the DNS lookup operation. + +
Event + The Event class is used as the base class for the creation of Event objects, + which are passed as parameters to event listeners when an event occurs.Event object base class. + Object + The Event class is used as the base class for the creation of Event objects, + which are passed as parameters to event listeners when an event occurs. + +

The properties of the Event class carry basic information about an event, such as + the event's type or whether the event's default behavior can be canceled. For many + events, such as the events represented by the Event class constants, this basic information + is sufficient. Other events, however, may require more detailed information. Events associated + with a mouse click, for example, need to include additional information about the location of + the click event and whether any keys were pressed during the click event. You can pass such additional + information to event listeners by extending the Event class, which is what + the MouseEvent class does. ActionScript 3.0 API defines several Event subclasses for common + events that require additional information. Events associated with each of the Event + subclasses are described in the documentation for each class.

+ +

The methods of the Event class can be used in event listener functions to affect the + behavior of the event object. Some events have an associated default behavior. For example, + the doubleClick event has an associated default behavior that highlights + the word under the mouse pointer at the time of the event. + Your event listener can cancel this + behavior by calling the preventDefault() method. + You can also make the current + event listener the last one to process an event by calling the stopPropagation() + or stopImmediatePropagation() method.

+

Other sources of information include:

+
  • A useful description about the timing of events, code execution, and rendering at runtime in Ted Patrick's blog entry: + Flash Player Mental Model - The Elastic Racetrack.
  • A blog entry by Johannes Tacskovics about the timing of frame events, such as ENTER_FRAME, EXIT_FRAME: + The MovieClip Lifecycle.
  • An article by Trevor McCauley about the order of ActionScript operations: + Order of Operations in ActionScript.
  • A blog entry by Matt Przybylski on creating custom events: + AS3: Custom Events.
+ + +
The following example uses the EventExample class and the + Square custom class to demonstrate how to manage event bubbling. + +package { + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + + public class EventExample extends Sprite { + + public function EventExample() { + var square_0:Square = new Square(300, 0x336633); + addChild(square_0); + + var square_1:Square = new Square(250, 0x669966); + square_0.addChild(square_1); + + var square_2:Square = new Square(200, 0x66CC66); + square_1.addChild(square_2); + + var square_3:Square = new Square(150, 0xAA0000); + square_3.shouldBubble = false; + square_2.addChild(square_3); + + var square_4:Square = new Square(100, 0x66FF66); + square_3.addChild(square_4); + + var square_5:Square = new Square(50, 0xCC0000); + square_5.shouldBubble = false; + square_4.addChild(square_5); + + this.addEventListener(MouseEvent.CLICK, clickHandler); + } + + private function clickHandler(e:Event):void { + trace(">> stage: " + e.type + " event from " + e.target.name + " called on " + this.name); + trace(">> --------------------------------------------"); + } + } +} + +import flash.display.Sprite; +import flash.events.Event; +import flash.events.MouseEvent; + +class Square extends Sprite { + private var sideLen:int; + private var color:Number; + public var shouldBubble:Boolean = true; + + public function Square(sideLen:int, color:Number) { + this.sideLen = sideLen; + this.color = color; + init(); + draw(); + } + + private function init():void { + buttonMode = true; + this.addEventListener(MouseEvent.CLICK, firstClickHandler); + this.addEventListener(MouseEvent.CLICK, secondClickHandler); + this.addEventListener(MouseEvent.CLICK, thirdClickHandler); + } + + private function draw():void { + this.graphics.beginFill(color); + this.graphics.drawRect(0, 0, sideLen, sideLen); + } + + private function firstClickHandler(e:Event):void { + trace(">> 1e: " + e.type + " event from " + e.target.name + " called on " + this.name); + if(!shouldBubble) { + e.stopPropagation(); + } + } + + private function secondClickHandler(e:Event):void { + trace(">> 2e: " + e.type + " event from " + e.target.name + " called on " + this.name); + if(!shouldBubble) { + e.stopImmediatePropagation(); + trace(">> --------------------------------------------"); + } + } + + private function thirdClickHandler(e:Event):void { + trace(">> 3e: " + e.type + " event from " + e.target.name + " called on " + this.name); + } +} + The following example creates an interactive demonstration of + the difference between ADDED and ADDED_TO_STAGE events, + as well as the difference between REMOVED and REMOVED_FROM_STAGE + events. Clicking a sprite will remove it from the stage as well as everything nested within it. + For example, clicking the largest sprite will cause a REMOVED event + as well as three REMOVED_FROM_STAGE events to fire. + + package { + import flash.display.Sprite; + import flash.events.*; + + public class EventExample2 extends Sprite { + public function EventExample2():void { + var parentSprite:Sprite = createSprite("parentSprite",200); + var childSprite:Sprite = createSprite("childSprite",100); + var childOfChildSprite:Sprite = createSprite("childOfChildSprite",50); + + trace(":: Adding to Stage ::"); + this.addChild(parentSprite); + trace(":: Adding to Stage ::"); + parentSprite.addChild(childSprite); + trace(":: Adding to Stage ::"); + childSprite.addChild(childOfChildSprite); + } + private function createSprite(name:String,size:uint):Sprite { + trace(":: Creating Sprite ::"); + var newSprite:Sprite = new Sprite(); + newSprite.name = name; + newSprite.graphics.beginFill(0xFFFFFF * Math.random(),1); + newSprite.graphics.drawRect(0,0,size,size); + newSprite.graphics.endFill(); + newSprite.addEventListener(Event.ADDED, spriteAdded); + newSprite.addEventListener(Event.ADDED_TO_STAGE, spriteAddedToStage); + newSprite.addEventListener(Event.REMOVED, spriteRemoved); + newSprite.addEventListener(Event.REMOVED_FROM_STAGE, spriteRemovedFromStage); + newSprite.addEventListener(MouseEvent.CLICK, remove); + return newSprite; + } + private function remove(event:Event) { + if(event.target == event.currentTarget) { + trace(":: Removing Clicked Sprite ::"); + var target:Sprite = Sprite(event.target); + target.parent.removeChild(target); + } + } + private function spriteRemovedFromStage(event:Event):void { + trace("REMOVED_FROM_STAGE: " + event.target.name + " : " + event.currentTarget.name); + } + private function spriteRemoved(event:Event):void { + trace("REMOVED: " + event.target.name + " from " + event.currentTarget.name); + } + private function spriteAddedToStage(event:Event):void { + trace("ADDED_TO_STAGE: " + event.target.name + " : " + event.currentTarget.name); + } + private function spriteAdded(event:Event):void { + trace("ADDED: " + event.target.name + " within " + event.currentTarget.name); + } + } +} +
flash.events.EventDispatcheractivateflash.events:Event:ACTIVATEflash.events:Eventflash.events.EventDispatcher.activateDEACTIVATEaddedToStageflash.events:Event:ADDED_TO_STAGEflash.events:Eventflash.display.DisplayObject.addedToStageADDEDREMOVEDREMOVED_FROM_STAGEaddedflash.events:Event:ADDEDflash.events:Eventflash.display.DisplayObject.addedADDED_TO_STAGEREMOVEDREMOVED_FROM_STAGEcancelflash.events:Event:CANCELflash.events:Eventflash.net.FileReference.cancelchangeflash.events:Event:CHANGEflash.events:Eventflash.text.TextField.changeflash.events.TextEvent.TEXT_INPUTcopyflash.events:Event:CLEARflash.events:Eventflash.display.InteractiveObject.clearcloseflash.events:Event:CLOSEflash.events:Eventflash.net.Socket.closeflash.net.XMLSocket.closeflash.display.NativeWindow.closeclosingflash.events:Event:CLOSINGflash.events:Eventflash.display.NativeWindow.closingcompleteflash.events:Event:COMPLETEflash.events:Eventflash.display.LoaderInfo.completeflash.html.HTMLLoader.completeflash.media.Sound.completeflash.net.FileReference.completeflash.net.URLLoader.completeflash.net.URLStream.completeconnectflash.events:Event:CONNECTflash.events:Eventflash.net.Socket.connectflash.net.XMLSocket.connectcopyflash.events:Event:COPYflash.events:Eventflash.display.InteractiveObject.copycutflash.events:Event:CUTflash.events:Eventflash.display.InteractiveObject.cutdeactivateflash.events:Event:DEACTIVATEflash.events:Eventflash.events.EventDispatcher.deactivateACTIVATEdisplayingflash.events:Event:DISPLAYINGflash.events:Eventflash.display.NativeMenu.displayingflash.display.NativeMenuItem.displayingenterFrameflash.events:Event:ENTER_FRAMEflash.events:Eventflash.display.DisplayObject.enterFrameexitingflash.events:Event:EXITINGflash.events:Eventflash.desktop.NativeApplication.exitingexitFrameflash.events:Event:EXIT_FRAMEflash.events:Eventflash.display.DisplayObject.exitFrameframeConstructedflash.events:Event:FRAME_CONSTRUCTEDflash.events:Eventflash.display.DisplayObject.frameConstructedfullScreenflash.events:Event:FULLSCREENflash.events:Eventflash.display.Stage.fullScreenhtmlBoundsChangeflash.events:Event:HTML_BOUNDS_CHANGEflash.events:EventhtmlBoundsChange eventhtmlDOMInitializeflash.events:Event:HTML_DOM_INITIALIZEflash.events:EventhtmlDOMInitialize eventhtmlRenderflash.events:Event:HTML_RENDERflash.events:EventhtmlRender eventid3flash.events:Event:ID3flash.events:Eventflash.media.Sound.id3initflash.events:Event:INITflash.events:Eventflash.display.LoaderInfo.initlocationChangeflash.events:Event:LOCATION_CHANGEflash.events:EventlocationChange eventmouseLeaveflash.events:Event:MOUSE_LEAVEflash.events:Eventflash.display.Stage.mouseLeaveflash.events.MouseEventnetworkChangeflash.events:Event:NETWORK_CHANGEflash.events:Eventflash.desktop.NativeApplication.networkChangeopenflash.events:Event:OPENflash.events:Eventflash.display.LoaderInfo.openflash.media.Sound.openflash.net.FileReference.openflash.net.URLLoader.openflash.net.URLStream.openpasteflash.events:Event:PASTEflash.events:Eventflash.display.InteractiveObject.pasteflash.events.Eventflash.events:Event:PREPARINGflash.events:Eventflash.display.NativeMenu.preparingflash.display.NativeMenuItem.preparingremovedFromStageflash.events:Event:REMOVED_FROM_STAGEflash.events:Eventflash.display.DisplayObject.removedFromStageADDEDREMOVEDADDED_TO_STAGEremovedflash.events:Event:REMOVEDflash.events:Eventflash.display.DisplayObject.removedADDEDADDED_TO_STAGEREMOVED_FROM_STAGErenderflash.events:Event:RENDERflash.events:Eventflash.display.DisplayObject.renderflash.display.Stage.invalidate()resizeflash.events:Event:RESIZEflash.events:Eventflash.display.Stage.resizescrollflash.events:Event:SCROLLflash.events:Eventflash.text.TextField.scrollflash.html.HTMLLoader.scrollselectAllflash.events:Event:SELECT_ALLflash.events:Eventflash.display.InteractiveObject.selectAllselectflash.events:Event:SELECTflash.events:Eventflash.net.FileReference.selectflash.display.NativeMenu.selectflash.display.NativeMenuItem.selectsoundCompleteflash.events:Event:SOUND_COMPLETEflash.events:Eventflash.media.SoundChannel.soundCompleteflash.events.Eventflash.events:Event:STANDARD_ERROR_CLOSEflash.events:Eventflash.events.Eventflash.events:Event:STANDARD_INPUT_CLOSEflash.events:Eventflash.events.Eventflash.events:Event:STANDARD_OUTPUT_CLOSEflash.events:EventtabChildrenChangeflash.events:Event:TAB_CHILDREN_CHANGEflash.events:Eventflash.display.InteractiveObject.tabChildrenChangetabEnabledChangeflash.events:Event:TAB_ENABLED_CHANGEflash.events:Eventflash.display.InteractiveObject.tabEnabledChangetabIndexChangeflash.events:Event:TAB_INDEX_CHANGEflash.events:Eventflash.display.InteractiveObject.tabIndexChangetextInteractionModeChangeflash.events:Event:TEXT_INTERACTION_MODE_CHANGEflash.events:Eventflash.text.TextField.textInteractionModeChangeunloadflash.events:Event:UNLOADflash.events:Eventflash.display.LoaderInfo.unloaduserIdleflash.events:Event:USER_IDLEflash.events:Eventflash.desktop.NativeApplication.userIdleuserIdleflash.events:Event:USER_PRESENTflash.events:Eventflash.desktop.NativeApplication.userPresentEvent + Creates an Event object to pass as a parameter to event listeners.typeString The type of the event, accessible as Event.type. + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. The default value is false. + cancelableBooleanfalseDetermines whether the Event object can be canceled. The default values is false. + + Used to create new Event object. + + + Creates an Event object to pass as a parameter to event listeners. + + clone + Duplicates an instance of an Event subclass.A new Event object that is identical to the original. + flash.events:Event + Duplicates an instance of an Event subclass. + +

Returns a new Event object that is a copy of the original instance of the Event object. + You do not normally call clone(); the EventDispatcher class calls it automatically + when you redispatch an event—that is, when you call dispatchEvent(event) from a handler + that is handling event.

+ +

The new Event object includes all the properties of the original.

+ +

When creating your own custom Event class, you must override the + inherited Event.clone() method in order for it to duplicate the + properties of your custom class. If you do not set all the properties that you add + in your event subclass, those properties will not have the correct values when listeners + handle the redispatched event.

+ +

In this example, PingEvent is a subclass of Event + and therefore implements its own version of clone().

+ + + class PingEvent extends Event { + var URL:String; + + public override function clone():Event { + return new PingEvent(type, bubbles, cancelable, URL); + } + } + + +
formatToString + A utility function for implementing the toString() method in custom + ActionScript 3.0 Event classes.The name of your custom Event class and the String value of your ...arguments + parameter. + + StringclassNameStringThe name of your custom Event class. In the previous example, + the className parameter is PingEvent. + + argumentsThe properties of the Event class and the + properties that you add in your custom Event class. In the previous example, the ...arguments + parameter includes type, bubbles, cancelable, + eventPhase, and URL. + + + A utility function for implementing the toString() method in custom + ActionScript 3.0 Event classes. Overriding the + toString() method is recommended, but not required. + +
+	 class PingEvent extends Event {
+	  var URL:String;
+	 
+	 public override function toString():String { 
+	  return formatToString("PingEvent", "type", "bubbles", "cancelable", "eventPhase", "URL"); 
+	    }
+	 }
+	 
+ + + +
isDefaultPrevented + Checks whether the preventDefault() method has been called on the event.If preventDefault() has been called, returns true; otherwise, + returns false. + + Boolean + Checks whether the preventDefault() method has been called on the event. If the + preventDefault() method has been called, + returns true; otherwise, returns false. + + flash.events.Event.preventDefault()preventDefault + Cancels an event's default behavior if that behavior can be canceled. + Cancels an event's default behavior if that behavior can be canceled. + +

Many events have associated behaviors that are carried out by default. + For example, if a user types a character + into a text field, the default behavior is that the character is + displayed in the text field. Because the TextEvent.TEXT_INPUT + event's default behavior can be canceled, you can use the preventDefault() + method to prevent the character from appearing. + +

+ +

An example of a behavior that is not cancelable is the default behavior associated with + the Event.REMOVED event, which is generated whenever Flash Player is about to + remove a display object from the display list. The default behavior (removing the element) + cannot be canceled, so the preventDefault() method has no effect on this + default behavior.

+ +

You can use the Event.cancelable property to check whether you can prevent + the default behavior associated with a particular event. If the value of + Event.cancelable is true, then preventDefault() can + be used to cancel the event; otherwise, preventDefault() has no effect.

+ +
flash.events.Event.isDefaultPrevented()Event.cancelable
stopImmediatePropagation + Prevents processing of any event listeners in the current node and any subsequent nodes in + the event flow. + Prevents processing of any event listeners in the current node and any subsequent nodes in + the event flow. This method takes effect immediately, and it affects event listeners + in the current node. In contrast, the stopPropagation() method doesn't take + effect until all the event listeners in the current node finish processing. + +

Note: This method does not cancel the behavior associated with this event; see preventDefault() for that functionality.

+ + + +
flash.events.Event.stopPropagation()flash.events.Event.preventDefault()
stopPropagation + Prevents processing of any event listeners in nodes subsequent to the current node in the + event flow. + Prevents processing of any event listeners in nodes subsequent to the current node in the + event flow. This method does not affect any event listeners in the current node + (currentTarget). In contrast, the stopImmediatePropagation() method + prevents processing of event listeners in both the current node and subsequent nodes. + Additional calls to this method have no effect. This method can be called in any phase + of the event flow. + +

Note: This method does not cancel the behavior associated with this event; see preventDefault() for that functionality.

+ + + +
flash.events.Event.stopImmediatePropagation()flash.events.Event.preventDefault()
toString + Returns a string containing all the properties of the Event object.A string containing all the properties of the Event object. + + String + Returns a string containing all the properties of the Event object. The string is in the following format: +

[Event type=value bubbles=value cancelable=value]

+ +
ACTIVATE + The ACTIVATE constant defines the value of the type property of an activate event object.activateString + The ACTIVATE constant defines the value of the type property of an activate event object. +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

AIR for TV devices never automatically dispatch this event. You can, however, dispatch it manually.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the activate event. + +
flash.events.EventDispatcher.activateDEACTIVATE
ADDED_TO_STAGE + The Event.ADDED_TO_STAGE constant defines the value of the type + property of an addedToStage event object.addedToStageString + The Event.ADDED_TO_STAGE constant defines the value of the type + property of an addedToStage event object. + + + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe DisplayObject instance being added to the on stage display list, + either directly or through the addition of a sub tree in which the DisplayObject instance is contained. + If the DisplayObject instance is being directly added, the added event occurs before this event. + +
flash.display.DisplayObject.addedToStageADDEDREMOVEDREMOVED_FROM_STAGE
ADDED + The Event.ADDED constant defines the value of the type property of + an added event object.addedString + The Event.ADDED constant defines the value of the type property of + an added event object. + + + +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe DisplayObject instance being added to the display list. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.DisplayObject.addedADDED_TO_STAGEREMOVEDREMOVED_FROM_STAGE
CANCEL + The Event.CANCEL constant defines the value of the type property of a cancel event object.cancelString + The Event.CANCEL constant defines the value of the type property of a cancel event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetA reference to the object on which the operation is canceled. +
flash.net.FileReference.cancel
CHANGE + The Event.CHANGE constant defines the value of the type property of a change event object.changeString + The Event.CHANGE constant defines the value of the type property of a change event object. + +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object that has had its value modified. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.text.TextField.changeflash.events.TextEvent.TEXT_INPUT
CLEAR + The Event.CLEAR constant defines the value of the type property + of a clear event object.clearString + The Event.CLEAR constant defines the value of the type property + of a clear event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny InteractiveObject instance with a listener registered for the clear event. + +

Note: TextField objects do not dispatch clear, copy, cut, paste, + or selectAll events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. + You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands + (or their keyboard equivalents) does not generate clear, copy, cut, paste, + or selectAll events. However, other classes that extend the InteractiveObject class, including components built + using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus.

+ +
flash.display.InteractiveObject.clear
CLOSE + The Event.CLOSE constant defines the value of the type property of a close event object.closeString + The Event.CLOSE constant defines the value of the type property of a close event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object whose connection has been closed. + +
flash.net.Socket.closeflash.net.XMLSocket.closeflash.display.NativeWindow.close
CLOSING + The Event.CLOSING constant defines the value of the + type property of a closing event object.closingString + The Event.CLOSING constant defines the value of the + type property of a closing event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelabletrue; canceling this event object stops the close operation.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object whose connection is to be closed. + +
flash.display.NativeWindow.closing
COMPLETE + The Event.COMPLETE constant defines the value of the type property of a complete event object.completeString + The Event.COMPLETE constant defines the value of the type property of a complete event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe network object that has completed loading. + + +
flash.display.LoaderInfo.completeflash.html.HTMLLoader.completeflash.media.Sound.completeflash.net.FileReference.completeflash.net.URLLoader.completeflash.net.URLStream.complete
CONNECT + The Event.CONNECT constant defines the value of the type property of a connect event object.connectString + The Event.CONNECT constant defines the value of the type property of a connect event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Socket or XMLSocket object that has established a network connection. + +
flash.net.Socket.connectflash.net.XMLSocket.connect
COPY + Defines the value of the type property of a copy event object.copyString + Defines the value of the type property of a copy event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny InteractiveObject instance with a listener registered for the copy event. + +

Note: TextField objects do not dispatch clear, copy, cut, paste, + or selectAll events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. + You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands + (or their keyboard equivalents) does not generate clear, copy, cut, paste, + or selectAll events. However, other classes that extend the InteractiveObject class, including components built + using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus.

+ +
flash.display.InteractiveObject.copy
CUT + Defines the value of the type property of a cut event object.cutString + Defines the value of the type property of a cut event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny InteractiveObject instance with a listener registered for the cut event. + +

Note: TextField objects do not dispatch clear, copy, cut, paste, + or selectAll events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. + You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands + (or their keyboard equivalents) does not generate clear, copy, cut, paste, + or selectAll events. However, other classes that extend the InteractiveObject class, including components built + using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus.

+ +
flash.display.InteractiveObject.cut
DEACTIVATE + The Event.DEACTIVATE constant defines the value of the type property of a deactivate event object.deactivateString + The Event.DEACTIVATE constant defines the value of the type property of a deactivate event object. +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

AIR for TV devices never automatically dispatch this event. You can, however, dispatch it manually.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the deactivate event. + +
flash.events.EventDispatcher.deactivateACTIVATE
DISPLAYING + The Event.DISPLAYING constant defines the value of the type property of a displaying event object.displayingString + The Event.DISPLAYING constant defines the value of the type property of a displaying event object. +

Note: This event does not go through a "capture phase" + and is dispatched directly to the target, whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalsecurrentTargetThe object that is actively processing the Event + object with an event listener.targetThe object that is about to be displayed. + +
flash.display.NativeMenu.displayingflash.display.NativeMenuItem.displaying
ENTER_FRAME + The Event.ENTER_FRAME constant defines the value of the type property of an enterFrame event object.enterFrameString + The Event.ENTER_FRAME constant defines the value of the type property of an enterFrame event object. +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the enterFrame event. + +
flash.display.DisplayObject.enterFrame
EXITING + The Event.EXITING constant defines the value of the type property of an exiting event object.exitingString + The Event.EXITING constant defines the value of the type property of an exiting event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelabletrue; canceling this event object stops the exit operation.currentTargetThe NativeApplication object.targetThe NativeApplication object. + +
flash.desktop.NativeApplication.exiting
EXIT_FRAME + The Event.EXIT_FRAME constant defines the value of the type property of an exitFrame event object.exitFrameString + The Event.EXIT_FRAME constant defines the value of the type property of an exitFrame event object. +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the enterFrame event. + +
flash.display.DisplayObject.exitFrame
FRAME_CONSTRUCTED + The Event.FRAME_CONSTRUCTED constant defines the value of the type property of an frameConstructed event object.frameConstructedString + The Event.FRAME_CONSTRUCTED constant defines the value of the type property of an frameConstructed event object. + +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the frameConstructed event. + +
flash.display.DisplayObject.frameConstructed
FULLSCREEN + The Event.FULL_SCREEN constant defines the value of the type property of a fullScreen event object.fullScreenString + The Event.FULL_SCREEN constant defines the value of the type property of a fullScreen event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Stage object. + +
flash.display.Stage.fullScreen
HTML_BOUNDS_CHANGE + The Event.HTML_BOUNDS_CHANGE constant defines the value of the type property of an htmlBoundsChange event object.htmlBoundsChangeString + The Event.HTML_BOUNDS_CHANGE constant defines the value of the type property of an htmlBoundsChange event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe HTMLLoader object.targetThe HTMLLoader object. + +
htmlBoundsChange event
HTML_DOM_INITIALIZE + The Event.HTML_DOM_INITIALIZE constant defines the value of the type property + of an htmlDOMInitialize event object.htmlDOMInitializeString + The Event.HTML_DOM_INITIALIZE constant defines the value of the type property + of an htmlDOMInitialize event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe HTMLLoader object.targetThe HTMLLoader object. + +
htmlDOMInitialize event
HTML_RENDER + The Event.HTML_RENDER constant defines the value of the type property of an htmlRender event object.htmlRenderString + The Event.HTML_RENDER constant defines the value of the type property of an htmlRender event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe HTMLLoader object.targetThe HTMLLoader object. + +
htmlRender event
ID3 + The Event.ID3 constant defines the value of the type property of an id3 event object.id3String + The Event.ID3 constant defines the value of the type property of an id3 event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Sound object loading the MP3 for which ID3 data is now available. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.media.Sound.id3
INIT + The Event.INIT constant defines the value of the type property of an init event object.initString + The Event.INIT constant defines the value of the type property of an init event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe LoaderInfo object associated with the SWF file being loaded. + +
flash.display.LoaderInfo.init
LOCATION_CHANGE + The Event.LOCATION_CHANGE constant defines the value of the type property of a locationChange event object.locationChangeString + The Event.LOCATION_CHANGE constant defines the value of the type property of a locationChange event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe HTMLLoader object.targetThe HTMLLoader object. + +
locationChange event
MOUSE_LEAVE + The Event.MOUSE_LEAVE constant defines the value of the type property of a mouseLeave event object.mouseLeaveString + The Event.MOUSE_LEAVE constant defines the value of the type property of a mouseLeave event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Stage object. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.Stage.mouseLeaveflash.events.MouseEvent
NETWORK_CHANGE + The Event.NETWORK_CHANGE constant defines the value of the type property of a networkChange event object.networkChangeString + The Event.NETWORK_CHANGE constant defines the value of the type property of a networkChange event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe NativeApplication object. + +
flash.desktop.NativeApplication.networkChange
OPEN + The Event.OPEN constant defines the value of the type property of an open event object.openString + The Event.OPEN constant defines the value of the type property of an open event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe network object that has opened a connection. + +
flash.display.LoaderInfo.openflash.media.Sound.openflash.net.FileReference.openflash.net.URLLoader.openflash.net.URLStream.open
PASTE + The Event.PASTE constant defines the value of the type property of a paste event object.pasteString + The Event.PASTE constant defines the value of the type property of a paste event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny InteractiveObject instance with a listener registered for the paste event. + +

Note: TextField objects do not dispatch clear, copy, cut, paste, + or selectAll events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. + You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands + (or their keyboard equivalents) does not generate clear, copy, cut, paste, + or selectAll events. However, other classes that extend the InteractiveObject class, including components built + using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus.

+ +
flash.display.InteractiveObject.paste
PREPARING + The Event.PREPARING constant defines the value of the type property of a preparing event object.preparingString + The Event.PREPARING constant defines the value of the type property of a preparing event object. +

Note: This event does not go through a "capture phase" + and is dispatched directly to the target, whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalsecurrentTargetThe object that dispatched this event.targetThe object that dispatched this event. + +
flash.display.NativeMenu.preparingflash.display.NativeMenuItem.preparing
REMOVED_FROM_STAGE + The Event.REMOVED_FROM_STAGE constant defines the value of the type + property of a removedFromStage event object.removedFromStageString + The Event.REMOVED_FROM_STAGE constant defines the value of the type + property of a removedFromStage event object. + + + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe DisplayObject instance being removed from the on stage display list, + either directly or through the removal of a sub tree in which the DisplayObject instance is contained. + If the DisplayObject instance is being directly removed, the removed event occurs before this event. + +
flash.display.DisplayObject.removedFromStageADDEDREMOVEDADDED_TO_STAGE
REMOVED + The Event.REMOVED constant defines the value of the type property of + a removed event object.removedString + The Event.REMOVED constant defines the value of the type property of + a removed event object. + + + +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe DisplayObject instance to be removed from the display list. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.DisplayObject.removedADDEDADDED_TO_STAGEREMOVED_FROM_STAGE
RENDER + The Event.RENDER constant defines the value of the type property of a render event object.renderString + The Event.RENDER constant defines the value of the type property of a render event object. +

Note: This event has neither a "capture phase" nor a "bubble phase", + which means that event listeners must be added directly to any potential targets, + whether the target is on the display list or not.

+

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; the default behavior cannot be canceled.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny DisplayObject instance with a listener registered for the render event. + +
flash.display.DisplayObject.renderflash.display.Stage.invalidate()
RESIZE + The Event.RESIZE constant defines the value of the type property of a resize event object.resizeString + The Event.RESIZE constant defines the value of the type property of a resize event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Stage object. + +
flash.display.Stage.resize
SCROLL + The Event.SCROLL constant defines the value of the type property of a scroll event object.scrollString + The Event.SCROLL constant defines the value of the type property of a scroll event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe TextField object that has been scrolled. + The target property is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.text.TextField.scrollflash.html.HTMLLoader.scroll
SELECT_ALL + The Event.SELECT_ALL constant defines the value of the type property of a selectAll event object.selectAllString + The Event.SELECT_ALL constant defines the value of the type property of a selectAll event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetAny InteractiveObject instance with a listener registered for the selectAll event. + +

Note: TextField objects do not dispatch clear, copy, cut, paste, + or selectAll events. TextField objects always include Cut, Copy, Paste, Clear, and Select All commands in the context menu. + You cannot remove these commands from the context menu for TextField objects. For TextField objects, selecting these commands + (or their keyboard equivalents) does not generate clear, copy, cut, paste, + or selectAll events. However, other classes that extend the InteractiveObject class, including components built + using the Flash Text Engine (FTE), will dispatch these events in response to user actions such as keyboard shortcuts and context menus.

+ +
flash.display.InteractiveObject.selectAll
SELECT + The Event.SELECT constant defines the value of the type property of a select event object.selectString + The Event.SELECT constant defines the value of the type property of a select event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object on which an item has been selected. + +
flash.net.FileReference.selectflash.display.NativeMenu.selectflash.display.NativeMenuItem.select
SOUND_COMPLETE + The Event.SOUND_COMPLETE constant defines the value of the type property of a soundComplete event object.soundCompleteString + The Event.SOUND_COMPLETE constant defines the value of the type property of a soundComplete event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe SoundChannel object in which a sound has finished playing. + +
flash.media.SoundChannel.soundComplete
STANDARD_ERROR_CLOSE + The Event.STANDARD_ERROR_CLOSE constant defines the value of the type property of a standardErrorClose event object.standardErrorCloseString + The Event.STANDARD_ERROR_CLOSE constant defines the value of the type property of a standardErrorClose event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.targetThe NativeProcess object. + +
STANDARD_INPUT_CLOSE + The Event.STANDARD_INPUT_CLOSE constant defines the value of the type property of a standardInputClose event object.standardInputCloseString + The Event.STANDARD_INPUT_CLOSE constant defines the value of the type property of a standardInputClose event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.targetThe NativeProcess object. + +
STANDARD_OUTPUT_CLOSE + The Event.STANDARD_OUTPUT_CLOSE constant defines the value of the type property of a standardOutputClose event object.standardOutputCloseString + The Event.STANDARD_OUTPUT_CLOSE constant defines the value of the type property of a standardOutputClose event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.targetThe NativeProcess object. + +
TAB_CHILDREN_CHANGE + The Event.TAB_CHILDREN_CHANGE constant defines the value of the type property of a tabChildrenChange event object.tabChildrenChangeString + The Event.TAB_CHILDREN_CHANGE constant defines the value of the type property of a tabChildrenChange event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object whose tabChildren flag has changed. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.tabChildrenChange
TAB_ENABLED_CHANGE + The Event.TAB_ENABLED_CHANGE constant defines the value of the type + property of a tabEnabledChange event object.tabEnabledChangeString + The Event.TAB_ENABLED_CHANGE constant defines the value of the type + property of a tabEnabledChange event object. + + + +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe InteractiveObject whose tabEnabled flag has changed. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.tabEnabledChange
TAB_INDEX_CHANGE + The Event.TAB_INDEX_CHANGE constant defines the value of the + type property of a tabIndexChange event object.tabIndexChangeString + The Event.TAB_INDEX_CHANGE constant defines the value of the + type property of a tabIndexChange event object. + + + +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object whose tabIndex has changed. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.tabIndexChange
TEXT_INTERACTION_MODE_CHANGE + The Event.TEXT_INTERACTION_MODE_CHANGE constant defines the value of the type property of a interaction mode event object.textInteractionModeChangeString + The Event.TEXT_INTERACTION_MODE_CHANGE constant defines the value of the type property of a interaction mode event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe TextField object whose interaction mode property is changed. For example on Android, one can change the interaction mode to SELECTION via context menu. + The target property is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.text.TextField.textInteractionModeChange
UNLOAD + The Event.UNLOAD constant defines the value of the type property of an unload event object.unloadString + The Event.UNLOAD constant defines the value of the type property of an unload event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe LoaderInfo object associated with the SWF file being unloaded or replaced. + +
flash.display.LoaderInfo.unload
USER_IDLE + The Event.USER_IDLE constant defines the value of the type property of a userIdle event object.userIdleString + The Event.USER_IDLE constant defines the value of the type property of a userIdle event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.targetThe NativeApplication object. + +
flash.desktop.NativeApplication.userIdle
USER_PRESENT + The Event.USER_PRESENT constant defines the value of the type property of a userPresent event object.userPresentString + The Event.USER_PRESENT constant defines the value of the type property of a userPresent event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.targetThe NativeApplication object. + +
flash.desktop.NativeApplication.userPresent
bubbles + Indicates whether an event is a bubbling event.Boolean + Indicates whether an event is a bubbling event. If the event can bubble, + this value is true; otherwise it is false. + + + +

When an event occurs, it moves through the three phases of the event flow: the capture + phase, which flows from the top of the display list hierarchy to the node just before the + target node; the target phase, which comprises the target node; and the bubbling phase, + which flows from the node subsequent to the target node back up the display list hierarchy.

+ +

Some events, such as the activate and unload events, do not + have a bubbling phase. The bubbles property has a value of + false for events that do not have a bubbling phase.

+ +
cancelable + Indicates whether the behavior associated with the event can be prevented.Boolean + Indicates whether the behavior associated with the event can be prevented. + If the behavior can be canceled, this value is true; otherwise it is false. + + Event.preventDefault()currentTarget + The object that is actively processing the Event object with an event listener.Object + The object that is actively processing the Event object with an event listener. For example, if a user clicks an OK button, the current target could be the node containing that button or one of its ancestors that has registered an event listener for that event. + + eventPhase + The current phase in the event flow.uint + The current phase in the event flow. This property can contain the following numeric values: +
  • The capture phase (EventPhase.CAPTURING_PHASE).
  • The target phase (EventPhase.AT_TARGET).
  • The bubbling phase (EventPhase.BUBBLING_PHASE).
+ + + +
target + The event target.Object + The event target. This property contains the target node. For example, if a user clicks an OK button, the target node is the display list node containing that button. + + type + The type of event.String + The type of event. The type is case-sensitive. + +
TextEvent + An object dispatches a TextEvent object when a user enters text in a text field or clicks + a hyperlink in an HTML-enabled text field.Event objects for TextEvent events. + flash.events:Event + An object dispatches a TextEvent object when a user enters text in a text field or clicks + a hyperlink in an HTML-enabled text field. There are two types of text events: TextEvent.LINK + and TextEvent.TEXT_INPUT. + + The following example uses the TextEventExample class to create text fields and to + listen for various text events on them. The example carries out the following tasks: +
  1. The example declares constants for two URLs to be used later.
  2. The example declares two variables of type TextField to be used later.
  3. The class constructor calls the following two methods: +
    • init() initializes the TextField objects and add event listeners to them.
    • draw() adds the TextFields to the display list and assigns the text to be displayed.
  4. The listeners linkHandler() and textInputHandler() react to the events + according to their event type. The linkHandler() method opens a web browser if one is not open already + and navigates to the clicked URL. The textInputHandler() method simply displays information every time + a key is pressed in the associated text field.
+ +

Note: The domain shown in this example is fictitious and [yourDomain] + should be replaced with a real domain.

+ +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFieldAutoSize; + import flash.events.TextEvent; + import flash.events.TextEvent; + import flash.net.URLRequest; + import flash.net.navigateToURL; + + public class TextEventExample extends Sprite { + private const DOMAIN_1_URL:String = "http://www.[yourDomain].com"; + private const DOMAIN_2_URL:String = "http://www.[yourDomain].com"; + private var linkTxt:TextField; + private var textInputTxt:TextField; + + public function TextEventExample() { + init(); + draw(); + } + + private function init():void { + linkTxt = new TextField(); + linkTxt.addEventListener(TextEvent.LINK, linkHandler); + linkTxt.height = 60; + linkTxt.autoSize = TextFieldAutoSize.LEFT; + linkTxt.multiline = true; + + textInputTxt = new TextField(); + textInputTxt.addEventListener(TextEvent.TEXT_INPUT, textInputHandler); + textInputTxt.type = TextFieldType.INPUT; + textInputTxt.background = true; + textInputTxt.border = true; + textInputTxt.height = 20; + } + + private function draw():void { + addChild(linkTxt); + linkTxt.htmlText += createLink(DOMAIN_1_URL, "Click to go to first domain"); + linkTxt.htmlText += "<br />"; + linkTxt.htmlText += createLink(DOMAIN_2_URL, "Click to go to second domain"); + + addChild(textInputTxt); + textInputTxt.y = linkTxt.height; + textInputTxt.text = "type here"; + } + + private function createLink(url:String, text:String):String { + var link:String = ""; + link += "<font color='#0000FF'>"; + link += "<u>"; + link += "<b>"; + link += "<a href='event:" + url + "'>" + text + "</a>"; + link += "</b>"; + link += "</u>"; + link += "</font>"; + return link; + } + + private function linkHandler(e:TextEvent):void { + var request:URLRequest = new URLRequest(e.text); + navigateToURL(request); + } + + private function textInputHandler(e:TextEvent):void { + trace(">> ============================"); + trace(">> e.text: " + e.text); + trace(">> textInputTxt.text: " + textInputTxt.text); + } + } +} +
flash.text.TextFieldlinkflash.events:TextEvent:LINKflash.events:TextEvent In this example, when a user clicks a hyperlink in HTML text, it triggers a text event. + Depending on the link, the user is sent to a designated website based on the + system's operating system, or a circle is drawn based on the user's selected radius. + +

A text field is created and its content is set to an HTML-formatted string by + using the htmlText property. The links are underlined for + easier identification by the user. (Adobe Flash Player changes the mouse + pointer only after the pointer is over the link.) To make sure that the user's click + invokes an ActionScript method, the URL of the link begins with the "event:" string + and a listener is added for the TextEvent.LINK event.

+ +

The linkHandler() method that is triggered after the user clicks a + link manages all the link events for the text field. The first if statement checks the + text property of the event, which holds the remainder of the URL after the + "event:" string. If the user clicked the link for the operating system, the + name of the user's current operating system, taken from the system's Capabilities.os + property, is used to send the user to the designated website. Otherwise, the selected radius + size, passed by the event's text property, is used to draw a circle below the text + field. Each time the user clicks the radius link, the previously drawn circle is cleared and a new + red circle with the selected radius size is drawn.

+ +package { + import flash.display.Sprite; + import flash.events.TextEvent; + import flash.errors.IOError; + import flash.events.IOErrorEvent; + import flash.system.Capabilities; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.display.Shape; + import flash.display.Graphics; + + public class TextEvent_LINKExample extends Sprite { + private var myCircle:Shape = new Shape(); + + public function TextEvent_LINKExample() { + var myTextField:TextField = new TextField(); + myTextField.autoSize = TextFieldAutoSize.LEFT; + myTextField.multiline = true; + myTextField.background = true; + myTextField.htmlText = "Draw a circle with the radius of <u><a href=\"event:20\">20 pixels</a></u>.<br>" + + "Draw a circle with the radius of <u><a href=\"event:50\">50 pixels</a></u>.<br><br>" + + "<u><a href=\"event:os\">Learn about your operating system.</a></u><br>"; + + myTextField.addEventListener(TextEvent.LINK, linkHandler); + + this.addChild(myTextField); + this.addChild(myCircle); + } + + private function linkHandler(e:TextEvent):void { + var osString:String = Capabilities.os; + + if(e.text == "os") { + + if (osString.search(/Windows/) != -1 ){ + navigateToURL(new URLRequest("http://www.microsoft.com/"), "_self"); + }else if (osString.search(/Mac/) != -1 ) { + navigateToURL(new URLRequest("http://www.apple.com/"), "_self"); + } else if (osString.search(/linux/i)!= -1) { + navigateToURL(new URLRequest("http://www.tldp.org/"), "_self"); + } + + } else { + myCircle.graphics.clear(); + myCircle.graphics.beginFill(0xFF0000); + myCircle.graphics.drawCircle(100, 150, Number(e.text)); + myCircle.graphics.endFill(); + } + } + } +} +
textflash.text.TextField.link
textInputflash.events:TextEvent:TEXT_INPUTflash.events:TextEvent The following example guides the user in generating a special combination + key (similar to a password). This combination key has seven alphanumeric + characters, where the second and fifth characters are numeric. + +

Three text fields for the preliminary instructions, the user input, and the + warning (error) messages are created. An event listener is added to respond to + the user's text input by triggering the textInputHandler() method. + (Every time the user enters text, a TextEvent.TEXT_INPUT event is + dispatched.

+

Note: The text events are dispatched when a user enters characters + and not as a response to any keyboard input, such as backspace. To catch all + keyboard events, use a listener for the KeyboardEvent event.)

+ +

The textInputHandler() method controls and manages the user + input. The preventDefault() method is used to prevent Adobe Flash Player + from immediately displaying the text in the input text field. The application is + responsible for updating the field. To undo the user's deletion or modification + to the characters already entered (the result string), the content of the + input text field is reassigned to the result string when a user enters + new characters. Also, to produce a consistent user experience, the setSelection() + method places the insertion point (a caret) after the last selected character in the text field.

+ +

The first if statement in the textInputHandler() method checks + the input for the second and fifth character positions of the combination key, + which must be numbers. If the user input is correct, the updateCombination() + method is called and the (result) combination key string is appended + with the user input. The updateCombination() method also moves the insertion + point after the selected character. After the seven characters are entered, + the last if statement in the textInputHandler() method changes type of the + inputTextField text field from INPUT to DYNAMIC, + which means that the user can no longer enter or change any characters.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFieldAutoSize; + import flash.events.TextEvent; + + public class TextEvent_TEXT_INPUTExample extends Sprite { + private var instructionTextField:TextField = new TextField(); + private var inputTextField:TextField = new TextField(); + private var warningTextField:TextField = new TextField(); + private var result:String = ""; + + public function TextEvent_TEXT_INPUTExample() { + instructionTextField.x = 10; + instructionTextField.y = 10; + instructionTextField.background = true; + instructionTextField.autoSize = TextFieldAutoSize.LEFT; + instructionTextField.text = "Please enter a value in the format A#AA#AA,\n" + + "where 'A' represents a letter and '#' represents a number.\n" + + "(Note that once you input a character you can't change it.)" ; + + inputTextField.x = 10; + inputTextField.y = 70; + inputTextField.height = 20; + inputTextField.width = 75; + inputTextField.background = true; + inputTextField.border = true; + inputTextField.type = TextFieldType.INPUT; + + warningTextField.x = 10; + warningTextField.y = 100; + warningTextField.autoSize = TextFieldAutoSize.LEFT; + + inputTextField.addEventListener(TextEvent.TEXT_INPUT, textInputHandler); + + this.addChild(instructionTextField); + this.addChild(inputTextField); + this.addChild(warningTextField); + } + + private function textInputHandler(event:TextEvent):void { + var charExp:RegExp = /[a-zA-z]/; + var numExp:RegExp = /[0-9]/; + + event.preventDefault(); + + inputTextField.text = result; + inputTextField.setSelection(result.length + 1, result.length + 1); + + if (inputTextField.text.length == 1 || inputTextField.text.length == 4) { + + if(numExp.test(event.text) == true) { + updateCombination(event.text); + } else { + warningTextField.text = "You need a single digit number."; + } + + }else { + + if(charExp.test(event.text) == true) { + updateCombination(event.text); + } else { + warningTextField.text = "You need an alphabet character."; + } + } + + if(inputTextField.text.length == 7) { + inputTextField.type = TextFieldType.DYNAMIC; + instructionTextField.text = "CONGRATULATIONS. You've done."; + } + } + + private function updateCombination(s:String):void { + warningTextField.text = ""; + result += s; + inputTextField.text = result; + inputTextField.setSelection(result.length + 1, result.length + 1); + } + } +} +
flash.text.TextField.textInputtext
TextEvent + Creates an Event object that contains information about text events.typeString The type of the event. Event listeners can access this information through the inherited type property. Possible values are: + TextEvent.LINK and TextEvent.TEXT_INPUT. + + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringOne or more characters of text entered by the user. Event listeners can access this information through the text property. + + Constructor for TextEvent objects. + + Creates an Event object that contains information about text events. + Event objects are passed as parameters to event listeners. + + flash.text.TextFieldclone + Creates a copy of the TextEvent object and sets the value of each property to match that of the original.A new TextEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the TextEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the TextEvent object.A string that contains all the properties of the TextEvent object. + + String + Returns a string that contains all the properties of the TextEvent object. The string is in the following format: +

[TextEvent type=value bubbles=value cancelable=value text=value]

+ +
LINK + Defines the value of the type property of a link event object.linkString + Defines the value of the type property of a link event object. + +

This event has the following properties:

+ + PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe text field containing the hyperlink that has been clicked. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.textThe remainder of the URL after "event:" + +
In this example, when a user clicks a hyperlink in HTML text, it triggers a text event. + Depending on the link, the user is sent to a designated website based on the + system's operating system, or a circle is drawn based on the user's selected radius. + +

A text field is created and its content is set to an HTML-formatted string by + using the htmlText property. The links are underlined for + easier identification by the user. (Adobe Flash Player changes the mouse + pointer only after the pointer is over the link.) To make sure that the user's click + invokes an ActionScript method, the URL of the link begins with the "event:" string + and a listener is added for the TextEvent.LINK event.

+ +

The linkHandler() method that is triggered after the user clicks a + link manages all the link events for the text field. The first if statement checks the + text property of the event, which holds the remainder of the URL after the + "event:" string. If the user clicked the link for the operating system, the + name of the user's current operating system, taken from the system's Capabilities.os + property, is used to send the user to the designated website. Otherwise, the selected radius + size, passed by the event's text property, is used to draw a circle below the text + field. Each time the user clicks the radius link, the previously drawn circle is cleared and a new + red circle with the selected radius size is drawn.

+ +package { + import flash.display.Sprite; + import flash.events.TextEvent; + import flash.errors.IOError; + import flash.events.IOErrorEvent; + import flash.system.Capabilities; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.display.Shape; + import flash.display.Graphics; + + public class TextEvent_LINKExample extends Sprite { + private var myCircle:Shape = new Shape(); + + public function TextEvent_LINKExample() { + var myTextField:TextField = new TextField(); + myTextField.autoSize = TextFieldAutoSize.LEFT; + myTextField.multiline = true; + myTextField.background = true; + myTextField.htmlText = "Draw a circle with the radius of <u><a href=\"event:20\">20 pixels</a></u>.<br>" + + "Draw a circle with the radius of <u><a href=\"event:50\">50 pixels</a></u>.<br><br>" + + "<u><a href=\"event:os\">Learn about your operating system.</a></u><br>"; + + myTextField.addEventListener(TextEvent.LINK, linkHandler); + + this.addChild(myTextField); + this.addChild(myCircle); + } + + private function linkHandler(e:TextEvent):void { + var osString:String = Capabilities.os; + + if(e.text == "os") { + + if (osString.search(/Windows/) != -1 ){ + navigateToURL(new URLRequest("http://www.microsoft.com/"), "_self"); + }else if (osString.search(/Mac/) != -1 ) { + navigateToURL(new URLRequest("http://www.apple.com/"), "_self"); + } else if (osString.search(/linux/i)!= -1) { + navigateToURL(new URLRequest("http://www.tldp.org/"), "_self"); + } + + } else { + myCircle.graphics.clear(); + myCircle.graphics.beginFill(0xFF0000); + myCircle.graphics.drawCircle(100, 150, Number(e.text)); + myCircle.graphics.endFill(); + } + } + } +} +
textflash.text.TextField.link
TEXT_INPUT + Defines the value of the type property of a textInput event object.textInputString + Defines the value of the type property of a textInput event object. +

Note: This event is not dispatched for the Delete or Backspace keys.

+

This event has the following properties:

+ PropertyValuebubblestruecancelabletrue; call the preventDefault() method + to cancel default behavior.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe text field into which characters are being entered. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.textThe character or sequence of characters entered by the user. + +
The following example guides the user in generating a special combination + key (similar to a password). This combination key has seven alphanumeric + characters, where the second and fifth characters are numeric. + +

Three text fields for the preliminary instructions, the user input, and the + warning (error) messages are created. An event listener is added to respond to + the user's text input by triggering the textInputHandler() method. + (Every time the user enters text, a TextEvent.TEXT_INPUT event is + dispatched.

+

Note: The text events are dispatched when a user enters characters + and not as a response to any keyboard input, such as backspace. To catch all + keyboard events, use a listener for the KeyboardEvent event.)

+ +

The textInputHandler() method controls and manages the user + input. The preventDefault() method is used to prevent Adobe Flash Player + from immediately displaying the text in the input text field. The application is + responsible for updating the field. To undo the user's deletion or modification + to the characters already entered (the result string), the content of the + input text field is reassigned to the result string when a user enters + new characters. Also, to produce a consistent user experience, the setSelection() + method places the insertion point (a caret) after the last selected character in the text field.

+ +

The first if statement in the textInputHandler() method checks + the input for the second and fifth character positions of the combination key, + which must be numbers. If the user input is correct, the updateCombination() + method is called and the (result) combination key string is appended + with the user input. The updateCombination() method also moves the insertion + point after the selected character. After the seven characters are entered, + the last if statement in the textInputHandler() method changes type of the + inputTextField text field from INPUT to DYNAMIC, + which means that the user can no longer enter or change any characters.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFieldAutoSize; + import flash.events.TextEvent; + + public class TextEvent_TEXT_INPUTExample extends Sprite { + private var instructionTextField:TextField = new TextField(); + private var inputTextField:TextField = new TextField(); + private var warningTextField:TextField = new TextField(); + private var result:String = ""; + + public function TextEvent_TEXT_INPUTExample() { + instructionTextField.x = 10; + instructionTextField.y = 10; + instructionTextField.background = true; + instructionTextField.autoSize = TextFieldAutoSize.LEFT; + instructionTextField.text = "Please enter a value in the format A#AA#AA,\n" + + "where 'A' represents a letter and '#' represents a number.\n" + + "(Note that once you input a character you can't change it.)" ; + + inputTextField.x = 10; + inputTextField.y = 70; + inputTextField.height = 20; + inputTextField.width = 75; + inputTextField.background = true; + inputTextField.border = true; + inputTextField.type = TextFieldType.INPUT; + + warningTextField.x = 10; + warningTextField.y = 100; + warningTextField.autoSize = TextFieldAutoSize.LEFT; + + inputTextField.addEventListener(TextEvent.TEXT_INPUT, textInputHandler); + + this.addChild(instructionTextField); + this.addChild(inputTextField); + this.addChild(warningTextField); + } + + private function textInputHandler(event:TextEvent):void { + var charExp:RegExp = /[a-zA-z]/; + var numExp:RegExp = /[0-9]/; + + event.preventDefault(); + + inputTextField.text = result; + inputTextField.setSelection(result.length + 1, result.length + 1); + + if (inputTextField.text.length == 1 || inputTextField.text.length == 4) { + + if(numExp.test(event.text) == true) { + updateCombination(event.text); + } else { + warningTextField.text = "You need a single digit number."; + } + + }else { + + if(charExp.test(event.text) == true) { + updateCombination(event.text); + } else { + warningTextField.text = "You need an alphabet character."; + } + } + + if(inputTextField.text.length == 7) { + inputTextField.type = TextFieldType.DYNAMIC; + instructionTextField.text = "CONGRATULATIONS. You've done."; + } + } + + private function updateCombination(s:String):void { + warningTextField.text = ""; + result += s; + inputTextField.text = result; + inputTextField.setSelection(result.length + 1, result.length + 1); + } + } +} +
flash.text.TextField.textInputtext
text + For a textInput event, the character or sequence of characters + entered by the user.String + For a textInput event, the character or sequence of characters + entered by the user. For a link event, the text + of the event attribute of the href attribute of the + <a> tag. + + The following code shows that the link event is dispatched when + a user clicks the hypertext link: + + + import flash.text.TextField; + import flash.events.TextEvent; + + var tf:TextField = new TextField(); + tf.htmlText = "<a href='event:myEvent'>Click Me.</a>"; + tf.addEventListener("link", clickHandler); + addChild(tf); + + function clickHandler(e:TextEvent):void { + trace(e.type); // link + trace(e.text); // myEvent + } + + +
SampleDataEvent + Dispatched when a Sound object requests new audio data or when a Microphone object + has new audio data to provide.flash.events:Event + Dispatched when a Sound object requests new audio data or when a Microphone object + has new audio data to provide. + +

This event has two uses:

+ +
  • To provide dynamically generated audio data for a Sound object
  • To get audio data for a Microphone object
+ +

Dynamically generating audio using the Sound object Use the + sampleData event to play dynamically generated audio. In this environment, + the Sound object doesn't actually contain sound data. Instead, it acts as a socket for + sound data that is being streamed to it through the use of the function + you assign as the handler for the sampleData event.

+ +

In your function, you use the ByteArray.writeFloat() method to write to + the event's data) property, which contains the sampled data you + want to play.

+ +

If a Sound object has not loaded an MP3 file, when you call its play() method + the object starts dispatching sampleData events, requesting sound samples. + The Sound object continues to send events as the sound plays back until you stop providing data, + or until the stop() method of the SoundChannel object is called.

+ +

Thes latency of the event varies from platform to platform, and it could change in future + versions of Flash Player or AIR. Don't depend on a specific latency. + Instead calculate it using ((SampleDataEvent.position/44.1) - SoundChannelObject.position).

+ +

Provide between 2048 and 8192 samples to the data property of + the SampleDataEvent object. For best performance, provide as many samples as possible. + The fewer samples you provide, the more likely it is + that clicks and pops will occur during playback. This behavior can differ on various platforms + and can occur in various situations - for example, when resizing the browser. + You might write code that works on one platform when you provide only 2048 samples, but that same code + might not work as well when run on a different platform. If you require the lowest latency possible, + consider making the amount of data user-selectable.

+ +

If you provide fewer than 2048 samples, tha Sound object plays the remaining samples + and then stops the sound as if the end of a sound file was reached, generating + a complete event.

+ +

You can use the extract() method of a Sound object to extract its sound data, + which you can then write to the dynamic stream for playback.

+ +

When you use the sampleData event with a Sound object, the only Sound methods that + are enabled are extract() and play(). Calling any other methods or properties + results in an "invalid call" exception. All methods and properties of the SoundChannel object + are still enabled.

+ +

Capturing Microphone audio Use the sampleData event + to capture audio data from a microphone. When you add an event listener for the + sampleData event, the Microphone dispatches the event as audio samples + become available.

+ +

In the event handler function, use the ByteArray.readFloat() method to read + the event's data) property, which contains the sampled data. The event will contain + multiple samples, so you should use a while loop to read the available data:

+ + var soundBytes:ByteArray = new ByteArray(); + while(event.data.bytesAvailable) + { + var sample:Number = event.data.readFloat(); + soundBytes.writeFloat(sample); + } + + +
The following example plays a simple sine wave. + + +var mySound:Sound = new Sound(); +function sineWaveGenerator(event:SampleDataEvent):void { + for ( var c:int=0; c<8192; c++ ) { + event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25); + event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25); + } +} + +mySound.addEventListener(SampleDataEvent.SAMPLE_DATA,sineWaveGenerator); +mySound.play(); +
flash.media.SoundsampleDataflash.events:SampleDataEvent:SAMPLE_DATAflash.events:SampleDataEventflash.media.Sound.sampleDataflash.events.SampleDataEventSampleDataEvent + Creates an event object that contains information about audio data events.typeString The type of the event. This value is:Event.SAMPLE_DATA. + + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + thepositionNumber0The position of the data in the audio stream. + thedataflash.utils:ByteArraynullA byte array of data. + + Creates an event object that contains information about audio data events. + Event objects are passed as parameters to event listeners. + clone + Creates a copy of the SampleDataEvent object and sets each property's value to match that of the original.A new SampleDataEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the SampleDataEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the SampleDataEvent object.A string that contains all the properties of the SampleDataEvent object. + String + Returns a string that contains all the properties of the SampleDataEvent object. The string is in the following format: +

[SampleDataEvent type=value bubbles=value cancelable=value theposition=value thedata=value]

+ +
SAMPLE_DATA + Defines the value of the type property of a SampleDataEvent event object.sampleDataString + Defines the value of the type property of a SampleDataEvent event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.positionThe point from which audio data is provided. + +
flash.media.Sound.sampleDataflash.events.SampleDataEvent
data + The data in the audio stream.flash.utils:ByteArray + The data in the audio stream. + position + The position of the data in the audio stream.Number + The position of the data in the audio stream. +
HTTPStatusEvent +The application dispatches HTTPStatusEvent objects when a network request returns an HTTP +status code.flash.events:Event +The application dispatches HTTPStatusEvent objects when a network request returns an HTTP +status code. + +

HTTPStatusEvent objects are always sent before error or completion events. An +HTTPStatusEvent object does not necessarily indicate an error condition; it simply reflects +the HTTP status code (if any) that is provided by the networking stack. Some Flash +Player environments may be unable to detect HTTP status codes; a status code of 0 is always +reported in these cases.

+ +

In Flash Player, there is only one type of HTTPStatus event: +httpStatus. In the AIR runtime, a FileReference, URLLoader, or URLStream +can register to listen for an httpResponseStatus, which includes responseURL +and responseHeaders properties. These properties are undefined in a httpStatus +event.

+ +
The following example attempts to load a nonexistent file from the root web directory + at http://www.[yourDomain].com, which should dispatch an httpStatusHandler event with a status of 404, indicating that + the file was not found. The httpStatusHandler event is handled by httpStatusHandler(), + which simply prints two lines of information about the event. + +

Notes: +

  1. You need to compile the SWF file with "Local Playback Security" set + to "Access Network Only" to generate a securityError event in this example.
  2. You need a server running on http://www.[yourDomain].com and listening on port 80 or you will receive + an httpStatusHandler event with status code 0 instead of 404.
  3. You must not have a file named MissingFile.html at the root web directory + of http://www.[yourDomain].com or you will not receive the correct httpStatusHandler event.
+

+ +package { + import flash.display.Sprite; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.events.HTTPStatusEvent; + + public class HTTPStatusEventExample extends Sprite { + + public function HTTPStatusEventExample() { + var loader:URLLoader = new URLLoader(); + loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + + var request:URLRequest = new URLRequest("http://www.[yourDomain].com/MissingFile.html"); + loader.load(request); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + trace("status: " + event.status); + } + } +} +
httpResponseStatusflash.events:HTTPStatusEvent:HTTP_RESPONSE_STATUSflash.events:HTTPStatusEventflash.net.URLStream.httpResponseStatusflash.net.FileReference.httpResponseStatushttpStatusflash.events:HTTPStatusEvent:HTTP_STATUSflash.events:HTTPStatusEventflash.display.LoaderInfo.httpStatusflash.net.FileReference.httpStatusflash.net.URLLoader.httpStatusflash.net.URLStream.httpStatusHTTPStatusEvent + Creates an Event object that contains specific information about HTTP status events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of HTTPStatus event: HTTPStatusEvent.HTTP_STATUS. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + statusint0Numeric status. Event listeners can access this information through the status property. + + Constructor for HTTPStatusEvent objects. + + Creates an Event object that contains specific information about HTTP status events. + Event objects are passed as parameters to event listeners. + + HTTP_STATUSclone + Creates a copy of the HTTPStatusEvent object and sets the value of each property to match that of the original.A new HTTPStatusEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the HTTPStatusEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the HTTPStatusEvent object.A string that contains all the properties of the HTTPStatusEvent object. + + String + Returns a string that contains all the properties of the HTTPStatusEvent object. The string is in the following format: +

[HTTPStatusEvent type=value bubbles=value cancelable=value status=value]

+ +
HTTP_RESPONSE_STATUS + Unlike the httpStatus event, the httpResponseStatus event is + delivered before any response data.httpResponseStatusString + Unlike the httpStatus event, the httpResponseStatus event is + delivered before any response data. Also, the httpResponseStatus event includes + values for the responseHeaders and responseURL properties (which are + undefined for an httpStatus event. Note that the httpResponseStatus event + (if any) will be sent before (and in addition to) any complete or error + event. + +

The HTTPStatusEvent.HTTP_RESPONSE_STATUS constant defines the value of the + type property of a httpResponseStatus event object.

+ + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.responseURLThe URL from which the response was returned.responseHeadersThe response headers that the response returned, + as an array of URLRequestHeader objects.statusThe HTTP status code returned by the server.targetThe network object receiving an HTTP status code. + +
flash.net.URLStream.httpResponseStatusflash.net.FileReference.httpResponseStatus
HTTP_STATUS + The HTTPStatusEvent.HTTP_STATUS constant defines the value of the + type property of a httpStatus event object.httpStatusString + The HTTPStatusEvent.HTTP_STATUS constant defines the value of the + type property of a httpStatus event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.statusThe HTTP status code returned by the server.targetThe network object receiving an HTTP status code. + +
flash.display.LoaderInfo.httpStatusflash.net.FileReference.httpStatusflash.net.URLLoader.httpStatusflash.net.URLStream.httpStatus
responseHeaders + The response headers that the response returned, as an array of URLRequestHeader objects.Array + The response headers that the response returned, as an array of URLRequestHeader objects. + + flash.net.URLRequestHeaderresponseURL + The URL that the response was returned from.String + The URL that the response was returned from. In the case of redirects, this will be different + from the request URL. + + status + The HTTP status code returned by the server.int + The HTTP status code returned by the server. For example, a value of 404 indicates that the server + has not found a match for the requested URI. HTTP status codes can be found in sections 10.4 and 10.5 + of the HTTP specification at + http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. + +

If Flash Player or AIR cannot get a status code from the + server, or if it cannot communicate with the server, the default value of 0 is passed to your code. + A value of 0 can be generated in any player (for example, + if a malformed URL is requested), and a value of 0 is always generated by the Flash Player plug-in + when it is run in the following browsers, which do not pass HTTP status codes to the player: + Netscape, Mozilla, Safari, Opera, and Internet Explorer for the Macintosh.

+ +
FileListEvent + A File object dispatches a FileListEvent object when a call to the getDirectoryListingAsync() method + of a File object successfully enumerates a set of files and directories or when a user selects files after a + call to the browseForOpenMultiple() method.A File object dispatches a FileListEvent object after successful calls to the getDirectoryListingAsync() + or browseForOpenMultiple() method. + + flash.events:Event + A File object dispatches a FileListEvent object when a call to the getDirectoryListingAsync() method + of a File object successfully enumerates a set of files and directories or when a user selects files after a + call to the browseForOpenMultiple() method. + + File.getDirectoryListingAsync()directoryListingflash.events:FileListEvent:DIRECTORY_LISTINGflash.events:FileListEventselectMultipleflash.events:FileListEvent:SELECT_MULTIPLEflash.events:FileListEventFileListEvent + The constructor function for a FileListEvent object.typeStringThe type of the event. + + bubblesBooleanfalseDetermines whether the event object bubbles (false for a FileListEvent object). + + cancelableBooleanfalseDetermines whether the Event object can be canceled (false for a FileListEvent object). + + filesArraynullAn array of File objects. + + + The constructor function for a FileListEvent object. + +

The runtime uses this class to create FileListEvent objects. You will not use this + constructor directly in your code.

+ +
DIRECTORY_LISTING + The FileListEvent.DIRECTORY_LISTING constant defines the value of the + type property of the event object for a directoryListing event.directoryListingString + The FileListEvent.DIRECTORY_LISTING constant defines the value of the + type property of the event object for a directoryListing event. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.filesAn array of File objects representing the files and directories found.targetThe FileListEvent object. + +
SELECT_MULTIPLE + The FileListEvent.SELECT_MULTIPLE constant defines the value of the + type property of the event object for a selectMultiple event.selectMultipleString + The FileListEvent.SELECT_MULTIPLE constant defines the value of the + type property of the event object for a selectMultiple event. + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.filesAn array of File objects representing the files selected.targetThe FileListEvent object. + files + An array of File objects representing the files and directories found or selected.Array + An array of File objects representing the files and directories found or selected. + +

For the File.getDirectoryListingAsync() method, this is the list of files and + directories found at the root level of the directory represented by the File object that called + the method. For the File.browseForOpenMultiple() method, this is the list of files + selected by the user.

+ +
NativeWindowBoundsEvent + A NativeWindow object dispatches a NativeWindowBoundsEvent object when the size or location + of the window changes.Event objects for NativeWindow events that change the size and/or location of the window. + flash.events:Event + A NativeWindow object dispatches a NativeWindowBoundsEvent object when the size or location + of the window changes. + +

There are four types of events:

+
  • NativeWindowBoundsEvent.MOVING
  • NativeWindowBoundsEvent.MOVE
  • NativeWindowBoundsEvent.RESIZING
  • NativeWindowBoundsEvent.RESIZE
+ +
flash.events.NativeWindowBoundsEvent.MOVINGflash.events.NativeWindowBoundsEvent.MOVEflash.events.NativeWindowBoundsEvent.RESIZINGflash.events.NativeWindowBoundsEvent.RESIZEmoveflash.events:NativeWindowBoundsEvent:MOVEflash.events:NativeWindowBoundsEventDispatched by a NativeWindow object after it moves. + + flash.display.NativeWindowmovingflash.events:NativeWindowBoundsEvent:MOVINGflash.events:NativeWindowBoundsEventDispatched by a NativeWindow object before it moves. + + flash.display.NativeWindowresizeflash.events:NativeWindowBoundsEvent:RESIZEflash.events:NativeWindowBoundsEventDispatched by a NativeWindow object after it resizes. + + flash.display.NativeWindowresizingflash.events:NativeWindowBoundsEvent:RESIZINGflash.events:NativeWindowBoundsEventDispatched by a NativeWindow object before it resizes. + + flash.display.NativeWindowNativeWindowBoundsEvent + Creates an Event object with specific information relevant to window bounds events.typeString The type of the event. Possible values are: +
  • NativeWindowBoundsEvent.MOVING
  • NativeWindowBoundsEvent.MOVE
  • NativeWindowBoundsEvent.RESIZING
  • NativeWindowBoundsEvent.RESIZE
+ +
bubblesBooleanfalse Indicates whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseIndicates whether the Event object can be canceled. + beforeBoundsflash.geom:RectanglenullIndicates the bounds before the most recent change or the pending change. + afterBoundsflash.geom:RectanglenullIndicates the bounds after the most recent change or the pending change. + +
+ Creates an Event object with specific information relevant to window bounds events. + Event objects are passed as parameters to event listeners. + +
clone + Creates a copy of the NativeWindowBoundsEvent object and sets the value of each property + to match that of the original.A new NativeWindowBoundsEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the NativeWindowBoundsEvent object and sets the value of each property + to match that of the original. + + toString + Returns a string that contains all the properties of the NativeWindowBoundsEvent object.A string that contains all the properties of the NativeWindowBoundsEvent object. + String + Returns a string that contains all the properties of the NativeWindowBoundsEvent object. The string has the following format: +

[NativeWindowBoundsEvent type=value bubbles=value cancelable=value previousDisplayState=value currentDisplayState=value]

+ +
MOVE + Defines the value of the type property of a move event object.moveStringDispatched by a NativeWindow object after it moves. + + + Defines the value of the type property of a move event object. + +

This event has the following properties:

+ PropertiesValuesafterBoundsThe new bounds of the window.beforeBoundsThe old bounds of the window.targetThe NativeWindow object that has just changed state. + bubblesNo.currentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelablefalse; There is no default behavior to cancel. + +
flash.display.NativeWindow
MOVING + Defines the value of the type property of a moving event object.movingStringDispatched by a NativeWindow object before it moves. + + + Defines the value of the type property of a moving event object. + +

This event has the following properties:

+ PropertiesValuesafterBoundsThe bounds of the window after the pending change.beforeBoundsThe bounds of the window before the pending change.bubblesNo.cancelabletrue; cancelling the event will prevent the window move.currentTargetIndicates the object that is actively processing the Event + object with an event listener.targetThe NativeWindow object that has just changed state. + +

Note: On Linux, the preventDefault() method is not supported for this event.

+ +
flash.display.NativeWindow
RESIZE + Defines the value of the type property of a resize event object.resizeStringDispatched by a NativeWindow object after it resizes. + + + Defines the value of the type property of a resize event object. + +

This event has the following properties:

+ PropertiesValuesafterBoundsThe new bounds of the window.beforeBoundsThe old bounds of the window.targetThe NativeWindow object that has just changed state. + bubblesNo.currentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelablefalse; There is no default behavior to cancel. + +
flash.display.NativeWindow
RESIZING + Defines the value of the type property of a resizing event object.resizingStringDispatched by a NativeWindow object before it resizes. + + + Defines the value of the type property of a resizing event object. + +

This event has the following properties:

+ PropertiesValuesafterBoundsThe bounds of the window after the pending change.beforeBoundsThe bounds of the window before the pending change.targetThe NativeWindow object that has just changed state. + bubblesNo.currentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelabletrue; cancelling the event will prevent the window move. + +

Note: On Linux, the preventDefault() method is not supported for this event.

+ +
flash.display.NativeWindow
afterBounds + The bounds of the window after the change.flash.geom:Rectangle + The bounds of the window after the change. + +

If the event is moving or resizing, the + bounds have not yet changed; afterBounds indicates the new bounds + if the event is not canceled. If the event is + move or resize, + afterBounds indicates the new bounds. +

+
beforeBounds + The bounds of the window before the change.flash.geom:Rectangle + The bounds of the window before the change. + +

If the event is moving or resizing, the + bounds have not yet changed; beforeBounds reflects the current bounds. If the event is + move or resize, + beforeBounds indicates the original value. +

+
SQLUpdateEvent + A SQLUpdateEvent object is dispatched by a SQLConnection object when a data change occurs + on any table associated with the SQLConnection instance.flash.events:Event + A SQLUpdateEvent object is dispatched by a SQLConnection object when a data change occurs + on any table associated with the SQLConnection instance. + A data change can result from the execution of a SQL INSERT, + UPDATE, or DELETE statement, either directly or as + a result of a trigger that fires in connection with the statement execution. + + The following example shows the use of of a SQLUpdateEvent instance + in responding to an update event. + + +var dbStatement:SQLStatement; + +function initConnection():void +{ + var dbFile:File = new File(File.separator + "employee.db"); + db.addEventListener(SQLEvent.OPEN, dbOpenHandler); + db.addEventListener(SQLUpdateEvent.UPDATE, dbUpdateHandler); + + dbStatement.text = "UPDATE employees SET name = :name WHERE id = :id"; + dbStatement.parameters[:name] = "Bruce"; + dbStatement.parameters[:id] = 100; + + dbStatement.sqlConnection = db; + + db.open(dbFile); +} + +function dbUpdateHandler(event:SQLUpdateEvent):void +{ + trace(event.type + " for table '" + event.table + "' was fired for row with ID:" + event.rowID); +} + +function dbOpenHandler(event:SQLEvent):void +{ + dbStatement.execute(); +} +flash.data.SQLConnectiondeleteflash.events:SQLUpdateEvent:DELETEflash.events:SQLUpdateEventinsertflash.events:SQLUpdateEvent:INSERTflash.events:SQLUpdateEventupdateflash.events:SQLUpdateEvent:UPDATEflash.events:SQLUpdateEventSQLUpdateEvent + Creates a new SQLUpdateEvent instance.typeString The type of the event, available through the type property. + + bubblesBooleanfalse Determines whether the event object participates in the bubbling + stage of the event flow. The default value is false. + + cancelableBooleanfalseDetermines whether the Event object can be cancelled. + The default value is false. + + tableStringnullIndicates the name of the table whose data changed. + + rowIDNumber0The unique row identifier of the row that was inserted, deleted, or updated. + + Used to create new SQLUpdateEvent object. + + + Creates a new SQLUpdateEvent instance. + + clone + Creates a copy of the SQLUpdateEvent object and sets the value of each property to + match that of the original.A new SQLUpdateEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the SQLUpdateEvent object and sets the value of each property to + match that of the original. + + DELETE + The SQLUpdateEvent.DELETE constant defines the value of the + type property of a SQLConnection delete event.deleteString + The SQLUpdateEvent.DELETE constant defines the value of the + type property of a SQLConnection delete event. + + The delete event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.rowIDThe unique row identifier of the row that was inserted, deleted, or updated.targetThe SQLConnection object on which the operation was performed.tableThe name of the table on which the change occurred. + + INSERT + The SQLUpdateEvent.INSERT constant defines the value of the + type property of a SQLConnection insert event.insertString + The SQLUpdateEvent.INSERT constant defines the value of the + type property of a SQLConnection insert event. + + The insert event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.rowIDThe unique row identifier of the row that was inserted, deleted, or updated.targetThe SQLConnection object on which the operation was performed.tableThe name of the table on which the change occurred. + + UPDATE + The SQLUpdateEvent.UPDATE constant defines the value of the + type property of a SQLConnection update event.updateString + The SQLUpdateEvent.UPDATE constant defines the value of the + type property of a SQLConnection update event. + +

The update event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.rowIDThe unique row identifier of the row that was inserted, deleted, or updated.targetThe SQLConnection object on which the operation was performed.tableThe name of the table on which the change occurred. + +
rowID + The unique row identifier of the row that was inserted, deleted, or updated.Number + The unique row identifier of the row that was inserted, deleted, or updated. + +

A row identifier is used to uniquely identify a row in a table within + the database. The value is frequently generated by the database.

+ +

The row identifier for a single SQL INSERT statement execution + can be obtained through the lastInsertRowID property of the SQLResult object + returned by the SQLStatement object's getResult() method (when called after the + SQLStatement dispatches its result event).

+ +

For more information about primary keys and generated row identifiers, + see the "CREATE TABLE" and + "Expressions" sections in the appendix + "SQL support in local databases."

+ +
flash.data.SQLConnection.lastInsertRowIDflash.data.SQLResult.lastInsertRowID
table + The name of the table whose data change caused the event to be dispatched.String + The name of the table whose data change caused the event to be dispatched. + +
EventDispatcher +The EventDispatcher class is the base class for all runtime classes that dispatch events.flash.events:IEventDispatcherObject +The EventDispatcher class is the base class for all classes that dispatch events. +The EventDispatcher class implements the IEventDispatcher interface and is the base class for +the DisplayObject class. The EventDispatcher class allows any object on the display list to be +an event target and as such, to use the methods of the IEventDispatcher interface. + +

Event targets are an important part of the Flash® Player and +Adobe® AIR® event model. The event target serves +as the focal point for how events flow through the display list hierarchy. +When an event such as a mouse click or a keypress occurs, Flash Player or the AIR application dispatches an event +object into the event flow from the root of the display list. The event object then makes its +way through the display list until it reaches the event target, at which point it begins its +return trip through the display list. This round-trip journey to the event target is +conceptually divided into three phases: the capture phase comprises the journey from the +root to the last node before the event target's node, the target phase comprises only the +event target node, and the bubbling phase comprises any subsequent nodes encountered on +the return trip to the root of the display list.

+ +

In general, the easiest way for a user-defined class to gain event dispatching +capabilities is to extend EventDispatcher. If this is impossible (that is, if the class is already extending +another class), you can instead implement the IEventDispatcher interface, create an EventDispatcher member, +and write simple hooks to route calls into the aggregated EventDispatcher.

+ + + +
The following example uses the classes EventDispatcherExample and + CustomDispatcher, a subclass of EventDispatcher, to show how a + custom event is created and dispatched. The example carries out the following tasks: +
  1. The constructor of EventDispatcherExample creates a local variable + dispatcher and assigns it to a new CustomDispatcher instance.
  2. Inside CustomDispatcher, a string is set so that the event has + the name action, and the doAction() method is declared. When called, this method creates the action + event and dispatches it using EventDispatcher.dispatchEvent().
  3. The dispatcher property is then used to add the action + event listener and associated subscriber method actionHandler(), which simply + prints information about the event when it is dispatched.
  4. The doAction() method is invoked, dispatching the action + event.
+ +package { + import flash.display.Sprite; + import flash.events.Event; + + public class EventDispatcherExample extends Sprite { + + public function EventDispatcherExample() { + var dispatcher:CustomDispatcher = new CustomDispatcher(); + dispatcher.addEventListener(CustomDispatcher.ACTION, actionHandler); + dispatcher.doAction(); + } + + private function actionHandler(event:Event):void { + trace("actionHandler: " + event); + } + } +} + +import flash.events.EventDispatcher; +import flash.events.Event; + +class CustomDispatcher extends EventDispatcher { + public static var ACTION:String = "action"; + + public function doAction():void { + dispatchEvent(new Event(CustomDispatcher.ACTION)); + } +} +
deactivate + [broadcast event] Dispatched when the Flash Player or AIR application operating + loses system focus and is becoming inactive.flash.events.Event.DEACTIVATEflash.events.Event + [broadcast event] Dispatched when the Flash Player or AIR application operating + loses system focus and is becoming inactive. This event is a broadcast event, which means that it is dispatched + by all EventDispatcher objects with a listener registered for this event. For more + information about broadcast events, see the DisplayObject class. + + flash.display.DisplayObjectactivate + [broadcast event] Dispatched when the Flash Player or AIR application gains + operating system focus and becomes active.flash.events.Event.ACTIVATEflash.events.Event + [broadcast event] Dispatched when the Flash Player or AIR application gains + operating system focus and becomes active. This event is a broadcast event, which means that it is dispatched + by all EventDispatcher objects with a listener registered for this event. For more + information about broadcast events, see the DisplayObject class. + + flash.display.DisplayObjectEventDispatcher + Aggregates an instance of the EventDispatcher class.targetflash.events:IEventDispatchernullThe target object for events dispatched to the EventDispatcher object. + This parameter is used when the EventDispatcher instance is aggregated by a class that implements IEventDispatcher; it is necessary so that the containing object can be the target for events. + Do not use this parameter in simple cases in which a class extends EventDispatcher. + + + + Aggregates an instance of the EventDispatcher class. + +

The EventDispatcher class is generally used as a base class, which means that most + developers do not need to use + this constructor function. However, advanced developers who are implementing + the IEventDispatcher interface need to use this constructor. + If you are unable to extend the EventDispatcher class and must + instead implement the IEventDispatcher interface, use this constructor to aggregate an instance of the EventDispatcher class.

+ +
addEventListener + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.The listener specified is not a function. + ArgumentErrorArgumentErrortypeStringThe type of event. + + listenerFunctionThe listener function that processes the event. This function must accept + an Event object as its only parameter and must return nothing, as this example shows: + + + function(evt:Event):void + +

The function can have any name.

+ +
useCaptureBooleanfalse + + Determines whether the listener works in the capture phase or the + target and bubbling phases. If useCapture is set to true, + the listener processes the event only during the capture phase and not in the + target or bubbling phase. If useCapture is false, the + listener processes the event only during the target or bubbling phase. To listen for + the event in all three phases, call addEventListener twice, once with + useCapture set to true, then again with + useCapture set to false. + + priorityint0The priority level of the event listener. The priority is designated by + a signed 32-bit integer. The higher the number, the higher the priority. All listeners + with priority n are processed before listeners of priority n-1. If two + or more listeners share the same priority, they are processed in the order in which they + were added. The default priority is 0. + + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or + weak. A strong reference (the default) prevents your listener from being garbage-collected. + A weak reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbage-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. + + + +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's + priority, you must first call removeListener(). Then you can register the + listener again with the new priority level.

+ +

Keep in mind that after the listener is registered, subsequent calls to + addEventListener() with a different type or + useCapture value result in the creation of a separate listener registration. + For example, if you first register a listener with useCapture set to + true, it listens only during the capture phase. If you call + addEventListener() again using the same listener object, but with + useCapture set to false, you have two separate listeners: one + that listens during the capture phase and another that listens during the target and + bubbling phases. +

+ +

You cannot register an event listener for only the target phase or the bubbling + phase. Those phases are coupled during registration because bubbling + applies only to the ancestors of the target node.

+ +

If you no longer need an event listener, remove it by calling + removeEventListener(), or memory problems could result. Event listeners are not automatically + removed from memory because the garbage + collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference + parameter is set to true).

+ +

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event listeners + attached to it move along with it.

+ + +

If the event listener is being registered on a node while an event is being processed + on this node, the event listener is not triggered during the current phase but can be + triggered during a later phase in the event flow, such as the bubbling phase.

+ +

If an event listener is removed from a node while an event is being processed on the node, + it is still triggered by the current actions. After it is removed, the event listener is + never invoked again (unless registered again for future processing).

+ +
dispatchEvent + Dispatches an event into the event flow.The event dispatch recursion limit has been reached. + ErrorErrorA value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called + on the event. + + Booleaneventflash.events:EventThe Event object that is dispatched into the event flow. + If the event is being redispatched, a clone of the event is created automatically. + After an event is dispatched, its target property cannot be changed, so you + must create a new copy of the event for redispatching to work. + + + Dispatches an event into the event flow. The event target is the EventDispatcher + object upon which the dispatchEvent() method is called. + + hasEventListener + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event.A value of true if a listener of the specified type is registered; + false otherwise. + BooleantypeStringThe type of event. + + Checks whether the EventDispatcher object has any listeners registered for a specific type + of event. This allows you to determine where an EventDispatcher object has altered + handling of an event type in the event flow hierarchy. To determine whether a specific + event type actually triggers an event listener, use willTrigger(). + +

The difference between hasEventListener() and willTrigger() + is that hasEventListener() examines only the object to + which it belongs, whereas willTrigger() examines the entire + event flow for the event specified by the type parameter. + +

+ +

When hasEventListener() is called from a LoaderInfo object, only the + listeners that the caller can access are considered.

+ +
willTrigger()
removeEventListener + Removes a listener from the EventDispatcher object.typeStringThe type of event. + + listenerFunctionThe listener object to remove. + + useCaptureBooleanfalse + + Specifies whether the listener was registered for the capture phase or the + target and bubbling phases. If the listener was registered for both the capture phase and the + target and bubbling phases, two calls to removeEventListener() are required + to remove both, one call with useCapture() set to true, and another + call with useCapture() set to false. + + + Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect. + + willTrigger + Checks whether an event listener is registered with this EventDispatcher object or any of + its ancestors for the specified event type.A value of true if a listener of the specified type will be triggered; false otherwise. + BooleantypeStringThe type of event. + + Checks whether an event listener is registered with this EventDispatcher object or any of + its ancestors for the specified event type. This method returns true if an + event listener is triggered during any phase of the event flow when an event of the + specified type is dispatched to this EventDispatcher object or any of its descendants. + +

The difference between the hasEventListener() and the willTrigger() + methods is that hasEventListener() examines only the object to which it belongs, + whereas the willTrigger() method examines the entire event flow for the event specified by the + type parameter.

+ +

When willTrigger() is called from a LoaderInfo object, only the + listeners that the caller can access are considered.

+ +
TouchEvent + The TouchEvent class lets you handle events on devices that detect user contact with + the device (such as a finger on a touch screen).provides event handling support for touch interaction + + flash.events:Event + The TouchEvent class lets you handle events on devices that detect user contact with + the device (such as a finger on a touch screen). + When a user interacts with a device such as a mobile phone or tablet with a touch screen, the user typically + touches the screen with his or her fingers or a pointing device. You can develop applications that respond to + basic touch events (such as a single finger tap) with the TouchEvent class. Create event listeners using the event types defined in this class. + For user interaction with multiple points of contact (such as several fingers moving across a touch screen at the same time) use + the related GestureEvent, PressAndTapGestureEvent, and TransformGestureEvent classes. And, use the properties and methods of these classes + to construct event handlers that respond to the user touching the device. +

Use the Multitouch class to determine the current environment's support for touch interaction, and to + manage the support of touch interaction if the current environment supports it.

+

Note: When objects are nested on the display list, touch events target the deepest possible + nested object that is visible in the display list. This object is called the target node. To have a target node's + ancestor (an object containing the target node in the display list) receive notification of a touch event, use + EventDispatcher.addEventListener() on the ancestor node with the type parameter set to the specific + touch event you want to detect.

+ +
The following example shows event handling for the TOUCH_BEGIN, TOUCH_MOVE, and TOUCH_END events. + While the point of contact moves across the screen (onTouchMove), the x-coordinate relative to the stage is traced to output. + For the Sprite.startTouchDrag parameters in the onTouchBegin function, the value for touchPointID is the value assigned to the event object. + The bounds parameter is the rectangle defining the boundaries of + the parent display object (bg is a display object containing MySprite). + +Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + +MySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +MySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); +MySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + +function onTouchBegin(eBegin:TouchEvent) { + eBegin.target.startTouchDrag(eBegin.touchPointID, false, bg.getRect(this)); + trace("touch begin"); + + } + +function onTouchMove(eMove:TouchEvent) { + trace(eMove.stageX); +} + +function onTouchEnd(eEnd:TouchEvent) { + eEnd.target.stopTouchDrag(eEnd.touchPointID); + trace("touch end"); +} + The following example shows how to handle touch events and touch event phases, as well as the Multitouch.maxTouchPoints and the + touch event object's touchPointID properties. + This example comes from Christian Cantrell, and is explained in more detail in his quickstart: + Multi-touch and gesture support on the Flash Platform. + + package +{ + import flash.display.Sprite; + import flash.events.TouchEvent; + import flash.text.AntiAliasType; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.ui.Multitouch; + import flash.ui.MultitouchInputMode; + + [SWF(width=320, height=460, frameRate=24, backgroundColor=0xEB7F00)] + public class TouchExample2 extends Sprite + { + private var dots:Object; + private var labels:Object; + private var labelFormat:TextFormat; + private var dotCount:uint; + private var dotsLeft:TextField; + private static const LABEL_SPACING:uint = 15; + + public function TouchExample2() + { + super(); + + this.labelFormat = new TextFormat(); + labelFormat.color = 0xACF0F2; + labelFormat.font = "Helvetica"; + labelFormat.size = 11; + + this.dotCount = 0; + + this.dotsLeft = new TextField(); + this.dotsLeft.width = 300; + this.dotsLeft.defaultTextFormat = this.labelFormat; + this.dotsLeft.x = 3; + this.dotsLeft.y = 0; + this.stage.addChild(this.dotsLeft); + this.updateDotsLeft(); + + this.dots = new Object(); + this.labels = new Object(); + + Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + this.stage.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); + this.stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); + this.stage.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); + } + + private function onTouchBegin(e:TouchEvent):void + { + if (this.dotCount == Multitouch.maxTouchPoints) return; + var dot:Sprite = this.getCircle(); + dot.x = e.stageX; + dot.y = e.stageY; + this.stage.addChild(dot); + dot.startTouchDrag(e.touchPointID, true); + this.dots[e.touchPointID] = dot; + + ++this.dotCount; + + var label:TextField = this.getLabel(e.stageX + ", " + e.stageY); + label.x = 3; + label.y = this.dotCount * LABEL_SPACING; + this.stage.addChild(label); + this.labels[e.touchPointID] = label; + + this.updateDotsLeft(); + } + + private function onTouchMove(e:TouchEvent):void + { + var label:TextField = this.labels[e.touchPointID]; + label.text = (e.stageX + ", " + e.stageY); + } + + private function onTouchEnd(e:TouchEvent):void + { + var dot:Sprite = this.dots[e.touchPointID]; + var label:TextField = this.labels[e.touchPointID]; + + this.stage.removeChild(dot); + this.stage.removeChild(label); + + delete this.dots[e.touchPointID]; + delete this.labels[e.touchPointID]; + + --this.dotCount; + + this.updateDotsLeft(); + } + + private function getCircle(circumference:uint = 40):Sprite + { + var circle:Sprite = new Sprite(); + circle.graphics.beginFill(0x1695A3); + circle.graphics.drawCircle(0, 0, circumference); + return circle; + } + + private function getLabel(initialText:String):TextField + { + var label:TextField = new TextField(); + label.defaultTextFormat = this.labelFormat; + label.selectable = false; + label.antiAliasType = AntiAliasType.ADVANCED; + label.text = initialText; + return label; + } + + private function updateDotsLeft():void + { + this.dotsLeft.text = "Touches Remaining: " + (Multitouch.maxTouchPoints - this.dotCount); + } + } +} +
flash.ui.Multitouchflash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()touchBeginflash.events:TouchEvent:TOUCH_BEGINflash.events:TouchEventflash.display.InteractiveObject.touchBegintouchEndflash.events:TouchEvent:TOUCH_ENDflash.events:TouchEventflash.display.InteractiveObject.touchEndtouchMoveflash.events:TouchEvent:TOUCH_MOVEflash.events:TouchEventflash.display.InteractiveObject.touchMovetouchOutflash.events:TouchEvent:TOUCH_OUTflash.events:TouchEventflash.display.InteractiveObject.touchOuttouchOverflash.events:TouchEvent:TOUCH_OVERflash.events:TouchEventflash.display.InteractiveObject.touchOvertouchRollOutflash.events:TouchEvent:TOUCH_ROLL_OUTflash.events:TouchEventflash.display.InteractiveObject.touchRollOuttouchRollOverflash.events:TouchEvent:TOUCH_ROLL_OVERflash.events:TouchEventflash.display.InteractiveObject.touchRollOvertouchTapflash.events:TouchEvent:TOUCH_TAPflash.events:TouchEvent The following example displays a message when the + square drawn on mySprite is tapped on a touch-enabled screen: + +Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +var myTextField:TextField = new TextField(); + +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); + +function taphandler(e:TouchEvent): void { + myTextField.text = "I've been tapped"; + myTextField.y = 50; + addChild(myTextField); +} +flash.display.InteractiveObject.touchTapTouchEvent + Creates an Event object that contains information about touch events.typeString The type of the event. Possible values are: TouchEvent.TOUCH_BEGIN, + TouchEvent.TOUCH_END, TouchEvent.TOUCH_MOVE, + TouchEvent.TOUCH_OUT, TouchEvent.TOUCH_OVER, + TouchEvent.TOUCH_ROLL_OUT, TouchEvent.TOUCH_ROLL_OVER, + and TouchEvent.TOUCH_TAP. + + bubblesBooleantrue Determines whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + touchPointIDint0A unique identification number (as an int) assigned to the touch point. + isPrimaryTouchPointBooleanfalseIndicates whether the first point of contact is mapped to mouse events. + localXNumberunknownThe horizontal coordinate at which the event occurred relative to the containing sprite. + localYNumberunknownThe vertical coordinate at which the event occurred relative to the containing sprite. + sizeXNumberunknownWidth of the contact area. + sizeYNumberunknownHeight of the contact area. + pressureNumberunknownA value between 0.0 and 1.0 indicating force of the contact with the device. + If the device does not support detecting the pressure, the value is 1.0. + relatedObjectflash.display:InteractiveObjectnullThe complementary InteractiveObject instance that is affected by the event. For example, when a touchOut event occurs, + relatedObject represents the display list object to which the pointing device now points. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated (Windows or Linux only). + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + commandKeyBooleanfalse(AIR only) Indicates whether the Command key is activated (Mac only). This parameter is for Adobe AIR only; do not set it for Flash Player content. + controlKeyBooleanfalse(AIR only) Indicates whether the Control or Ctrl key is activated. This parameter is for Adobe AIR only; do not set it for Flash Player content. + + Constructor for TouchEvent objects. + + Creates an Event object that contains information about touch events. + Event objects are passed as parameters to event listeners. + + + clone + Creates a copy of the TouchEvent object and sets the value of each property to match that of the original.A new TouchEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the TouchEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the TouchEvent object.A string that contains all the properties of the TouchEvent object. + + String + Returns a string that contains all the properties of the TouchEvent object. The string is in the following format: +

[TouchEvent type=value bubbles=value cancelable=value ... ]

+ +
updateAfterEvent + Instructs Flash Player or Adobe AIR to render after processing of this event completes, if the display list has been modified. + Instructs Flash Player or Adobe AIR to render after processing of this event completes, if the display list has been modified. + + TOUCH_BEGIN + Defines the value of the type property of a TOUCH_BEGIN touch event object.touchBeginString + Defines the value of the type property of a TOUCH_BEGIN touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchBegin
TOUCH_END + Defines the value of the type property of a TOUCH_END touch event object.touchEndString + Defines the value of the type property of a TOUCH_END touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchEnd
TOUCH_MOVE + Defines the value of the type property of a TOUCH_MOVE touch event object.touchMoveString + Defines the value of the type property of a TOUCH_MOVE touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchMove
TOUCH_OUT + Defines the value of the type property of a TOUCH_OUT touch event object.touchOutString + Defines the value of the type property of a TOUCH_OUT touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchOut
TOUCH_OVER + Defines the value of the type property of a TOUCH_OVER touch event object.touchOverString + Defines the value of the type property of a TOUCH_OVER touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchOver
TOUCH_ROLL_OUT + Defines the value of the type property of a TOUCH_ROLL_OUT touch event object.touchRollOutString + Defines the value of the type property of a TOUCH_ROLL_OUT touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchRollOut
TOUCH_ROLL_OVER + Defines the value of the type property of a TOUCH_ROLL_OVER touch event object.touchRollOverString + Defines the value of the type property of a TOUCH_ROLL_OVER touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
flash.display.InteractiveObject.touchRollOver
TOUCH_TAP + Defines the value of the type property of a TOUCH_TAP touch event object.touchTapString + Defines the value of the type property of a TOUCH_TAP touch event object. + +

The dispatched TouchEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.eventPhaseThe current phase in the event flow.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.pressureA value between 0.0 and 1.0 indicating force of the contact with the device. If the device does not support detecting the pressure, the value is 1.0.relatedObjectA reference to a display list object related to the event.shiftKeytrue if the Shift key is active; false if it is inactive.sizeXWidth of the contact area.sizeYHeight of the contact area.stageXThe horizontal coordinate at which the event occurred in global stage coordinates.stageYThe vertical coordinate at which the event occurred in global stage coordinates.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event.touchPointIDA unique identification number (as an int) assigned to the touch point. + +
The following example displays a message when the + square drawn on mySprite is tapped on a touch-enabled screen: + +Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +var myTextField:TextField = new TextField(); + +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); + +function taphandler(e:TouchEvent): void { + myTextField.text = "I've been tapped"; + myTextField.y = 50; + addChild(myTextField); +} +
flash.display.InteractiveObject.touchTap
altKey + Indicates whether the Alt key is active (true) or inactive (false).Boolean + Indicates whether the Alt key is active (true) or inactive (false). + Supported for Windows and Linux operating systems only. + + commandKey + Indicates whether the command key is activated (Mac only).Boolean + Indicates whether the command key is activated (Mac only). + +

On a Mac OS, the value of the commandKey property + is the same value as the ctrlKey property. + This property is always false on Windows or Linux.

+ +
controlKey + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux.Boolean + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux. + + ctrlKey + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false).Boolean + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false). + On Macintosh, indicates whether either the Control key or the Command key is activated. + + isPrimaryTouchPoint + Indicates whether the first point of contact is mapped to mouse events.Boolean + Indicates whether the first point of contact is mapped to mouse events. + + flash.events.MouseEventisRelatedObjectInaccessible + If true, the relatedObject property is set to null for + reasons related to security sandboxes.Boolean + If true, the relatedObject property is set to null for + reasons related to security sandboxes. If the nominal value of relatedObject is a reference to a + DisplayObject in another sandbox, relatedObject is set to + null unless there is permission in both directions across this sandbox boundary. Permission is + established by calling Security.allowDomain() from a SWF file, or by providing + a policy file from the server of an image file, and setting the LoaderContext.checkPolicyFile + property when loading the image. + + MouseEvent.relatedObjectSecurity.allowDomain()LoaderContext.checkPolicyFilelocalX + The horizontal coordinate at which the event occurred relative to the containing sprite.Number + The horizontal coordinate at which the event occurred relative to the containing sprite. + + localY + The vertical coordinate at which the event occurred relative to the containing sprite.Number + The vertical coordinate at which the event occurred relative to the containing sprite. + + pressure + A value between 0.0 and 1.0 indicating force of the contact with the device.Number + A value between 0.0 and 1.0 indicating force of the contact with the device. + If the device does not support detecting the pressure, the value is 1.0. + + relatedObject + A reference to a display list object that is related to the event.flash.display:InteractiveObject + A reference to a display list object that is related to the event. For example, when a touchOut event occurs, + relatedObject represents the display list object to which the pointing device now points. + This property applies to the touchOut, touchOver, touchRollOut, and touchRollOver events. +

The value of this property can be null in two circumstances: if there is no related object, + or there is a related object, but it is in a security sandbox to which you don't have access. + Use the isRelatedObjectInaccessible() property to determine which of these reasons applies.

+ +
TouchEvent.isRelatedObjectInaccessible
shiftKey + Indicates whether the Shift key is active (true) or inactive + (false).Boolean + Indicates whether the Shift key is active (true) or inactive + (false). + + sizeX + Width of the contact area.Number + Width of the contact area. + + sizeY + Height of the contact area.Number + Height of the contact area. + + stageX + The horizontal coordinate at which the event occurred in global Stage coordinates.Number + The horizontal coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localX property is set. + + stageY + The vertical coordinate at which the event occurred in global Stage coordinates.Number + The vertical coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localY property is set. + + touchPointID + A unique identification number (as an int) assigned to the touch point.int + A unique identification number (as an int) assigned to the touch point. + + The following example establishes a variable touchMoveID to test for the correct touchPointID + value before responding to a touch move event. Otherwise, other touch input triggers the event handler, too. Notice the listeners for + the move and end phases are on the stage, not the display object. The stage listens for the move or end phases in case the user's touch + moves beyond the display object boundaries. + +Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +var myTextField:TextField = new TextField(); +addChild(myTextField); +myTextField.width = 200; +myTextField.height = 20; + +var touchMoveID:int = 0; + +mySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin); +function onTouchBegin(event:TouchEvent) { + if(touchMoveID != 0) { + myTextField.text = "already moving. ignoring new touch"; + return; + } + touchMoveID = event.touchPointID; + + myTextField.text = "touch begin" + event.touchPointID; + stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); + stage.addEventListener(TouchEvent.TOUCH_END, onTouchEnd); +} +function onTouchMove(event:TouchEvent) { + if(event.touchPointID != touchMoveID) { + myTextField.text = "ignoring unrelated touch"; + return; + } + mySprite.x = event.stageX; + mySprite.y = event.stageY; + myTextField.text = "touch move" + event.touchPointID; +} +function onTouchEnd(event:TouchEvent) { + if(event.touchPointID != touchMoveID) { + myTextField.text = "ignoring unrelated touch end"; + return; + } + touchMoveID = 0; + stage.removeEventListener(TouchEvent.TOUCH_MOVE, onTouchMove); + stage.removeEventListener(TouchEvent.TOUCH_END, onTouchEnd); + myTextField.text = "touch end" + event.touchPointID; +} +
ServerSocketConnectEvent + A ServerSocket object dispatches a ServerSocketConnectEvent object when a client attempts + to connect to the server socket.flash.events:Event + A ServerSocket object dispatches a ServerSocketConnectEvent object when a client attempts + to connect to the server socket. + +

The socket property of the ServerSocketConnectEvent object provides the + Socket object to use for subsequent communication between the server and the client. To + deny the connection, call the Socket close() method.

+ +
ServerSocket classServerSocketConnectEvent + Creates a ServerSocketConnectEvent object that contains information about a client connection.typeString The type of the event. Must be: ServerSocketConnectEvent.CONNECT. + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. Always false + cancelableBooleanfalseDetermines whether the Event object can be canceled. Always false. + socketflash.net:SocketnullThe socket for the new connection. + + Creates a ServerSocketConnectEvent object that contains information about a client connection. + + clone + Creates a copy of the ServerSocketConnectEvent object and sets each property's value to match that of the original.A new ServerSocketConnectEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the ServerSocketConnectEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the ServerSocketConnectEvent object.A string that contains all the properties of the ServerSocketConnectEvent object. + String + Returns a string that contains all the properties of the ServerSocketConnectEvent object. + +

The string is in the following format:

+

[ServerSocketConnectEvent type=value bubbles=value cancelable=value + socket=value]

+ +
CONNECT + Defines the value of the type property of a ServerSocketConnectEvent event object.connectStringDispatched by a ServerSocket object when a client connection is received. + + + Defines the value of the type property of a ServerSocketConnectEvent event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalse.cancelablefalse, there is no default behavior to cancel.currentTargetThis ServerSocket object.targetThis ServerSocket object.socketThe Socket object representing the new connection. + +
socket + The socket for the new connection.flash.net:Socket + The socket for the new connection. + +

Use this Socket object for all communication with the client. Your application is responsible for + maintaining a reference to the Socket object. If you don't, the object is eligible for garbage collection and may be + destroyed by the runtime without warning.

+ +
SyncEvent + An SharedObject object representing a remote shared object dispatches a SyncEvent object when the remote + shared object has been updated by the server.Event objects for SyncEvent events. + flash.events:Event + An SharedObject object representing a remote shared object dispatches a SyncEvent object when the remote + shared object has been updated by the server. There is only one type of sync event: + SyncEvent.SYNC. + + SharedObject classsyncflash.events:SyncEvent:SYNCflash.events:SyncEventflash.net.SharedObject.syncSyncEvent + Creates an Event object that contains information about sync events.typeStringThe type of the event. Event listeners can access this information through the inherited type property. There is only one type of sync event: SyncEvent.SYNC. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + changeListArraynullAn array of objects that describe the synchronization with the remote SharedObject. Event listeners can access this object through the changeList property. + + Constructor for SyncEvent objects. + + Creates an Event object that contains information about sync events. + Event objects are passed as parameters to event listeners. + + changeListclone + Creates a copy of the SyncEvent object and sets the value of each property to match that of the original.A new SyncEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the SyncEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the SyncEvent object.A string that contains all the properties of the SyncEvent object. + + String + Returns a string that contains all the properties of the SyncEvent object. The string is in the following format: +

[SyncEvent type=value bubbles=value cancelable=value list=value]

+ +
SYNC + Defines the value of the type property of a sync event object.syncString + Defines the value of the type property of a sync event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.changeListAn array with properties that describe the array's status.targetThe SharedObject instance that has been updated by the server. + +
flash.net.SharedObject.sync
changeList + An array of objects; each object contains properties that describe the changed members of a remote shared object.Array + An array of objects; each object contains properties that describe the changed members of a remote shared object. + The properties of each object are code, name, and oldValue. +

When you initially connect to a remote shared object that is persistent locally and/or on the server, all the + properties of this object are set to empty strings.

Otherwise, Flash sets code to "clear", + "success", "reject", "change", or "delete".

+
  • A value of "clear" means either that you have successfully connected to a remote shared object + that is not persistent on the server or the client, or that all the properties of the object have been deleted--for + example, when the client and server copies of the object are so far out of sync that Flash Player resynchronizes the client + object with the server object. In the latter case, SyncEvent.SYNC is dispatched and the "code" value + is set to "change".
  • A value of "success" means the client changed the shared object.
  • A value of "reject" means the client tried unsuccessfully to change the object; instead, another client changed the object.
  • A value of "change" means another client changed the object or the server resynchronized the object.
  • A value of "delete" means the attribute was deleted.
+

The name property contains the name of the property that has been changed.

+

The oldValue property contains the former value of the changed property. This parameter is + null unless code has a value of "reject" or "change".

+ +
NetConnection classNetStream class
KeyboardEvent + A KeyboardEvent object id dispatched in response to user input through a keyboard.Event objects for Keyboard events. + flash.events:Event + A KeyboardEvent object id dispatched in response to user input through a keyboard. + There are two types of keyboard events: KeyboardEvent.KEY_DOWN and + KeyboardEvent.KEY_UP + +

Because mappings between keys and specific characters vary by device + and operating system, use the TextEvent event type for processing character input.

+ +

To listen globally for key events, listen on the Stage for the capture and target + or bubble phase.

+ +
The following example uses the KeyboardEventExample class to show + keyboard events and their listener functions. The example carries out the following tasks: +
  1. It creates a new Sprite instance named child.
  2. It declares properties for later use in setting a square's background color and size.
  3. Using methods of Sprite, it draws a light-blue square that it displays on the Stage + at default coordinates (0,0) by calling the addChild() method.
  4. It adds one mouse event and two keyboard type event listeners: +
    • click/clickHandler which is dispatched when you click on the square to set focus on the child sprite so it can listen for keyboard events.
    • keyDown/keyDownHandler which is dispatched whenever any key is pressed. The subscriber method prints information about the event + using the trace() statement.
    • keyUp/keyUpHandler which is dispatched when a key is + released.
+ +

When you test this example, you need to click the square first for the keyboard events to work.

+

Also, if you are using the Test Movie command in Flash, the authoring + interface may respond to certain keys instead of the event listeners attached to + the child sprite.

+ +package { + import flash.display.Sprite; + import flash.display.DisplayObject; + import flash.events.*; + + public class KeyboardEventExample extends Sprite { + private var child:Sprite = new Sprite(); + private var bgColor:uint = 0x00CCFF; + private var size:uint = 80; + + public function KeyboardEventExample() { + child.graphics.beginFill(bgColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + addChild(child); + child.addEventListener(MouseEvent.CLICK, clickHandler); + child.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); + child.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler); + + } + + private function clickHandler(event:MouseEvent):void { + stage.focus = child; + } + + private function keyDownHandler(event:KeyboardEvent):void { + trace("keyDownHandler: " + event.keyCode); + trace("ctrlKey: " + event.ctrlKey); + trace("keyLocation: " + event.keyLocation); + trace("shiftKey: " + event.shiftKey); + trace("altKey: " + event.altKey); + + } + + private function keyUpHandler(event:KeyboardEvent):void { + trace("keyUpHandler: " + event.keyCode); + } + + + } +} +
KEY_DOWNKEY_UPKeyLocationkeyDownflash.events:KeyboardEvent:KEY_DOWNflash.events:KeyboardEventflash.display.InteractiveObject.keyDownkeyUpflash.events:KeyboardEvent:KEY_UPflash.events:KeyboardEventflash.display.InteractiveObject.keyUpKeyboardEvent + Creates an Event object that contains specific information about keyboard events.typeString The type of the event. Possible values are: + KeyboardEvent.KEY_DOWN and KeyboardEvent.KEY_UP + + bubblesBooleantrueDetermines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + charCodeValueuint0The character code value of the key pressed or released. The character code values returned are English keyboard values. For example, if you press Shift+3, the Keyboard.charCode() property returns # on a Japanese keyboard, just as it does on an English keyboard. + keyCodeValueuint0The key code value of the key pressed or released. + keyLocationValueuint0The location of the key on the keyboard. + ctrlKeyValueBooleanfalseOn Windows, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyValueBooleanfalseIndicates whether the Alt key modifier is activated (Windows only). + shiftKeyValueBooleanfalseIndicates whether the Shift key modifier is activated. + controlKeyValueBooleanfalseIndicates whether the Control key is activated on Mac, and whether the Control or Ctrl keys are activated on WIndows and Linux. + commandKeyValueBooleanfalseIndicates whether the Command key is activated (Mac only). + + Constructor for KeyboardEvent objects. + + Creates an Event object that contains specific information about keyboard events. + Event objects are passed as parameters to event listeners. + + KEY_DOWNKEY_UPKeyboard.charCodeclone + Creates a copy of the KeyboardEvent object and sets the value of each property to match that of the original.A new KeyboardEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the KeyboardEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the KeyboardEvent object.A string that contains all the properties of the KeyboardEvent object. + + String + Returns a string that contains all the properties of the KeyboardEvent object. The string + is in the following format: +

[KeyboardEvent type=value bubbles=value cancelable=value ... shiftKey=value]

+ +
updateAfterEvent + Indicates that the display should be rendered after processing of this event completes, if the display + list has been modified + + + Indicates that the display should be rendered after processing of this event completes, if the display + list has been modified + + KEY_DOWN + The KeyboardEvent.KEY_DOWN constant defines the value of the type property of a keyDown event object.keyDownString + The KeyboardEvent.KEY_DOWN constant defines the value of the type property of a keyDown event object. + +

This event has the following properties:

+ PropertyValuebubblestruecancelabletrue in AIR, false in Flash Player; + in AIR, canceling this event prevents the character from being entered into a text field.charCodeThe character code value of the key pressed or released.commandKeytrue on Mac if the Command key is active. Otherwise, falsecontrolKeytrue on Windows and Linux if the Ctrl key is active. true on Mac if either the Control key is active. Otherwise, falsectrlKeytrue on Windows and Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.keyCodeThe key code value of the key pressed or released.keyLocationThe location of the key on the keyboard.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance with focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.keyDown
KEY_UP + The KeyboardEvent.KEY_UP constant defines the value of the type property of a keyUp event object.keyUpString + The KeyboardEvent.KEY_UP constant defines the value of the type property of a keyUp event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.charCodeContains the character code value of the key pressed or released.commandKeytrue on Mac if the Command key is active. Otherwise, falsecontrolKeytrue on Windows and Linux if the Ctrl key is active. true on Mac if either the Control key is active. Otherwise, falsectrlKeytrue on Windows if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.keyCodeThe key code value of the key pressed or released.keyLocationThe location of the key on the keyboard.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance with focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.keyUp
altKey + Indicates whether the Alt key is active (true) or inactive (false) on Windows; + indicates whether the Option key is active on Mac OS.Boolean + Indicates whether the Alt key is active (true) or inactive (false) on Windows; + indicates whether the Option key is active on Mac OS. + + charCode + Contains the character code value of the key pressed or released.uint + Contains the character code value of the key pressed or released. + The character code values are English keyboard values. For example, + if you press Shift+3, charCode is # on a Japanese keyboard, + just as it is on an English keyboard. +

Note: When an input method editor (IME) is running, + charCode does not report accurate character codes.

+ +
flash.system.IME
commandKey + Indicates whether the Command key is active (true) or inactive (false).Boolean + Indicates whether the Command key is active (true) or inactive (false). + Supported for Mac OS only. On Mac OS, the commandKey property has the same + value as the ctrlKey property. + + controlKey + Indicates whether the Control key is active (true) or inactive (false).Boolean + Indicates whether the Control key is active (true) or inactive (false). + On Windows and Linux, this is also true when the Ctrl key is active. + + ctrlKey + On Windows and Linux, indicates whether the Ctrl key is active (true) or inactive (false); + On Mac OS, indicates whether either the Ctrl key or the Command key is active.Boolean + On Windows and Linux, indicates whether the Ctrl key is active (true) or inactive (false); + On Mac OS, indicates whether either the Ctrl key or the Command key is active. + + keyCode + The key code value of the key pressed or released.uint + The key code value of the key pressed or released. +

Note: When an input method editor (IME) is running, + keyCode does not report accurate key codes.

+ +
flash.system.IME
keyLocation + Indicates the location of the key on the keyboard.uint + Indicates the location of the key on the keyboard. This is useful for differentiating keys + that appear more than once on a keyboard. For example, you can differentiate between the + left and right Shift keys by the value of this property: KeyLocation.LEFT + for the left and KeyLocation.RIGHT for the right. Another example is + differentiating between number keys pressed on the standard keyboard + (KeyLocation.STANDARD) versus the numeric keypad (KeyLocation.NUM_PAD). + + shiftKey + Indicates whether the Shift key modifier is active (true) or inactive + (false).Boolean + Indicates whether the Shift key modifier is active (true) or inactive + (false). + +
NativeWindowDisplayStateEvent + A NativeWindow object dispatches events of the NativeWindowDisplayStateEvent class when the window + display state changes.Event objects for NativeWindow events that change the display state of the window. + flash.events:Event + A NativeWindow object dispatches events of the NativeWindowDisplayStateEvent class when the window + display state changes. + + There are two types of events: +
  • NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING
  • NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE
+ +
flash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGINGflash.events.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGEdisplayStateChangeflash.events:NativeWindowDisplayStateEvent:DISPLAY_STATE_CHANGEflash.events:NativeWindowDisplayStateEventDispatched by a NativeWindow object after the display state changes. + + flash.display.NativeWindowdisplayStateChangingflash.events:NativeWindowDisplayStateEvent:DISPLAY_STATE_CHANGINGflash.events:NativeWindowDisplayStateEventDispatched by a NativeWindow object before the display state changes. + + flash.display.NativeWindowNativeWindowDisplayStateEvent + Creates an Event object with specific information relevant to window display state events.typeString The type of the event. Possible values are: +
  • NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING
  • NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE
+ +
bubblesBooleantrue Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be cancelled. + beforeDisplayStateStringThe displayState before the change. + afterDisplayStateStringThe displayState after the change. + +
+ Creates an Event object with specific information relevant to window display state events. + Event objects are passed as parameters to event listeners. + +
clone + Creates a copy of the NativeWindowDisplayStateEvent object and sets the + value of each property to match that of the original.A new NativeWindowDisplayStateEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the NativeWindowDisplayStateEvent object and sets the + value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the NativeWindowDisplayStateEvent object.A string that contains all the properties of the NativeWindowDisplayStateEvent object. + String + Returns a string that contains all the properties of the NativeWindowDisplayStateEvent object. The string has the following format: +

[NativeWindowDisplayStateEvent type=value bubbles=value cancelable=value beforeDisplayState=value afterDisplayState=value]

+ +
DISPLAY_STATE_CHANGE + Defines the value of the type property of a displayStateChange event object.displayStateChangeStringDispatched by a NativeWindow object after the display state changes. + + + Defines the value of the type property of a displayStateChange event object. + +

This event has the following properties:

+ + PropertiesValuesafterDisplayStateThe old display state of the window.beforeDisplayStateThe new display state of the window.targetThe NativeWindow instance that has just changed state. + bubblesNo.currentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelablefalse; There is no default behavior to cancel. + +
flash.display.NativeWindow
DISPLAY_STATE_CHANGING + Defines the value of the type property of a displayStateChanging event object.displayStateChangingStringDispatched by a NativeWindow object before the display state changes. + + + Defines the value of the type property of a displayStateChanging event object. + +

This event has the following properties:

+ + PropertiesValuesafterDisplayStateThe display state of the window before the pending change.beforeDisplayStateThe display state of the window after the pending change.targetThe NativeWindow instance that has just changed state. + bubblesNo.currentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelabletrue; canceling the event will prevent the change. + +
flash.display.NativeWindow
afterDisplayState + The display state of the NativeWindow after the change.String + The display state of the NativeWindow after the change. + +

If the event is displayStateChanging, the + display state has not yet changed; afterDisplayState indicates the new + display state if the event is not canceled. If the event is + displayStateChanged, afterDisplayState indicates the current value.

+ +
beforeDisplayState + The display state of the NativeWindow before the change.String + The display state of the NativeWindow before the change. + +

If the event is displayStateChanging, the + display state has not yet changed; beforeDisplayState reflects the Window's + current display state. If the event is displayStateChanged, + beforeDisplayState indicates the previous value.

+ +
VideoEvent + This event class reports the current video rendering status.Reports the current video rendering status. + flash.events:Event +

This event class reports the current video rendering status. Use this event for the following purposes:

+
  • To find out when size of the Video display changes or is initialized. Use this event instead of polling for size changes. + When you receive this event you can access Video.videoSize and Video.videoHeight to get the pixel + dimensions of the video that is currently playing.
  • To find out whether the video is decoded by software or the GPU. If the status property returns "accelerated", + you should switch to using the StageVideo class, if possible.
+
flash.events.StageVideoEventflash.events.StageVideoAvailabilityEventflash.display.Stage.stageVideosflash.media.Videoflash.net.NetStreamWorking with VideoVideoEvent + Constructor. + + typeStringThe type of event. Possible values are: VideoEvent.RENDER_STATE. + bubblesBooleanfalseIndicates whether this Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseIndicates whether you can cancel the action that triggers this event. + statusStringnullThe rendering state of the video. + Constructor. + +

Constructor.

+ +
RENDER_STATE + Defines the value of the type property of a renderState event object.renderStateStringThe identifier for the renderState event of the Video object. + + Defines the value of the type property of a renderState event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event.statusThe rendering status reported by the event.targetThe Video object reporting rendering status. +
RENDER_STATUS_ACCELERATED + For internal use only.acceleratedStringFor internal use only. + +

For internal use only. Use flash.media.VideoStatus.ACCELERATED instead.

+
RENDER_STATUS_SOFTWARE + For internal use only.softwareStringFor internal use only. + +

For internal use only. Use flash.media.VideoStatus.SOFTWARE instead.

+
RENDER_STATUS_UNAVAILABLE + For internal use only.unavailableStringFor internal use only. + +

For internal use only. Use flash.media.VideoStatus.UNAVAILABLE instead.

+
status + Returns the rendering status of the VideoEvent object.StringReturns the rendering status of the VideoEvent object. + +

Returns the rendering status of the VideoEvent object. Possible values include "unavailable", "software", and "accelerated".

+
GestureEvent + The GestureEvent class lets you handle multi-touch events on devices that detect complex user contact with + the device (such as pressing two fingers on a touch screen at the same time).provides event handling support for touch interaction + + flash.events:Event + The GestureEvent class lets you handle multi-touch events on devices that detect complex user contact with + the device (such as pressing two fingers on a touch screen at the same time). + When a user interacts with a device such as a mobile phone or tablet with a touch screen, the user typically + touches and moves across the screen with his or her fingers or a pointing device. You can develop applications that respond to + this user interaction with the GestureEvent and TransformGestureEvent classes. Create event listeners using the event types defined here, or in + the related TouchEvent and TransformGestureEvent classes. And, use the properties and methods of these classes + to construct event handlers that respond to the user touching the device. +

Use the Multitouch class to determine the current environment's support for touch interaction, and to + manage the support of touch interaction if the current environment supports it.

+

Note: When objects are nested on the display list, touch events target the deepest possible + nested object that is visible in the display list. This object is called the target node. To have a target node's + ancestor (an object containing the target node in the display list) receive notification of a touch event, use + EventDispatcher.addEventListener() on the ancestor node with the type parameter set to the specific + touch event you want to detect.

+
The following example shows event handling for the GESTURE_TWO_FINGER_TAP event. + While the user performs a two-finger tap gesture, mySprite rotates and myTextField populates with the phase all, + which is the only phase for two-finger tap events. Other gestures from the TransformGestureEvent class support begin, update, + and end phases. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(GestureEvent.GESTURE_TWO_FINGER_TAP , onTwoFingerTap ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onTwoFingerTap(evt:GestureEvent):void { + + evt.target.rotation -= 45; + myTextField.text = evt.phase; //"all" + +} +
flash.ui.Multitouchflash.events.TouchEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()gestureTwoFingerTapflash.events:GestureEvent:GESTURE_TWO_FINGER_TAPflash.events:GestureEventflash.display.InteractiveObject.gestureTwoFingerTapflash.events.GesturePhaseGestureEvent + Creates an Event object that contains information about multi-touch events + (such as pressing two fingers on a touch screen at the same time).typeString The type of the event. The supported value is: GestureEvent.GESTURE_TWO_FINGER_TAP. + + bubblesBooleantrue Determines whether the Event object participates in the bubbling phase of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + phaseStringnullA value from the GesturePhase class indicating the progress of the touch gesture (begin, update, end, or all). + localXNumber0The horizontal coordinate at which the event occurred relative to the containing sprite. + localYNumber0The vertical coordinate at which the event occurred relative to the containing sprite. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key is activated. On Mac, indicates whether either the Ctrl key or the Command key is activated. + altKeyBooleanfalseIndicates whether the Alt key is activated (Windows or Linux only). + shiftKeyBooleanfalseIndicates whether the Shift key is activated. + commandKeyBooleanfalse(AIR only) Indicates whether the Command key is activated (Mac only). This parameter is for Adobe AIR only; do not set it for Flash Player content. + controlKeyBooleanfalse(AIR only) Indicates whether the Control or Ctrl key is activated. This parameter is for Adobe AIR only; do not set it for Flash Player content. + + Constructor for GestureEvent objects. + + Creates an Event object that contains information about multi-touch events + (such as pressing two fingers on a touch screen at the same time). + Event objects are passed as parameters to event listeners. + + + flash.events.GesturePhaseclone + Creates a copy of the GestureEvent object and sets the value of each property to match that of the original.A new GestureEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the GestureEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the GestureEvent object.A string that contains all the properties of the GestureEvent object. + + String + Returns a string that contains all the properties of the GestureEvent object. The string is in the following format: +

[GestureEvent type=value bubbles=value cancelable=value ... ]

+ +
updateAfterEvent + Refreshes the Flash runtime display after processing the gesture event, in case the display list has been modified by the event handler. + Refreshes the Flash runtime display after processing the gesture event, in case the display list has been modified by the event handler. + + GESTURE_TWO_FINGER_TAP + Defines the value of the type property of a GESTURE_TWO_FINGER_TAP gesture event object.gestureTwoFingerTapString + Defines the value of the type property of a GESTURE_TWO_FINGER_TAP gesture event object. + +

The dispatched GestureEvent object has the following properties:

+ + PropertyValuealtKeytrue if the Alt key is active (Windows or Linux).bubblestruecancelablefalse; there is no default behavior to cancel.commandKey(AIR only) true on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.phaseThe current phase in the event flow. For two-finger tap events, + this value is always all corresponding to the value GesturePhase.ALL once the event is dispatched.isRelatedObjectInaccessibletrue if the relatedObject property is set to null because of security sandbox rules.localXThe horizontal coordinate at which the event occurred relative to the containing sprite.localYThe vertical coordinate at which the event occurred relative to the containing sprite.shiftKeytrue if the Shift key is active; false if it is inactive.targetThe InteractiveObject instance under the touching device. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.display.InteractiveObject.gestureTwoFingerTapflash.events.GesturePhase
altKey + Indicates whether the Alt key is active (true) or inactive (false).Boolean + Indicates whether the Alt key is active (true) or inactive (false). + Supported for Windows and Linux operating systems only. + + commandKey + Indicates whether the command key is activated (Mac only).Boolean + Indicates whether the command key is activated (Mac only). + +

On a Mac OS, the value of the commandKey property + is the same value as the ctrlKey property. + This property is always false on Windows or Linux.

+ +
controlKey + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux.Boolean + Indicates whether the Control key is activated on Mac and whether the Ctrl key is activated on Windows or Linux. + + ctrlKey + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false).Boolean + On Windows or Linux, indicates whether the Ctrl key is active (true) or inactive (false). + On Macintosh, indicates whether either the Control key or the Command key is activated. + + localX + The horizontal coordinate at which the event occurred relative to the containing sprite.Number + The horizontal coordinate at which the event occurred relative to the containing sprite. + + localY + The vertical coordinate at which the event occurred relative to the containing sprite.Number + The vertical coordinate at which the event occurred relative to the containing sprite. + + phase + A value from the GesturePhase class indicating the progress of the touch gesture.String + A value from the GesturePhase class indicating the progress of the touch gesture. For most gestures, + the value is begin, update, or end. For the swipe and two-finger tap gestures, + the phase value is always all once the event is dispatched. + Use this value to determine when an event handler responds to a complex user interaction, or responds in + different ways depending on the current phase of a multi-touch gesture (such as expanding, moving, and "dropping" as + a user touches and drags a visual object across a screen). + + flash.events.GesturePhaseshiftKey + Indicates whether the Shift key is active (true) or inactive + (false).Boolean + Indicates whether the Shift key is active (true) or inactive + (false). + + stageX + The horizontal coordinate at which the event occurred in global Stage coordinates.Number + The horizontal coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localX property is set. + + stageY + The vertical coordinate at which the event occurred in global Stage coordinates.Number + The vertical coordinate at which the event occurred in global Stage coordinates. + This property is calculated when the localY property is set. + +
FullScreenEvent +The Stage object dispatches a FullScreenEvent object whenever the Stage enters or leaves full-screen display mode.Event objects for FullScreenEvent events. +flash.events:ActivityEvent +The Stage object dispatches a FullScreenEvent object whenever the Stage enters or leaves full-screen display mode. +There is only one type of fullScreen event: FullScreenEvent.FULL_SCREEN. + +flash.display.Stage.displayStatefullScreenflash.events:FullScreenEvent:FULL_SCREENflash.events:FullScreenEventflash.display.Stage.displayStateFullScreenEvent + Creates an event object that contains information about fullScreen events.typeString The type of the event. Event listeners can access this information through the + inherited type property. There is only one type of fullScreen event: + FullScreenEvent.FULL_SCREEN. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + fullScreenBooleanfalseIndicates whether the device is activating (true) or + deactivating (false). Event listeners can access this information through the + activating property. + + Constructor for FullScreenEvent objects. + + Creates an event object that contains information about fullScreen events. + Event objects are passed as parameters to event listeners. + + FullScreenEvent.FULL_SCREENclone + Creates a copy of a FullScreenEvent object and sets the value of each property to match that of + the original.A new FullScreenEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of a FullScreenEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the FullScreenEvent object.A string that contains all the properties of the FullScreenEvent object. + + String + Returns a string that contains all the properties of the FullScreenEvent object. The following + format is used: +

[FullScreenEvent type=value bubbles=value cancelable=value + activating=value]

+ +
FULL_SCREEN + The FullScreenEvent.FULL_SCREEN constant defines the value of the type property of a fullScreen event object.fullScreenString + The FullScreenEvent.FULL_SCREEN constant defines the value of the type property of a fullScreen event object. +

This event has the following properties:

+ PropertyValuefullScreentrue if the display state is full screen or false if it is normal.bubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe Stage object. + +
flash.display.Stage.displayState
fullScreen + Indicates whether the Stage object is in full-screen mode (true) or not (false).Boolean + Indicates whether the Stage object is in full-screen mode (true) or not (false). + +
StageVideoAvailabilityEvent + This event fires when the state of the Stage.stageVideos property changes.Reports the current availability of stage video. + flash.events:Event +

This event fires when the state of the Stage.stageVideos property changes. + This property can change when a user expands a video to full screen display from a wmode + that does not support StageVideo (for example, wmode=normal, wmode=opaque, or + wmode=transparent). Expanding to full screen can cause the Stage.stageVideos + vector to become populated. Conversely, exiting full screen display can cause the Stage.stageVideos + vector to become empty.

+

NOTE: This notification occurs only when the state of the Stage.stageVideos property changes. + As a result, behavior may vary according to platform and browser. On Windows, for example, + the stageVideoAvailability event is not dispatched when you go into full screen mode while + wmode is set to direct. On some other platforms, however, the same behavior causes Flash Player + to reallocate resources. In those cases, the Stage.stageVideos property state changes, and the event fires. + You can detect changes to full screen mode by listening to the flash.events.FullScreenEvent event. This event is dispatched + by the Stage object.

+ +
flash.events.StageVideoEventflash.media.StageVideoAvailabilityflash.events.VideoEventflash.events.FullScreenEventflash.display.Stage.stageVideosflash.events.FullScreenEventflash.media.Videoflash.net.NetStreamWorking with VideoStageVideoAvailabilityEvent + Constructor. + + typeStringThe type of event. Possible values are: StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY. + bubblesBooleanfalseIndicates whether this Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseIndicates whether you can cancel the action that triggers this event. + availabilityStringnullThe current availability of stage video. + Constructor. +

Constructor.

+ +
STAGE_VIDEO_AVAILABILITY + Defines the value of the type property of a stageVideoAvailability event object.stageVideoAvailabilityStringThe identifier for the stageVideoAvailability event of the Stage object. + + Defines the value of the type property of a stageVideoAvailability event object. +

This event has the following properties:

+ PropertyValueavailabilityThe status reported by the event.bubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event.targetThe Stage object reporting on the availability of stage video. +
availability + Reports the current availability of stage video using a constant of the flash.media.StageVideoAvailability class. + StringReports the current availability of stage video. + +

Reports the current availability of stage video using a constant of the flash.media.StageVideoAvailability class.

+
DatagramSocketDataEvent + A DatagramSocketDataEvent object is dispatched when Datagram socket has received data.flash.events:Event + A DatagramSocketDataEvent object is dispatched when Datagram socket has received data. + + DatagramSocket classdataflash.events:DatagramSocketDataEvent:DATAflash.events:DatagramSocketDataEventDispatched by a DatagramSocket object when a UDP packet is received. + + flash.net.DatagramSocket.dataDatagramSocketDataEvent + Creates an Event object that contains information about datagram events.typeString The type of the event. Possible values are:DatagramSocketDataEvent.DATA + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + + srcAddressStringThe IP address of the machine that sent the packet. + srcPortint0The port on the machine that sent the packet. + dstAddressStringThe IP address to which the packet is addressed. + dstPortint0The port to which the packet is addressed. + dataflash.utils:ByteArraynullThe datagram packet data. + + Creates an Event object that contains information about datagram events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the DatagramSocketDataEvent object and sets each property's value to match that of the original.A new DatagramSocketDataEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the DatagramSocketDataEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the DatagramSocketDataEvent object.A string that contains all the properties of the ProgressEvent object. + String + Returns a string that contains all the properties of the DatagramSocketDataEvent object. + + The string is in the following format: +

[DatagramSocketDataEvent type=value bubbles=value cancelable=value srcAddress=value srcPort=value dstAddress=value dstPort=value data=value]

+ +
DATA + Defines the value of the type property of a data event object.dataStringDispatched by a DatagramSocket object when a UDP packet is received. + + + Defines the value of the type property of a data event object. + + flash.net.DatagramSocket.datadata + The datagram packet data.flash.utils:ByteArray + The datagram packet data. + + dstAddress + The IP address of the DatagramSocket object that dispatched this event.String + The IP address of the DatagramSocket object that dispatched this event. + +

Note: If the socket is bound to the special address: 0.0.0.0, then this property + will return 0.0.0.0. In order to know the specific IP to which the datagram message is sent, + you must bind the socket to an explicit IP address.

+ +
dstPort + The port of the DatagramSocket object that dispatched this event.int + The port of the DatagramSocket object that dispatched this event. + + srcAddress + The IP address of the machine that sent the packet.String + The IP address of the machine that sent the packet. + + srcPort + The port on the machine that sent the packet.int + The port on the machine that sent the packet. + +
DRMStatusEvent + + A NetStream object dispatches a DRMStatusEvent object when the content protected using + digital rights management (DRM) begins playing successfully (when the voucher is + verified, and when the user is authenticated and authorized to view the content).Event objects for DRM-enabled objects. + flash.events:Event + + A NetStream object dispatches a DRMStatusEvent object when the content protected using + digital rights management (DRM) begins playing successfully (when the voucher is + verified, and when the user is authenticated and authorized to view the content). + The DRMStatusEvent object contains information related to the voucher, such as + whether the content can be made available offline or when the voucher will expire + and the content can no longer be viewed. The application can use this data to + inform the user of the status of her policy and permissions. + + flash.net.NetStreamDRMStatusEvent.DRM_STATUSflash.net.drm.DRMManagerflash.net.drm.DRMVoucherdrmStatusflash.events:DRMStatusEvent:DRM_STATUSflash.events:DRMStatusEventDispatched by a NetStream object when DRM-protected content begins playing. + DRMStatusEvent + Creates an Event object that contains specific information about DRM status events.typeStringunknown The type of the event. Event listeners can access this information through the inherited type property. There is only one type of DRMAuthenticate event: DRMAuthenticateEvent.DRM_AUTHENTICATE. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + inMetadataflash.net.drm:DRMContentDatanullThe custom object that contains custom DRM properties. + inVoucherflash.net.drm:DRMVouchernullThe context of the Event. + inLocalBooleanfalseIndicates if content can be viewed offline. + + Creates an Event object that contains specific information about DRM status events. + Event objects are passed as parameters to event listeners. + + + clone + Creates a copy of the DRMStatusEvent object and sets the value of each property to match + that of the original.A new DRMStatusEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the DRMStatusEvent object and sets the value of each property to match + that of the original. + + toString + Returns a string that contains all the properties of the DRMStatusEvent object.A string that contains all the properties of the DRMStatusEvent object. + String + Returns a string that contains all the properties of the DRMStatusEvent object. + DRM_STATUS + The DRMStatusEvent.DRM_STATUS constant defines the value of the + type property of a drmStatus event object.drmStatusStringDispatched by a NetStream object when DRM-protected content begins playing. + + The DRMStatusEvent.DRM_STATUS constant defines the value of the + type property of a drmStatus event object. + + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.detailA string explaining the context of the status event.isAnonymousIndicates whether the content protected with DRM + encryption is available without requiring a user to provide authentication credentials.isAvailableOfflineIndicates whether the content protected with DRM + encryption is available offline.offlineLeasePeriodThe remaining number of days that content can be + viewed offline.policiesA custom object of the DRM status event.targetThe NetStream object.voucherEndDateThe absolute date on which the voucher expires + and the content can no longer be viewed by userscontentDataThe DRMContentData for the contentvoucherThe DRMVoucher object for the content.isLocalIndicates whether the content is stored on the local file system + + +
contentData + A DRMContentData object containing the information necessary + to obtain a voucher for viewing the DRM-protected content.flash.net.drm:DRMContentData + A DRMContentData object containing the information necessary + to obtain a voucher for viewing the DRM-protected content. + + detail + A string explaining the context of the status event.String + A string explaining the context of the status event. + + isAnonymous + Indicates whether the content, protected with digital rights management (DRM) encryption, is available + without requiring a user to provide authentication credentials.Boolean + Indicates whether the content, protected with digital rights management (DRM) encryption, is available + without requiring a user to provide authentication credentials. If so, the value is + true. Otherwise, the value is false, and a user must provide a username + and password that matches the one known and expected by the content provider. + + isAvailableOffline + Indicates whether the content, protected with digital rights management (DRM) encryption, is available + offline.Boolean + Indicates whether the content, protected with digital rights management (DRM) encryption, is available + offline. If so, the value is true. Otherwise, the value is false. +

+ In order for digitally protected content to be available offline, its voucher must be cached to the user's + local machine. (The application decides where to store the content locally in order for it to be available + offline.) +

+ +
isLocal + Indicates whether the voucher is cached in the local voucher store.Boolean + Indicates whether the voucher is cached in the local voucher store. + + offlineLeasePeriod + The remaining number of days that content can be viewed offline.uint + The remaining number of days that content can be viewed offline. + + policies + A custom object of the DRM status event.Object + A custom object of the DRM status event. + + voucherEndDate + The absolute date on which the voucher expires and the content can no longer be viewed by users.Date + The absolute date on which the voucher expires and the content can no longer be viewed by users. + + voucher + A DRMVoucher object for the content.flash.net.drm:DRMVoucher + A DRMVoucher object for the content. + +
AsyncErrorEvent + An object dispatches an AsyncErrorEvent when an exception is thrown from native + asynchronous code, which could be from, for example, LocalConnection, NetConnection, + SharedObject, or NetStream.Event objects for AsyncErrorEvent events. + flash.events:ErrorEvent + An object dispatches an AsyncErrorEvent when an exception is thrown from native + asynchronous code, which could be from, for example, LocalConnection, NetConnection, + SharedObject, or NetStream. There is only one type of asynchronous error event: + AsyncErrorEvent.ASYNC_ERROR. + + ASYNC_ERRORasyncErrorflash.events:AsyncErrorEvent:ASYNC_ERRORflash.events:AsyncErrorEventAsyncErrorEvent + Creates an AsyncErrorEvent object that contains information about asyncError events.typeString The type of the event. Event listeners can access this information through + the inherited type property. There is only one type of error event: + ErrorEvent.ERROR. + + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access + this information through the inherited bubbles property. + + + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners + can access this information through the inherited cancelable property. + + textStringText to be displayed as an error message. Event listeners can access this + information through the text property. + + errorErrornullThe exception that occurred. + If error is non-null, the event's errorId property is set from the error's + errorId property. + + Constructor for AsyncErrorEvent objects. + + + Creates an AsyncErrorEvent object that contains information about asyncError events. + AsyncErrorEvent objects are passed as parameters to event listeners. + + clone + Creates a copy of the AsyncErrorEvent object and sets the value of each property to match + that of the original.A new AsyncErrorEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the AsyncErrorEvent object and sets the value of each property to match + that of the original. + + toString + Returns a string that contains all the properties of the AsyncErrorEvent object.A string that contains all the properties of the AsyncErrorEvent object. + + String + Returns a string that contains all the properties of the AsyncErrorEvent object. The + string is in the following format: +

[AsyncErrorEvent type=value bubbles=value + cancelable=value ... error=value errorID=value] + The errorId is only available in Adobe AIR

+ +
ASYNC_ERROR + The AsyncErrorEvent.ASYNC_ERROR constant defines the value of the + type property of an asyncError event object.asyncErrorString + The AsyncErrorEvent.ASYNC_ERROR constant defines the value of the + type property of an asyncError event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default + behavior to cancel. currentTargetThe object that is actively processing the + Event object with an event listener. targetThe object dispatching the event.errorThe error that triggered the event. + +
error + The exception that was thrown.Error + The exception that was thrown. + +
StatusEvent + An object dispatches a StatusEvent object when a device, such as a camera or microphone, or an object such as a LocalConnection object reports its status.Event objects for StatusEvent events. + flash.events:Event + An object dispatches a StatusEvent object when a device, such as a camera or microphone, or an object such as a LocalConnection object reports its status. There is only one type of status event: StatusEvent.STATUS. + + flash.media.Cameraflash.media.Microphoneflash.net.LocalConnectionflash.sensors.Accelerometerflash.sensors.Geolocationair.net.ServiceMonitorstatusflash.events:StatusEvent:STATUSflash.events:StatusEventflash.media.Camera.statusflash.media.Microphone.statusflash.net.LocalConnection.statusflash.net.NetStream.statusflash.sensors.Geolocation.statusflash.sensors.Accelerometer.statusStatusEvent + Creates an Event object that contains information about status events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of status event: StatusEvent.STATUS. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + codeStringA description of the object's status. Event listeners can access this information through the code property. + levelStringThe category of the message, such as "status", "warning" or "error". Event listeners can access this information through the level property. + + Constructor for StatusEvent objects. + + Creates an Event object that contains information about status events. + Event objects are passed as parameters to event listeners. + + STATUSclone + Creates a copy of the StatusEvent object and sets the value of each property to match that of the original.A new StatusEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the StatusEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the StatusEvent object.A string that contains all the properties of the StatusEvent object. + + String + Returns a string that contains all the properties of the StatusEvent object. The string is in the following format: +

[StatusEvent type=value bubbles=value cancelable=value code=value level=value]

+ +
STATUS + Defines the value of the type property of a status event object.statusString + Defines the value of the type property of a status event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.codeA description of the object's status.currentTargetThe object that is actively processing the Event + object with an event listener.levelThe category of the message, such as "status", "warning" or "error".targetThe object reporting its status. + +
flash.media.Camera.statusflash.media.Microphone.statusflash.net.LocalConnection.statusflash.net.NetStream.statusflash.sensors.Geolocation.statusflash.sensors.Accelerometer.status
code + A description of the object's status.String + A description of the object's status. + + flash.media.Cameraflash.media.Microphoneflash.net.LocalConnectionlevel + The category of the message, such as "status", "warning" or "error".String + The category of the message, such as "status", "warning" or "error". + + flash.media.Cameraflash.media.Microphoneflash.net.LocalConnection
DRMAuthenticationErrorEvent + The DRMManager dispatches a DRMAuthenticationErrorEvent object when a call to the authenticate() + method of the DRMManager object fails.flash.events:ErrorEvent + The DRMManager dispatches a DRMAuthenticationErrorEvent object when a call to the authenticate() + method of the DRMManager object fails. + + DRMAuthenticationErrorEvent + Creates a new instance of a DRMAuthenticationErrorEvent object.typeStringthe event type string + bubblesBooleanfalsewhether the event bubbles up the display list + cancelableBooleanfalsewhether the event can be canceled + inDetailStringThe error description + inErrorIDint0The ID of the general type of error + inSubErrorIDint0The ID indicating the specific error within its type + inServerURLStringnullthe URL of the logged-in server + inDomainStringnullthe authenticated domain on the logged-in server + + + Creates a new instance of a DRMAuthenticationErrorEvent object. + + clone + Creates a copy of the ErrorEvent object and sets the value of each property to match that of the original.A new ErrorEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the ErrorEvent object and sets the value of each property to match that of the original. + + AUTHENTICATION_ERROR + The string constant to use for the authentication error event + in the type parameter when adding and removing event listeners.authenticationErrorString + The string constant to use for the authentication error event + in the type parameter when adding and removing event listeners. + + domain + The content domain of the media rights server.String + The content domain of the media rights server. Here, domain is not a network or Internet domain name. + + serverURL + The URL of the media rights server that rejected the authentication attempt.String + The URL of the media rights server that rejected the authentication attempt. + + subErrorID + A more detailed error code.int + A more detailed error code. + + HTMLUncaughtScriptExceptionEvent + An HTMLLoader object dispatches an HTMLUncaughtScriptExceptionEvent object whenever a JavaScript exception + is thrown and not handled with a catch statement.flash.events:Event + An HTMLLoader object dispatches an HTMLUncaughtScriptExceptionEvent object whenever a JavaScript exception + is thrown and not handled with a catch statement. + + HTMLLoaderuncaughtScriptExceptionflash.events:HTMLUncaughtScriptExceptionEvent:UNCAUGHT_SCRIPT_EXCEPTIONflash.events:HTMLUncaughtScriptExceptionEventHTMLUncaughtScriptExceptionEvent + Creates an HTMLUncaughtScriptExceptionEvent object to pass as a parameter to event listeners.exceptionValueWhen a JavaScript process throws an uncaught exception, the + exceptionValue is the result of evaluating the expression in the throw + statement that resulted in the uncaught exception. The exceptionValue + property can be a primitive value, a reference to a JavaScript object, or a reference to an + ActionScript object. + + + Creates an HTMLUncaughtScriptExceptionEvent object to pass as a parameter to event listeners. + + clone + + Creates a copy of the HTMLUncaughtScriptExceptionEvent object and sets + the value of each property to match that of the original.The copy of the HTMLUncaughtScriptExceptionEvent object. + + flash.events:Event + + Creates a copy of the HTMLUncaughtScriptExceptionEvent object and sets + the value of each property to match that of the original. + + UNCAUGHT_SCRIPT_EXCEPTION + The HTMLUncaughtScriptExceptionEvent.UNCAUGHT_SCRIPT_EXCEPTION constant + defines the value of the type property of an + uncaughtScriptException event object.uncaughtScriptException + The HTMLUncaughtScriptExceptionEvent.UNCAUGHT_SCRIPT_EXCEPTION constant + defines the value of the type property of an + uncaughtScriptException event object. + + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.exceptionValueThe result of evaluating the expression in the throw + statement that resulted in the uncaught exception.stackTraceAn array of objects that represent the stack trace + at the time the throw statement that resulted in the uncaught exception was executed.targetThe HTMLLoader object. + +
exceptionValue + The result of evaluating the expression in the throw statement that resulted in the + uncaught exception. + The result of evaluating the expression in the throw statement that resulted in the + uncaught exception. The exceptionValue property can be a primitive + value, a reference to a JavaScript object, or a reference to an ActionScript object. + + stackTrace + An array of objects that represent the stack trace at the time the throw statement + that resulted in the uncaught exception was executed.Array + An array of objects that represent the stack trace at the time the throw statement + that resulted in the uncaught exception was executed. Each object in the array has + three properties: + +
  • sourceURL (a string): The URL of the script of the call stack frame.
  • line (a number): The line number in the sourceURL + resource of the call stack frame.
  • functionName (a string): The name of the function for the call stack frame.
+ +
SoftKeyboardEvent +A SoftKeyboardEvent object is dispatched when a virtual keyboard is activated or deactivated.A SoftKeyboardEvent is dispatched when a soft keyboard is activated or deactivated. + +flash.events:Event +A SoftKeyboardEvent object is dispatched when a virtual keyboard is activated or deactivated. + +

SoftKeyboardEvents are dispatched by TextFields and by InteractiveObjects that have their +needsSoftKeyboardproperty set to true.

+ +
flash.display.InteractiveObject.needsSoftKeyboardSoftKeyboardEvent + Creates an event object that contains information about soft keyboard activation and deactivation events.typeString The type of the event as a constant value (such as SOFT_KEYBOARD_ACTIVATE). + Event listeners can access this information through the + inherited type property. + bubblesBooleanDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + relatedObjectValflash.display:InteractiveObjectA reference to a display list object that is related to the event. + triggerTypeValStringIndicates whether the keyboard event was triggered by an application or user. + + Constructor for SoftKeyboardEvent objects. + + + Creates an event object that contains information about soft keyboard activation and deactivation events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of a SoftKeyboardEvent object and sets the value of each property to match that of + the original.A new SoftKeyboardEvent object with property values that match those of the original. + + flash.events:EventCreates a copy of a SoftKeyboardEvent object. + + Creates a copy of a SoftKeyboardEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the SoftKeyboardEvent object.A string that contains all the properties of the SoftKeyboardEvent object. + + String + Returns a string that contains all the properties of the SoftKeyboardEvent object. The following + format is used: +

[SoftKeyboardEvent type=value bubbles=value cancelable=value relatedObjectVal=value + triggerTypeVal=value activating=value]

+ +
SOFT_KEYBOARD_ACTIVATE + The SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE constant defines the value of the + type property of the SoftKeyboardEvent object dispatched when a soft keyboard + is displayed.softKeyboardActivateStringConstant value for an event dispatched when the soft keyboard is displayed. + + The SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE constant defines the value of the + type property of the SoftKeyboardEvent object dispatched when a soft keyboard + is displayed. + +

The softKeyboardActivate event is dispatched after the softKeyboardActivating event and + cannot be canceled. To prevent the virtual keyboard from displaying, cancel the softKeyboardActivating event.

+ +

This event has the following properties:

+ PropertyValuetypeSOFT_KEYBOARD_ACTIVATEbubblestruecancelablefalse; it is too late to cancel.relatedObjectValA reference to a display list object that is related to the event.triggerTypeValIndicates whether the keyboard event was triggered by an application or user.currentTargetThe object that is actively processing the Event + object with an event listener. +
SOFT_KEYBOARD_ACTIVATING + The SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING constant defines the value of the + type property of the SoftKeyboardEvent object dispatched immediately before a + soft keyboard is displayed.softKeyboardActivatingStringConstant value for an event dispatched immediately before the soft keyboard is displayed. + + The SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING constant defines the value of the + type property of the SoftKeyboardEvent object dispatched immediately before a + soft keyboard is displayed. If canceled by calling preventDefault, + the soft keyboard does not open. + +

This event has the following properties:

+ PropertyValuetypeSOFT_KEYBOARD_ACTIVATINGbubblestruecancelabletrue; canceling prevents the keyboard from opening.relatedObjectValA reference to a display list object that is related to the event.triggerTypeValIndicates whether the keyboard event was triggered by an application or user.currentTargetThe object that is actively processing the Event + object with an event listener. +
SOFT_KEYBOARD_DEACTIVATE + The SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE constant defines the value of the + type property of the SoftKeyboardEvent object dispatched when a soft keyboard + is lowered or hidden..softKeyboardDeactivateStringConstant value for an event dispatched after the soft keyboard is lowered or hidden. + + The SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE constant defines the value of the + type property of the SoftKeyboardEvent object dispatched when a soft keyboard + is lowered or hidden.. + +

This event has the following properties:

+ PropertyValuetypeSOFT_KEYBOARD_DEACTIVATEbubblestruecancelablefalse; canceling is not allowed.relatedObjectValA reference to a display list object that is related to the event.triggerTypeValIndicates whether the keyboard event was triggered by an application or user.currentTargetThe object that is actively processing the Event + object with an event listener. +
relatedObject + A reference to a display list object that is related to the event.flash.display:InteractiveObjectA reference to a display list object that is related to the event. + + A reference to a display list object that is related to the event. + + triggerType + Indicates whether the change in keyboard status has been triggered by + an application (such as programmatic use of requestSoftKeyboard()) or by the user + (such as selecting a text field).StringThe source of the change in keyboard status. + + Indicates whether the change in keyboard status has been triggered by + an application (such as programmatic use of requestSoftKeyboard()) or by the user + (such as selecting a text field). + + flash.events.SoftKeyboardTrigger
ProgressEvent + A ProgressEvent object is dispatched when a load operation has begun or a socket has received data.Event objects for ProgressEvent events. + flash.events:Event + A ProgressEvent object is dispatched when a load operation has begun or a socket has received data. + These events are usually generated when SWF files, images or data are loaded into an application. + There are two types of progress events: + ProgressEvent.PROGRESS and ProgressEvent.SOCKET_DATA. + Additionally, in AIR ProgressEvent objects are dispatched + when a data is sent to or from a child process using the NativeProcess class. + + The following example uses the ProgressEventExample class to illustrate how various + event listeners are used when a file is being downloaded. The example carries out the following tasks: +
  1. The properties downloadURL and fileName are created, which indicate the location + and name of the download file.
  2. In the ProgressEventExample constructor, a new FileReference object named file is + created and then passed to the configureListeners() method.
  3. The downloadURL and fileName properties are then passed to file.download(), + which prompts for the location to download the file.
  4. The configureListeners() method adds seven event listeners and their associated subscriber + methods: +
    1. cancel/cancelHandler() is dispatched if the file download is canceled.
    2. complete/complereHandler() is dispatched when the file download process is + finished.
    3. ioError/ioErrorHandler() is dispatched if the download file is unavailable or + inaccessible.
    4. open/openHandler() is dispatched when the download operation has started.
    5. progress/progressHandler() is dispatched when the download process begins and again + when it ends.
    6. securityError/securityErrorHandler is dispatched if the local playback + security setting does not match the type of data access for the download file (local versus network); + see the notes below.
    7. select/selectHandler() is dispatched when the download object is selected.
    +
+

Notes: +

  • You need to compile the SWF file with Local Playback Security set to Access Network Files Only.
  • This example requires a file named SomeFile.pdf.
  • Although this example makes use of all events available to the FileReference object, most situations + require only a subset.
+

+ + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class ProgressEventExample extends Sprite { + private var downloadURL:String = "http://www.[yourDomain].com/SomeFile.pdf"; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function ProgressEventExample() { + var request:URLRequest = new URLRequest(downloadURL); + file = new FileReference(); + configureListeners(file); + file.download(request, fileName); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CANCEL, cancelHandler); + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(Event.SELECT, selectHandler); + } + + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + downloadURL); + } + } +} +
FileStream classLoaderInfo classSocket classprogressflash.events:ProgressEvent:PROGRESSflash.events:ProgressEventflash.display.LoaderInfo.progressflash.media.Sound.progressflash.net.FileReference.progressflash.net.URLLoader.progressflash.net.URLStream.progresssocketDataflash.events:ProgressEvent:SOCKET_DATAflash.events:ProgressEventflash.net.Socket.socketDataerrorDataflash.events:ProgressEvent:STANDARD_ERROR_DATAflash.events:ProgressEventflash.desktop.NativeProcess.standardErrorDataerrorDataflash.events:ProgressEvent:STANDARD_INPUT_PROGRESSflash.events:ProgressEventflash.desktop.NativeProcess.standardInputProgressoutputDataflash.events:ProgressEvent:STANDARD_OUTPUT_DATAflash.events:ProgressEventflash.desktop.NativeProcess.standardOutputDataProgressEvent + Creates an Event object that contains information about progress events.typeString The type of the event. Possible values are:ProgressEvent.PROGRESS, + ProgressEvent.SOCKET_DATA, ProgressEvent.STANDARD_ERROR_DATA, ProgressEvent.STANDARD_INPUT_PROGRESS, and ProgressEvent.STANDARD_OUTPUT_DATA. + + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + bytesLoadedNumber0The number of items or bytes loaded at the time the listener processes the event. + bytesTotalNumber0The total number of items or bytes that will be loaded if the loading process succeeds. + + Constructor for ProgressEvent objects. + + + Creates an Event object that contains information about progress events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the ProgressEvent object and sets each property's value to match that of the original.A new ProgressEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the ProgressEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the ProgressEvent object.A string that contains all the properties of the ProgressEvent object. + + String + Returns a string that contains all the properties of the ProgressEvent object. The string is in the following format: +

[ProgressEvent type=value bubbles=value cancelable=value bytesLoaded=value bytesTotal=value]

+ +
PROGRESS + Defines the value of the type property of a progress event object.progressString + Defines the value of the type property of a progress event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsebytesLoadedThe number of items or bytes loaded at the time the listener processes the event.bytesTotalThe total number of items or bytes that ultimately will be loaded if the loading process succeeds.cancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object reporting progress. + +
flash.display.LoaderInfo.progressflash.media.Sound.progressflash.net.FileReference.progressflash.net.URLLoader.progressflash.net.URLStream.progress
SOCKET_DATA + Defines the value of the type property of a socketData event object.socketDataString + Defines the value of the type property of a socketData event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event.bytesLoadedThe number of items or bytes loaded at the time the listener processes the event.bytesTotal0; this property is not used by socketData event objects.targetThe socket reporting progress. + +
flash.net.Socket.socketData
STANDARD_ERROR_DATA + Defines the value of the type property of a standardErrorData event object.standardErrorDataString + Defines the value of the type property of a standardErrorData event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event.bytesLoadedThe number of bytes of error data buffered by the NativeProcessObject.error due to this event.bytesTotal0; this property is not used by standardErrorData event objects.targetThe NativeProcess object reporting error data. + +
flash.desktop.NativeProcess.standardErrorData
STANDARD_INPUT_PROGRESS + Defines the value of the type property of a standardInputProgress event object.standardInputProgressString + Defines the value of the type property of a standardInputProgress event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event.bytesLoadedThe number of bytes of error data buffered by the NativeProcessObject.error due to this event.bytesTotal0; this property is not used by standardInputProgress event objects.targetThe NativeProcess object reporting error data. + +
flash.desktop.NativeProcess.standardInputProgress
STANDARD_OUTPUT_DATA + Defines the value of the type property of a standardOutputData event object.standardOutputDataString + Defines the value of the type property of a standardOutputData event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event.bytesLoadedThe number of bytes of output data buffered by the NativeProcessObject.output due to this event.bytesTotal0; this property is not used by standardOutputData event objects.targetThe NativeProcess object reporting output data. + +
flash.desktop.NativeProcess.standardOutputData
bytesLoaded + The number of items or bytes loaded when the listener processes the event.Number + The number of items or bytes loaded when the listener processes the event. + + bytesTotal + The total number of items or bytes that will be loaded if the loading process succeeds.Number + The total number of items or bytes that will be loaded if the loading process succeeds. + If the progress event is dispatched/attached to a Socket object, the bytesTotal will always be 0 + unless a value is specified in the bytesTotal parameter of the constructor. + The actual number of bytes sent back or forth is not set and is up to the application developer. + +
ShaderEvent + A ShaderEvent is dispatched when a shader operation launched from + a ShaderJob finishes.flash.events:Event + A ShaderEvent is dispatched when a shader operation launched from + a ShaderJob finishes. + + flash.display.ShaderJobcompleteflash.events:ShaderEvent:COMPLETEflash.events:ShaderEventflash.display.ShaderJob.completeShaderEvent + Creates a ShaderEvent object to pass to event listeners.typeStringThe type of the event, available in the + type property. + + bubblesBooleanfalseDetermines whether the Event object participates + in the bubbling stage of the event flow. The default value + is false. + + cancelableBooleanfalseDetermines whether the Event object can be + canceled. The default value is false. + + bitmapflash.display:BitmapDatanullThe BitmapData object containing the result of the + operation that finished (or null if + the target wasn't a BitmapData object). + + arrayflash.utils:ByteArraynullThe ByteArray object containing the result of the + operation that finished (or null if + the target wasn't a ByteArray object). + + vectornullThe Vector.<Number> instance containing the result of the + operation that finished (or null if + the target wasn't a Vector.<Number> instance). + + + Creates a ShaderEvent object to pass to event listeners. + + clone + Creates a copy of the ShaderEvent object and sets the value of each property + to match that of the original.A new ShaderEvent object with property values that match the values of + the original. + + flash.events:Event + Creates a copy of the ShaderEvent object and sets the value of each property + to match that of the original. + + toString + Returns a string that contains all the properties of the ShaderEvent object.A string that contains all the properties of the ShaderEvent object. + + String + Returns a string that contains all the properties of the ShaderEvent object. + The string is in the following format: + +

[ShaderEvent type=value bubbles=value + cancelable=value eventPhase=value + bitmapData=value byteArray=value vector=value]

+ +
COMPLETE + Defines the value of the type property of a complete event object.completeString + Defines the value of the type property of a complete event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsebitmapDataThe BitmapData object + containing the result of the operation that finished (or + null if the target wasn't a BitmapData object).byteArrayThe ByteArray object containing + the result of the operation that finished (or null if + the target wasn't a ByteArray object).cancelablefalse; there is + no default behavior to cancel.currentTargetThe object that is + actively processing the event object with an event listener.targetThe ShaderJob object reporting completion.vectorThe Vector.<Number> instance + containing the result of the operation that finished (or null if + the target wasn't a Vector.<Number> instance). + +
flash.display.ShaderJob.complete
bitmapData + The BitmapData object that was passed to the ShaderJob.start() method.flash.display:BitmapData + The BitmapData object that was passed to the ShaderJob.start() method. + If a ByteArray or Vector.<Number> was passed to the start() method + this property is null. + + flash.display.ShaderJob.start()byteArray + + The ByteArray object that was passed to the ShaderJob.start() method.flash.utils:ByteArray + + The ByteArray object that was passed to the ShaderJob.start() method. + If a BitmapData or Vector.<Number> object was passed to the start() method + this property is null. + + flash.display.ShaderJob.start()vector + + The Vector.&lt;Number&gt; object that was passed to the ShaderJob.start() method. + + The Vector.<Number> object that was passed to the ShaderJob.start() method. + If a BitmapData or ByteArray object was passed to the start() method + this property is null. + + flash.display.ShaderJob.start()
DRMAuthenticationCompleteEvent + The DRMManager dispatches a DRMAuthenticationCompleteEvent object when a call to the authenticate() + method of the DRMManager object succeeds.flash.events:Event + The DRMManager dispatches a DRMAuthenticationCompleteEvent object when a call to the authenticate() + method of the DRMManager object succeeds. + + DRMAuthenticationCompleteEvent + Creates a new instance of a DRMAuthenticationCompleteEvent object.typeStringthe event type string + bubblesBooleanfalsewhether the event bubbles up the display list + cancelableBooleanfalsewhether the event can be canceled + inServerURLStringnullthe URL of the logged-in server + inDomainStringnullthe authenticated domain on the logged-in server + inTokenflash.utils:ByteArraynullthe authentication token + + + Creates a new instance of a DRMAuthenticationCompleteEvent object. + + clone + Duplicates an instance of an Event subclass.A new Event object that is identical to the original. + flash.events:Event + Duplicates an instance of an Event subclass. + +

Returns a new Event object that is a copy of the original instance of the Event object. + You do not normally call clone(); the EventDispatcher class calls it automatically + when you redispatch an event—that is, when you call dispatchEvent(event) from a handler + that is handling event.

+ +

The new Event object includes all the properties of the original.

+ +

When creating your own custom Event class, you must override the + inherited Event.clone() method in order for it to duplicate the + properties of your custom class. If you do not set all the properties that you add + in your event subclass, those properties will not have the correct values when listeners + handle the redispatched event.

+ +

In this example, PingEvent is a subclass of Event + and therefore implements its own version of clone().

+ + + class PingEvent extends Event { + var URL:String; + + public override function clone():Event { + return new PingEvent(type, bubbles, cancelable, URL); + } + } + + +
AUTHENTICATION_COMPLETE + The string constant to use for the authentication complete event + in the type parameter when adding and removing event listeners.authenticationCompleteString + The string constant to use for the authentication complete event + in the type parameter when adding and removing event listeners. + + domain + The content domain of the media rights server.String + The content domain of the media rights server. Here, domain is not a network or Internet domain name. + + serverURL + The URL of the media rights server.String + The URL of the media rights server. + + token + The authentication token.flash.utils:ByteArray + The authentication token. + +

The authentication is automatically added to the DRMManager session cache. You + can save the token and use it to authenticate the user in a future session. Reuse a + token with the setAuthenticationToken() method of the DRMManager. + Token expiration and other properties are determined by the server generating the token.

+ +
flash.net.drm.DRMManager.setAuthenticationToken()
AccelerometerEvent +The Accelerometer class dispatches AccelerometerEvent objects when acceleration updates are obtained from the Accelerometer sensor installed on the device.flash.events:Event +The Accelerometer class dispatches AccelerometerEvent objects when acceleration updates are obtained from the Accelerometer sensor installed on the device. + +flash.sensors.Accelerometerupdateflash.events:AccelerometerEvent:UPDATEflash.events:AccelerometerEventAccelerometerEvent + Creates an AccelerometerEvent object that contains information about acceleration along three dimensional axis.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of update event: AccelerometerEvent.UPDATE. + bubblesBooleanfalseDetermines whether the Event object bubbles. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + timestampNumber0The timestamp of the Accelerometer update. + accelerationXNumber0The acceleration value in Gs (9.8m/sec/sec) along the x-axis. + accelerationYNumber0The acceleration value in Gs (9.8m/sec/sec) along the y-axis. + accelerationZNumber0The acceleration value in Gs (9.8m/sec/sec) along the z-axis. + + Constructor for AccelerometerEvent objects. + + + Creates an AccelerometerEvent object that contains information about acceleration along three dimensional axis. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of an AccelerometerEvent object and sets the value of each property to match that of + the original.A new AccelerometerEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of an AccelerometerEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the AccelerometerEvent object.A string that contains all the properties of the AccelerometerEvent object. + + String + Returns a string that contains all the properties of the AccelerometerEvent object. The following + format is used: + +

[AccelerometerEvent type=value bubbles=value cancelable=value + timestamp=value accelerationX=value accelerationY=value accelerationZ=value ]

+ +
UPDATE + Defines the value of the type property of a AccelerometerEvent event object.updateString + Defines the value of the type property of a AccelerometerEvent event object. +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.timestampThe timestamp of the Accelerometer update.accelerationXThe acceleration value in Gs (9.8m/sec/sec) along the x-axis.accelerationYThe acceleration value in Gs (9.8m/sec/sec) along the y-axis. accelerationZThe acceleration value in Gs (9.8m/sec/sec) along the z-axis. + +
accelerationX + Acceleration along the x-axis, measured in Gs.Number + Acceleration along the x-axis, measured in Gs. (1 G is roughly 9.8 m/sec/sec.) The x-axis runs from the left to the right of the device + when it is in the upright position. The acceleration is positive if the device moves towards the right. + + accelerationY + Acceleration along the y-axis, measured in Gs.Number + Acceleration along the y-axis, measured in Gs. (1 G is roughly 9.8 m/sec/sec.). + The y-axis runs from the bottom to the top of the device when it is in the upright position. + The acceleration is positive if the device moves up relative to this axis. + + accelerationZ + Acceleration along the z-axis, measured in Gs.Number + Acceleration along the z-axis, measured in Gs. (1 G is roughly 9.8 m/sec/sec.). + The z-axis runs perpendicular to the face of the device. The acceleration is positive if you move the device + so that the face moves higher. + + timestamp + The number of milliseconds at the time of the event since the runtime was initialized.Number + The number of milliseconds at the time of the event since the runtime was initialized. + For example, if the device captures accelerometer data 4 seconds after the application initializes, + then the timestamp property of the event is set to 4000. + +
IMEEvent + An IMEEvent object is dispatched when the user enters text using an input method editor + (IME).Event objects for IMEEvent events. + flash.events:TextEvent + An IMEEvent object is dispatched when the user enters text using an input method editor + (IME). IMEs are generally used to enter text from languages that have ideographs instead of + letters, such as Japanese, Chinese, and Korean. There are two IME events: + IMEEvent.IME_COMPOSITION and IMEEvent.IME_START_COMPOSITION. + + flash.system.IMEflash.events.IMEEvent.IME_COMPOSITIONflash.events.IMEEvent.IME_START_COMPOSITIONimeCompositionflash.events:IMEEvent:IME_COMPOSITIONflash.events:IMEEventflash.system.IME.imeCompositionimeCompositionflash.events:IMEEvent:IME_START_COMPOSITIONflash.events:IMEEventflash.system.IME.imeCompositionIMEEvent + Creates an Event object with specific information relevant to IME events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one IME event: IMEEvent.IME_COMPOSITION. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringThe reading string from the IME. This is the initial string as typed by the user, before selection of any candidates. The final composition string is delivered to the object with keyboard focus in a TextEvent.TEXT_INPUT event. Event listeners can access this information through the text property. + imeClientflash.text.ime:IIMEClientnullA set of callbacks used by the text engine to communicate with the IME. Useful if your code has its own text engine and is rendering lines of text itself, rather than using TextField objects or the TextLayoutFramework. + + Constructor for IMEEvent objects. + + Creates an Event object with specific information relevant to IME events. + Event objects are passed as parameters to event listeners. + + flash.system.IMEflash.events.IMEEvent.IME_COMPOSITIONflash.events.IMEEvent.IME_START_COMPOSITIONclone + Creates a copy of the IMEEvent object and sets the value of each property to match that of the original.A new IMEEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the IMEEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the IMEEvent object.A string that contains all the properties of the IMEEvent object. + + String + Returns a string that contains all the properties of the IMEEvent object. The string is in the following format: +

[IMEEvent type=value bubbles=value cancelable=value text=value]

+ +
IME_COMPOSITION + Defines the value of the type property of an imeComposition event object.imeCompositionString + Defines the value of the type property of an imeComposition event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe IME object. + +
flash.system.IME.imeComposition
IME_START_COMPOSITION + To handle IME text input, the receiver must set the imeClient field of the event to an object + that implements the IIMEClient interface.imeStartCompositionString + To handle IME text input, the receiver must set the imeClient field of the event to an object + that implements the IIMEClient interface. If imeClient is unset, the runtime uses out-of-line + IME composition instead, and sends the final composition as a TEXT_INPUT event. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe IME object. + +
flash.system.IME.imeComposition
imeClient + Specifies an object that implements the IMEClient interface.flash.text.ime:IIMEClient + Specifies an object that implements the IMEClient interface. Components based on the flash.text.engine + package must implement this interface to support editing text inline using an IME. + +
DataEvent +An object dispatches a DataEvent object when raw data has completed loading.Event objects for DataEvent events. + +flash.events:TextEvent +An object dispatches a DataEvent object when raw data has completed loading. +There are two types of data event: +
  • DataEvent.DATA: dispatched for data sent or received.
  • DataEvent.UPLOAD_COMPLETE_DATA: dispatched when data is sent and the server has responded.
+ +
The following example creates an XMLSocket and connects it to a socket server + running on port 8080 of yourDomain. An event listener is attached to the XMLSocket + object that listens for data events, which are dispatched whenever raw data + is received. + +

Notes: +

  • To generate a securityError event in this example, you need to compile the SWF file with "Local playback security" set + to "Access network only".
  • You need a server running on [yourDomain] using port 8080.
+

+ +package { + import flash.display.Sprite; + import flash.events.DataEvent; + import flash.net.XMLSocket; + + public class DataEventExample extends Sprite { + private var hostName:String = "[yourDomain]"; + private var port:uint = 8080; + private var socket:XMLSocket; + + public function DataEventExample() { + socket = new XMLSocket(); + socket.addEventListener(DataEvent.DATA, dataHandler); + socket.connect(hostName, port); + } + + private function dataHandler(event:DataEvent):void { + trace("dataHandler: " + event.data); + } + } +} +
flash.net.FileReferenceflash.net.XMLSocketdataflash.events:DataEvent:DATAflash.events:DataEventflash.net.XMLSocket.datauploadCompleteDataflash.events:DataEvent:UPLOAD_COMPLETE_DATAflash.events:DataEventflash.net.FileReference.uploadCompleteDataDataEvent + Creates an event object that contains information about data events.typeString The type of the event. Event listeners can access this information through the + inherited type property. There is only one type of data event: + DataEvent.DATA. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + dataStringThe raw data loaded into Flash Player or Adobe AIR. Event listeners can access this information + through the data property. + + Constructor for DataEvent objects. + + Creates an event object that contains information about data events. + Event objects are passed as parameters to event listeners. + + flash.net.XMLSocketDataEvent.DATAclone + Creates a copy of the DataEvent object and sets the value of each property to match that of the + original.A new DataEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the DataEvent object and sets the value of each property to match that of the + original. + + toString + Returns a string that contains all the properties of the DataEvent object.A string that contains all the properties of the DataEvent object. + + String + Returns a string that contains all the properties of the DataEvent object. The string is in + the following format: +

[DataEvent type=value bubbles=value cancelable=value + data=value]

+ +
DATA + Defines the value of the type property of a data event object.dataString + Defines the value of the type property of a data event object. +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.dataThe raw data loaded into Flash Player or Adobe AIR.targetThe XMLSocket object receiving data. + +
flash.net.XMLSocket.data
UPLOAD_COMPLETE_DATA + Defines the value of the type property of an uploadCompleteData event object.uploadCompleteDataString + Defines the value of the type property of an uploadCompleteData event object. +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.dataThe raw data returned from the server after a successful file upload.targetThe FileReference object receiving data after a successful upload. + +
flash.net.FileReference.uploadCompleteData
data + The raw data loaded into Flash Player or Adobe AIR.String + The raw data loaded into Flash Player or Adobe AIR. + +
SecurityErrorEvent +An object dispatches a SecurityErrorEvent object to report the occurrence of a +security error.Event objects for SecurityErrorEvent events. +flash.events:ErrorEvent +An object dispatches a SecurityErrorEvent object to report the occurrence of a +security error. Security errors reported through this class are generally from asynchronous +operations, such as loading data, in which security violations may not manifest immediately. +Your event listener can access the object's text property to determine what operation was +attempted and any URLs that were involved. If there are no event listeners, the +debugger version of Flash Player or the AIR Debug Launcher (ADL) application +automatically displays an error message that contains the contents of the text +property. There is one type of security error event: SecurityErrorEvent.SECURITY_ERROR. + +

Security error events are the final events dispatched for any target object. +This means that any other events, including generic error events, are not dispatched for a target object +that experiences a security error.

+ +
The following example uses the SecurityErrorEventExample class to show how a + listener method securityErrorHandler() can be instantiated and set to listen for securityError + events to be dispatched. This event will occur when a URLRequest location is not in exactly + the same domain as the calling SWF, and the requested domain has not authorized cross-domain access by way of + a cross-domain policy file. +

To create a SecurityErrorEvent, replace http://www.[yourdomain].com with a path that has not been authorized for + cross domain access.

+ +package { + import flash.display.Sprite; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.events.SecurityErrorEvent; + + public class SecurityErrorEventExample extends Sprite { + public function SecurityErrorEventExample() { + var loader:URLLoader = new URLLoader(); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + + var request:URLRequest = new URLRequest("http://www.[yourDomain].com"); + loader.load(request); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + } +} +
Security classSECURITY_ERRORsecurityErrorflash.events:SecurityErrorEvent:SECURITY_ERRORflash.events:SecurityErrorEventflash.net.FileReference.securityErrorflash.net.LocalConnection.securityErrorflash.net.NetConnection.securityErrorflash.net.Socket.securityErrorflash.net.URLLoader.securityErrorflash.net.URLStream.securityErrorflash.net.XMLSocket.securityErrorSecurityErrorEvent + Creates an Event object that contains information about security error events.typeStringThe type of the event. Event listeners can access this information through the inherited type property. There is only one type of error event: SecurityErrorEvent.SECURITY_ERROR. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + textStringText to be displayed as an error message. Event listeners can access this information through the text property. + idint0A reference number to associate with the specific error. + + Constructor for SecurityErrorEvent objects. + + Creates an Event object that contains information about security error events. + Event objects are passed as parameters to event listeners. + + SECURITY_ERRORclone + Creates a copy of the SecurityErrorEvent object and sets the value of each property to match that of the original.A new securityErrorEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the SecurityErrorEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the SecurityErrorEvent object.A string that contains all the properties of the SecurityErrorEvent object. + + String + Returns a string that contains all the properties of the SecurityErrorEvent object. The string is in the following format: +

[securityErrorEvent type=value bubbles=value cancelable=value text=value errorID=value] + The errorId is only available in Adobe AIR

+ +
SECURITY_ERROR + The SecurityErrorEvent.SECURITY_ERROR constant defines the value of the type property of a securityError event object.securityErrorString + The SecurityErrorEvent.SECURITY_ERROR constant defines the value of the type property of a securityError event object. + +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe network object reporting the security error.textText to be displayed as an error message. + +
flash.net.FileReference.securityErrorflash.net.LocalConnection.securityErrorflash.net.NetConnection.securityErrorflash.net.Socket.securityErrorflash.net.URLLoader.securityErrorflash.net.URLStream.securityErrorflash.net.XMLSocket.securityError
UncaughtErrorEvent + An UncaughtErrorEvent object is dispatched by an instance of the UncaughtErrorEvents + class when an uncaught error occurs.flash.events:ErrorEvent + An UncaughtErrorEvent object is dispatched by an instance of the UncaughtErrorEvents + class when an uncaught error occurs. An uncaught error happens when an error is + thrown outside of any try..catch blocks or when an ErrorEvent + object is dispatched with no registered listeners. The uncaught error event + functionality is often described as a "global error handler." + +

The UncaughtErrorEvents object that dispatches the event is associated with + either a LoaderInfo object or a Loader object. Use the following properties to + access an UncaughtErrorEvents instance:

+ +
  • LoaderInfo.uncaughtErrorEvents: to + detect uncaught errors in code defined in the same SWF.
  • Loader.uncaughtErrorEvents: to detect uncaught + errors in code defined in the SWF loaded by a Loader object.
+ +

When an uncaughtError event happens, even if the event is handled, + execution does not continue in the call stack that caused the error. If the error is + a synchronous error, any code remaining in the function where the error happened is + not executed. Consequently, it is likely that when an uncaught error event happens, + your application is in an unstable state. Since there can be many causes for an + uncaught error, it is impossible to predict what functionality is available. For + example, your application may be able to execute network operations or file + operations. However, those operations aren't necessarily available.

+ +

When one SWF loads another, uncaughtError events bubble down and up + again through the LoaderInfo heirarchy. For example, suppose A.swf loads B.swf using a + Loader instance. If an uncaught error occurs in B.swf, an uncaughtError + event is dispatched to LoaderInfo and Loader objects in the following + sequence:

+ +
  1. (Capture phase) A.swf's LoaderInfo
  2. (Capture phase) Loader in A.swf
  3. (Target phase) B.swf's LoaderInfo
  4. (Bubble phase) Loader in A.swf
  5. (Bubble phase) A.swf's LoaderInfo
+ +

A Loader object's uncaughtErrorEvents property + never dispatches an uncaughtErrorEvent in the target phase. It only + dispatches the event in the capture and bubbling phases.

+ +

As with other event bubbling, calling stopPropagation() or + stopImmediatePropagation() stops the event from being dispatched + to any other listeners, with one important difference. A Loader object's + UncaughtErrorEvents object is treated as a pair with the loaded SWF's + LoaderInfo.uncaughtErrorEvents object for event propagation purposes. + If a listener registered with one of those objects calls the stopPropagation() + method, events are still dispatched to other listeners registered with that + UncaughtErrorEvents object and to listeners registered with its partner + UncaughtErrorEvents object before event propagation ends. The + stopImmediatePropagation() method still prevents events from being + dispatched to all additional listeners.

+ +

When content is running in a debugger version of the runtime, such as the + debugger version of Flash Player or the AIR Debug Launcher (ADL), an uncaught + error dialog appears when an uncaught error happens. + For those runtime versions, the error dialog appears even when a listener is registered + for the uncaughtError event. To prevent the dialog from appearing + in that situation, call the UncaughtErrorEvent object's + preventDefault() method.

+ +

If the content loaded by a Loader object is an AVM1 (ActionScript 2) SWF file, + uncaught errors in the AVM1 SWF file do not result in an uncaughtError + event. In addition, JavaScript errors in HTML content loaded in an HTMLLoader object + (including a Flex HTML control) do not result in an uncaughtError event.

+ +
The following example demonstrates the use of an uncaught error event + handler to detect uncaught errors in an ActionScript project. The example defines + an uncaughtError event handler to detect uncaught errors. It also + provides a button that, when clicked, throws an error that is caught by the + uncaught error handler. + +

In the constructor, the code registers a listener for the uncaughtError + event dispatched by the LoaderInfo object's uncaughtErrorEvents property.

+ +

In the uncaughtErrorHandler() method, the code checks the data type of + the error property and responds accordingly.

+ +package +{ + import flash.display.Sprite; + import flash.events.ErrorEvent; + import flash.events.MouseEvent; + import flash.events.UncaughtErrorEvent; + + public class UncaughtErrorEventExample extends Sprite + { + public function UncaughtErrorEventExample() + { + loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + + drawUI(); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + + private function drawUI():void + { + var btn:Sprite = new Sprite(); + btn.graphics.clear(); + btn.graphics.beginFill(0xFFCC00); + btn.graphics.drawRect(0, 0, 100, 50); + btn.graphics.endFill(); + addChild(btn); + btn.addEventListener(MouseEvent.CLICK, clickHandler); + } + + private function clickHandler(event:MouseEvent):void + { + throw new Error("Gak!"); + } + } +} +
The following example is the Flex equivalent of the previous example, + using an MXML document instead of an ActionScript class as the root content. + +<?xml version="1.0" encoding="utf-8"?> +<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" + xmlns:s="library://ns.adobe.com/flex/spark" + xmlns:mx="library://ns.adobe.com/flex/halo" + applicationComplete="applicationCompleteHandler();"> + + <fx:Script> + <![CDATA[ + import flash.events.ErrorEvent; + import flash.events.MouseEvent; + import flash.events.UncaughtErrorEvent; + + private function applicationCompleteHandler():void + { + loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + + private function clickHandler(event:MouseEvent):void + { + throw new Error("Gak!"); + } + ]]> + </fx:Script> + + <s:Button label="Cause Error" click="clickHandler(event);"/> +</s:WindowedApplication> + The following example demonstrates the use of an uncaught error event + handler to detect uncaught errors in a loaded SWF. The example defines + an uncaughtError event handler to detect uncaught errors. + +

In the constructor, the code creates a Loader object and registers a listener for + the uncaughtError event dispatched by the Loader object's + uncaughtErrorEvents property.

+ +

In the uncaughtErrorHandler() method, the code checks the data type of + the error property and responds accordingly.

+ +package +{ + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.ErrorEvent; + import flash.events.UncaughtErrorEvent; + import flash.net.URLRequest; + + public class LoaderUncaughtErrorEventExample extends Sprite + { + private var ldr:Loader; + + public function LoaderUncaughtErrorEventExample() + { + ldr = new Loader(); + ldr.load(new URLRequest("child.swf")); + ldr.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler); + } + + private function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + if (event.error is Error) + { + var error:Error = event.error as Error; + // do something with the error + } + else if (event.error is ErrorEvent) + { + var errorEvent:ErrorEvent = event.error as ErrorEvent; + // do something with the error + } + else + { + // a non-Error, non-ErrorEvent type was thrown and uncaught + } + } + } +} +
LoaderInfo.uncaughtErrorEventsLoader.uncaughtErrorEventsUncaughtErrorEventsuncaughtErrorflash.events:UncaughtErrorEvent:UNCAUGHT_ERRORflash.events:UncaughtErrorEventUncaughtErrorEvent + Creates an UncaughtErrorEvent object that contains information about an + uncaughtError event.typeStringunknownThe type of the event. + bubblesBooleantrueDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleantrueDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + error_innullThe object associated with the error that was not caught or handled (an Error or ErrorEvent object under normal circumstances). + + Constructor for UncaughtErrorEvent objects. + + + Creates an UncaughtErrorEvent object that contains information about an + uncaughtError event. + + clone + Creates a copy of the UncaughtErrorEvent object and sets the value of + each property to match that of the original.A new UncaughtErrorEvent object with property values that match those + of the original. + + flash.events:Event + Creates a copy of the UncaughtErrorEvent object and sets the value of + each property to match that of the original. + + toString + Returns a string that contains all the properties of the UncaughtErrorEvent object.A string that contains all the properties of the UncaughtErrorEvent object. + + String + Returns a string that contains all the properties of the UncaughtErrorEvent object. + + UNCAUGHT_ERROR + Defines the value of the type property of an uncaughtError event object.uncaughtErrorString + Defines the value of the type property of an uncaughtError event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelabletrue; cancelling the event prevents the uncaught error dialog from appearing in debugger runtime versionscurrentTargetThe object that is actively processing the Event object with an event listener.errorThe uncaught error.targetThe LoaderInfo object associated with the SWF where the error happened.textText error message. + +
error + The error object associated with the uncaught error. + The error object associated with the uncaught error. Typically, this + object's data type is one of the following: + +
  • An Error instance (or one of its subclasses), if the uncaught error is + a synchronous error created by a throw statement, such as an + error that could have been caught using a try..catch block
  • An ErrorEvent instance (or one of its subclasses), if the uncaught error + is an asynchronous error that dispatches an error event when the error happens
+ +

However, the error property can potentially be an object of any + data type. ActionScript does not require a throw + statement to be used only with Error objects. For example, the following + code is legal both at compile time and run time:

+ + throw new Sprite() + +

If that throw statement is not caught by a + try..catch block, the throw statement + triggers an uncaughtError event. In that case, the + error property of the UncaughtErrorEvent object that's dispatched + is the Sprite object that's constructed in the throw statement.

+ +

Consequently, in your uncaughtError listener, you should check + the data type of the error property. The following example + demonstrates this check:

+ + + function uncaughtErrorHandler(event:UncaughtErrorEvent):void + { + var message:String; + + if (event.error is Error) + { + message = Error(event.error).message; + } + else if (event.error is ErrorEvent) + { + message = ErrorEvent(event.error).text; + } + else + { + message = event.error.toString(); + } + } + + + +

If the error property contains an Error instance (or Error subclass), + the available error information varies depending on the version of the runtime + in which the content is running. The following functionality is only available + when content is running in a debugger version of the runtime, such as the + debugger version of Flash Player or the AIR Debug Launcher (ADL):

+ +
  • Error.getStackTrace() to get the call stack that led to + the error. In non-debugger runtime versions, this method returns + null. Note that call stack information is never available + when the error property is an ErrorEvent instance.
  • Complete Error.message text. In non-debugger runtime versions, + this property contains a short version of the error message, which is often a + combination of the Error.errorID and Error.name properties.
+ +

All other properties and methods of the Error class are available in all + runtime versions.

+ +
InvokeEvent + The NativeApplication object of an AIR application dispatches an invoke event when the + application is invoked.Dispatched by the NativeApplication object when an AIR application is invoked via the + operating system. + + flash.events:Event + The NativeApplication object of an AIR application dispatches an invoke event when the + application is invoked. + +

The NativeApplication object always dispatches an invoke event + when an application is launched, but the event may be dispatched + at other times as well. For example, a running application dispatches an + additional InvokeEvent when a user activates a file associated with the + application.

+ +

Only a single instance of a particular application can be launched. Subsequent attempts to + launch the application will result in a new invoke event dispatched by + the NativeApplication object of the running instance. + It is an application's responsibility to handle this event and take the appropriate + action, such as opening a new application window to display the data in a file.

+ +

InvokeEvent objects are dispatched by the NativeApplication object + (NativeApplication.nativeApplication). To receive invoke events, + call the addEventListener() method of the NativeApplication object. + When an event listener registers for an invoke event, it will also receive all + invoke events that occurred before the registration. These earlier events are dispatched + after the call to addEventListener() returns, but not necessarily before + a new invoke event that might be might be dispatched after registration. Thus, + you should not rely on dispatch order.

+ +
flash.events.BrowserInvokeEventflash.desktop.NativeApplicationinvokeflash.events:InvokeEvent:INVOKEflash.events:InvokeEventThe type constant for flash.events.InvokeEvent events. + flash.desktop.NativeApplicationflash.desktop.InvokeEventReasonInvokeEvent + The constructor function for the InvokeEvent class.typeStringThe type of the event, accessible as Event.type. + bubblesBooleanfalseSet to false for an InvokeEvent object. + cancelableBooleanfalseSet to false for an InvokeEvent object. + dirflash.filesystem:FilenullThe directory that should be used to resolve any relative paths in + the arguments array. + argvArraynullAn array of arguments (strings) to pass to the application. + reasonStringstandardthe cause of the event, either InvokeEventReason.LOGIN or InvokeEventReason.STANDARD. + (This parameter is available as of AIR version 1.5.1.) + + + The constructor function for the InvokeEvent class. + + flash.desktop.InvokeEventReasonclone + Creates a new copy of this event.The copy of the event. + + flash.events:Event + Creates a new copy of this event. + + INVOKE + The InvokeEvent.INVOKE constant defines the value of the type + property of an InvokeEvent object.invokeStringThe type constant for flash.events.InvokeEvent events. + + The InvokeEvent.INVOKE constant defines the value of the type + property of an InvokeEvent object. + +

The InvokeEvent object has the following properties:

+ PropertiesValuesargumentsThe array of string arguments passed + during this invocation.currentDirectorya File object representing the + directory that should be used to resolve any relative paths in the arguments array.reasona code indicating whether the invoke event was dispatched + because the application started automatically at login (InvokeEventReason.LOGIN), or + for another reason (InvokeEventReason.STANDARD). Available as of AIR version 1.5.1.bubblesfalse.cancelablefalse; + there is no default behavior to cancel.currentTargetIndicates the object that is + actively processing this InvokeEvent object with an event listener.targetAlways the NativeApplication object. + + +
flash.desktop.NativeApplicationflash.desktop.InvokeEventReason
arguments + The array of string arguments passed during this invocation.Array + The array of string arguments passed during this invocation. If this is a + command line invocation, the array contains the command line arguments + (excluding the process name). + +

Note: When multiple files are selected and opened on Mac® OS X, AIR + dispatches a single invoke event containing the names of all the + selected files in the arguments array. On Windows® and Linux, however, AIR + dispatches a separate invoke event for each selected file containing only that + filename in the arguments array. +

+ +
currentDirectory + The directory that should be used to resolve any relative paths in the arguments + array.flash.filesystem:File + The directory that should be used to resolve any relative paths in the arguments + array. + +

If an application is started from the command line, this property is + typically set to the current working directory of the command line shell from which + the application was started. If an application is launched from the GUI shell, + this is typically the file system root.

+ +
reason + The reason for this InvokeEvent.String + The reason for this InvokeEvent. This property indicates whether the application was launched manually + by the user or automatically at login. Possible values are enumerated as constants in + the InvokeEventReason class: + + InvokeEventReason constantMeaningLOGINLaunched automatically at at login.STANDARDLaunched for any other reason. + + flash.desktop.InvokeEventReason
ScreenMouseEvent +The SystemTrayIcon object dispatches events of type ScreenMouseEvent in response to mouse interaction.Event object for ScreenMouseEvent events. +flash.events:MouseEvent +The SystemTrayIcon object dispatches events of type ScreenMouseEvent in response to mouse interaction. + +

The ScreenMouseEvent object extends the MouseEvent class to provide two additional properties, +screenX and screenY, that report the mouse coordinates +in relation to the primary desktop screen rather than an application window or +stage.

+ +
flash.desktop.SystemTrayIconflash.display.Screenclickflash.events:ScreenMouseEvent:CLICKflash.events:ScreenMouseEventDispatched by a SystemTrayIcon object when the icon is clicked. + + mouseDownflash.events:ScreenMouseEvent:MOUSE_DOWNflash.events:ScreenMouseEventmouseUpflash.events:ScreenMouseEvent:MOUSE_UPflash.events:ScreenMouseEventrightClickflash.events:ScreenMouseEvent:RIGHT_CLICKflash.events:ScreenMouseEventrightMouseDownflash.events:ScreenMouseEvent:RIGHT_MOUSE_DOWNflash.events:ScreenMouseEventrightMouseUpflash.events:ScreenMouseEvent:RIGHT_MOUSE_UPflash.events:ScreenMouseEventScreenMouseEvent + Creates a ScreenMouseEvent object that contains the mouse location in + screen coordinates.typeString The type of the event. Event listeners can access this information + through the inherited type property. + bubblesBooleanfalseThe X position of the click in screen coordinates. + cancelableBooleanfalseThe Y position of the click in screen coordinates. + screenXNumberunknownSet to false since screen mouse events never bubble. + screenYNumberunknownSet to false since there is no default behavior to cancel. + ctrlKeyBooleanfalseOn Windows or Linux, indicates whether the Ctrl key was down when this event occurred. + On Mac, indicates whether the Ctrl key or the Command key was down. + altKeyBooleanfalseSet to true to indicate that the alt key was down when this event occured. + shiftKeyBooleanfalseSet to true to indicate that the shift key was down when this event occured. + buttonDownBooleanfalseSet to true to indicate that a mouse button was down when this event occured. + commandKeyBooleanfalseIndicates whether the Command key was down (Mac only). + controlKeyBooleanfalseIndicates whether the Ctrl or Control key was down. + + Constructor for ScreenMouseEvent objects. + + + Creates a ScreenMouseEvent object that contains the mouse location in + screen coordinates. + + flash.events.MouseEventflash.display.Screenclone + Creates a copy of the ScreenMouseEvent object and sets the value of each property to match that of the original.A new ScreenMouseEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the ScreenMouseEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the ScreenMouseEvent object.A string that contains all the properties of the ScreenMouseEvent object. + String + Returns a string that contains all the properties of the ScreenMouseEvent object. + The string is in the following format: +

[ScreenMouseEvent type=value bubbles=value cancelable=value status=value]

+ +
CLICK + The ScreenMouseEvent.CLICK constant defines the value of the type + property of a click event object.clickStringDispatched by a SystemTrayIcon object when the icon is clicked. + + + The ScreenMouseEvent.CLICK constant defines the value of the type + property of a click event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
MOUSE_DOWN + The ScreenMouseEvent.MOUSE_DOWN constant defines the value of the type + property of a mouseDown event object.mouseDownString + The ScreenMouseEvent.MOUSE_DOWN constant defines the value of the type + property of a mouseDown event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
MOUSE_UP + The ScreenMouseEvent.MOUSE_UP constant defines the value of the type + property of a mouseUp event object.mouseUpString + The ScreenMouseEvent.MOUSE_UP constant defines the value of the type + property of a mouseUp event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
RIGHT_CLICK + The ScreenMouseEvent.RIGHT_CLICK constant defines the value of the type + property of a rightClick event object.rightClickString + The ScreenMouseEvent.RIGHT_CLICK constant defines the value of the type + property of a rightClick event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
RIGHT_MOUSE_DOWN + The ScreenMouseEvent.RIGHT_MOUSE_DOWN constant defines the value of the type + property of a rightMouseDown event object.rightMouseDownString + The ScreenMouseEvent.RIGHT_MOUSE_DOWN constant defines the value of the type + property of a rightMouseDown event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
RIGHT_MOUSE_UP + The ScreenMouseEvent.RIGHT_MOUSE_UP constant defines the value of the type + property of a rightMouseUp event object.rightMouseUpString + The ScreenMouseEvent.RIGHT_MOUSE_UP constant defines the value of the type + property of a rightMouseUp event object. + +

This event has the following relevant properties:

+ + PropertyValuebuttonDowntrue if the primary mouse button is pressed; false otherwise.ctrlKeytrue on Windows or Linux if the Ctrl key is active. true on Mac if either the Ctrl key or the Command key is active. Otherwise, false.currentTargetThe object that is actively processing the Event + object with an event listener.shiftKeytrue if the Shift key is active; false if it is inactive.commandKeytrue on the Mac if the Command key is active; false if it is inactive. Always false on Windows.controlKeytrue if the Ctrl or Control key is active; false if it is inactive.screenXThe horizontal coordinate at which the event occurred in screen coordinates.screenYThe vertical coordinate at which the event occurred in screen coordinates.targetThe SystemTrayIcon object under the pointing device. + +
screenX + The X position of the click in screen coordinates.Number + The X position of the click in screen coordinates. + + screenY + The Y position of the click in screen coordinates.Number + The Y position of the click in screen coordinates. + +
ContextMenuEvent + An InteractiveObject dispatches a ContextMenuEvent object when the user opens or interacts with + the context menu.Event objects for ContextMenuEvent events. + flash.events:Event + An InteractiveObject dispatches a ContextMenuEvent object when the user opens or interacts with + the context menu. There are two types of + ContextMenuEvent objects: +
  • ContextMenuEvent.MENU_ITEM_SELECT
  • ContextMenuEvent.MENU_SELECT
+ +
The following example uses the ContextMenuEventExample class + to remove the default context menu items from the Stage and add a new menu item that changes + the color of a square on the Stage. The example carries out the following + tasks: + +
  1. The myContextMenu property is declared and then assigned to a new ContextMenu + object and the redRectangle property (of type Sprite) is declared.
  2. The removeDefaultItems() method is called. This method removes all built-in context + menu items except Print.
  3. The addCustomMenuItems() method is called. This method places a + Reverse Colors menu item in the defaultItems array by using the + push() method of Array. A menuItemSelect event listener is added to the + ContextMenuItem object and the associated method is called menuItemSelectHandler(). + This method prints some trace() statements whenever the user + selects Reverse Colors from the context menu. In addition the red square + becomes black and the black text becomes red.
  4. Back in the constructor, a menuSelect event listener is added, along with + the associated method menuSelectHandler(), which simply prints out three trace() statements + every time an item in the context menu is selected.
  5. The constructor calls addChildren(), which draws a red square and adds it + to the display list, which immediately displays the square.
  6. Finally, myContextMenu is assigned to the context menu of the redRectangle property, + so that the custom context menu is displayed only when the mouse pointer is over the square.
+ +package { + import flash.ui.ContextMenu; + import flash.ui.ContextMenuItem; + import flash.ui.ContextMenuBuiltInItems; + import flash.events.ContextMenuEvent; + import flash.display.Sprite; + import flash.display.Shape; + import flash.text.TextField; + + public class ContextMenuEventExample extends Sprite { + private var myContextMenu:ContextMenu; + private var menuLabel:String = "Reverse Colors"; + private var textLabel:String = "Right Click"; + private var redRectangle:Sprite; + private var label:TextField; + private var size:uint = 100; + private var black:uint = 0x000000; + private var red:uint = 0xFF0000; + + public function ContextMenuEventExample() { + myContextMenu = new ContextMenu(); + removeDefaultItems(); + addCustomMenuItems(); + myContextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, menuSelectHandler); + + addChildren(); + redRectangle.contextMenu = myContextMenu; + } + + private function addChildren():void { + redRectangle = new Sprite(); + redRectangle.graphics.beginFill(red); + redRectangle.graphics.drawRect(0, 0, size, size); + addChild(redRectangle); + redRectangle.x = size; + redRectangle.y = size; + label = createLabel(); + redRectangle.addChild(label); + } + + private function removeDefaultItems():void { + myContextMenu.hideBuiltInItems(); + var defaultItems:ContextMenuBuiltInItems = myContextMenu.builtInItems; + defaultItems.print = true; + } + + private function addCustomMenuItems():void { + var item:ContextMenuItem = new ContextMenuItem(menuLabel); + myContextMenu.customItems.push(item); + item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelectHandler); + } + + private function menuSelectHandler(event:ContextMenuEvent):void { + trace("menuSelectHandler: " + event); + } + + private function menuItemSelectHandler(event:ContextMenuEvent):void { + trace("menuItemSelectHandler: " + event); + var textColor:uint = (label.textColor == black) ? red : black; + var bgColor:uint = (label.textColor == black) ? black : red; + redRectangle.graphics.clear(); + redRectangle.graphics.beginFill(bgColor); + redRectangle.graphics.drawRect(0, 0, size, size); + label.textColor = textColor; + } + + private function createLabel():TextField { + var txtField:TextField = new TextField(); + txtField.text = textLabel; + return txtField; + } + } +} +
ContextMenu classContextMenuItem classmenuItemSelectflash.events:ContextMenuEvent:MENU_ITEM_SELECTflash.events:ContextMenuEventflash.ui.ContextMenuItem.menuItemSelectmenuSelectflash.events:ContextMenuEvent:MENU_SELECTflash.events:ContextMenuEventflash.ui.ContextMenu.menuSelectContextMenuEvent + Creates an Event object that contains specific information about menu events.typeString The type of the event. Possible values are: +
  • ContextMenuEvent.MENU_ITEM_SELECT
  • ContextMenuEvent.MENU_SELECT
+
bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + mouseTargetflash.display:InteractiveObjectnullThe display list object on which the user right-clicked to display the context menu. This could be the contextMenuOwner or one of its display list descendants. + contextMenuOwnerflash.display:InteractiveObjectnullThe display list object to which the menu is attached. This could be the mouseTarget or one of its ancestors in the display list. + + Constructor for ContextMenuEvent objects. +
+ Creates an Event object that contains specific information about menu events. + Event objects are passed as parameters to event listeners. + +
ContextMenuEvent.MENU_ITEM_SELECTContextMenuEvent.MENU_SELECT
clone + Creates a copy of the ContextMenuEvent object and sets the value of each property to match that of the original.A new ContextMenuEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the ContextMenuEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the ContextMenuEvent object.A string that contains all the properties of the ContextMenuEvent object. + String + Returns a string that contains all the properties of the ContextMenuEvent object. The string is in the following format: +

[ContextMenuEvent type=value bubbles=value cancelable=value ... contextMenuOwner=value]

+ +
MENU_ITEM_SELECT + Defines the value of the type property of a menuItemSelect event object.menuItemSelectString + Defines the value of the type property of a menuItemSelect event object. +

This event has the following properties:

+ PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.contextMenuOwnerThe display list object to which the menu is attached.currentTargetThe object that is actively processing the Event + object with an event listener.mouseTargetThe display list object on which the user right-clicked to display the context menu.targetThe ContextMenuItem object that has been selected. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.ui.ContextMenuItem.menuItemSelect
MENU_SELECT + Defines the value of the type property of a menuSelect event object.menuSelectString + Defines the value of the type property of a menuSelect event object. +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.contextMenuOwnerThe display list object to which the menu is attached.currentTargetThe object that is actively processing the Event + object with an event listener.mouseTargetThe display list object on which the user right-clicked to display the context menu.targetThe ContextMenu object that is about to be displayed. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + +
flash.ui.ContextMenu.menuSelect
contextMenuOwner + The display list object to which the menu is attached.flash.display:InteractiveObject + The display list object to which the menu is attached. This could be the mouse target (mouseTarget) or one of its ancestors in the display list. + + isMouseTargetInaccessible + Indicates whether the mouseTarget property was set to null for security + reasons.Boolean + Indicates whether the mouseTarget property was set to null for security + reasons. If the nominal value of menuTarget would be a reference to a + DisplayObject in another security sandbox, then menuTarget is set to + null unless there is permission in both directions across this sandbox boundary. Permission is + established by calling Security.allowDomain() from a SWF file, or providing + a policy file from the server of an image file, and setting the LoaderContext.checkPolicyFile + flag when loading the image. + + ContextMenuEvent.mouseTargetSecurity.allowDomain()LoaderContext.checkPolicyFilemouseTarget + The display list object on which the user right-clicked to display the context menu.flash.display:InteractiveObject + The display list object on which the user right-clicked to display the context menu. This could be the display list object to which the + menu is attached (contextMenuOwner) or one of its display list descendants. +

The value of this property can be null in two circumstances: if there no mouse target, + for example when you mouse over something from + the background; or there is a mouse target, but it is in a security sandbox to which you don't have access. + Use the isMouseTargetInaccessible() property to determine which of these reasons applies.

+ +
ContextMenuEvent.isMouseTargetInaccessible
DRMAuthenticateEvent + A NetStream object dispatchs a DRMAuthenticateEvent object when attempting to play digital rights management (DRM) encrypted + content that requires a user credential for authentication.Event objects for DRM-enabled objects. + flash.events:Event + A NetStream object dispatchs a DRMAuthenticateEvent object when attempting to play digital rights management (DRM) encrypted + content that requires a user credential for authentication. +

+ The DRMAuthenticateEvent handler is responsible for gathering the required credentials + (such as the user name, password, and type) and passing the values to the + NetStream.setDRMAuthenticationCredentials() method for authentication. Each + AIR application must provide some mechanism for obtaining user credentials. + For example, the application could provide a user with a simple user interface to enter the + username and password values, and optionally the type value as well. +

+

+ If user authentication failed, the application will retry + authentication and dispatch a new DRMAuthenticateEvent event for the NetStream object. +

+ +
package +{ + import flash.display.Sprite; + import flash.events.AsyncErrorEvent; + import flash.events.NetStatusEvent; + import flash.events.DRMAuthenticateEvent; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + + public class DRMAuthenticateEventExample extends Sprite + { + var videoURL:String = "Video.flv"; + var videoConnection:NetConnection; + var videoStream:NetStream; + var video:Video = new Video(); + + public function DRMAuthenticateEventExample() + { + videoConnection = new NetConnection(); + videoConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + videoConnection.connect(null); + } + + private function connectStream():void { + videoStream = new NetStream(videoConnection); + videoStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + videoStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + videoStream.addEventListener(DRMAuthenticateEvent.DRM_AUTHENTICATE, drmAuthenticateEventHandler); + video.attachNetStream(videoStream); + videoStream.play(videoURL); + addChild(video); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Unable to locate video: " + videoURL); + break; + } + } + + private function asyncErrorHandler(event:AsyncErrorEvent):void { + // ignore AsyncErrorEvent events. + } + + private function drmAuthenticateEventHandler(event:DRMAuthenticateEvent):void { + videoStream.setDRMAuthenticationCredentials("User", "password", "drm"); + } + } +} +
DRMAuthenticateEvent.DRM_AUTHENTICATEflash.net.drm.DRMManagerdrmAuthenticateflash.events:DRMAuthenticateEvent:AUTHENTICATION_TYPE_DRMflash.events:DRMAuthenticateEventflash.net.NetStream.drmAuthenticateDRMAuthenticateEvent.authenticationTypedrmAuthenticateflash.events:DRMAuthenticateEvent:AUTHENTICATION_TYPE_PROXYflash.events:DRMAuthenticateEventflash.net.NetStream.drmAuthenticateDRMAuthenticateEvent.authenticationTypedrmAuthenticateflash.events:DRMAuthenticateEvent:DRM_AUTHENTICATEflash.events:DRMAuthenticateEventflash.net.NetStream.drmAuthenticateDRMAuthenticateEvent + Creates an Event object that contains specific information about DRM authentication events.typeString The type of the event. Event listeners can access this information through the inherited type property. There is only one type of DRMAuthenticate event: DRMAuthenticateEvent.DRM_AUTHENTICATE. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + headerStringThe encrypted content file header provided by the server. + userPromptString A prompt for a user name credential, provided by the server. + passPromptStringA prompt for a password credential, provided by the server. + urlPromptStringA prompt for a URL to display, provided by the server. + authenticationTypeStringIndicates whether the supplied credentials are for authenticating against the Flash Media Rights Management Server (FMRMS) or a proxy server. + netstreamflash.net:NetStreamnullThe NetStream object that initiated this event. + + + Creates an Event object that contains specific information about DRM authentication events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the DRMAuthenticateEvent object and sets the value of each property to match + that of the original.A new DRMAuthenticateEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the DRMAuthenticateEvent object and sets the value of each property to match + that of the original. + + toString + Returns a string that contains all the properties of the DRMAuthenticateEvent object.A string that contains all the properties of the DRMAuthenticateEvent object. + + String + Returns a string that contains all the properties of the DRMAuthenticateEvent object. + The string is in the following format: +

[DRMAuthenticateEvent type=value bubbles=value cancelable=value + eventPhase=value header=value usernamePrompt=value passwordPrompt=value + urlPrompt=value] authenticationType=value

+ +
AUTHENTICATION_TYPE_DRM + The DRMAuthenticateEvent.AUTHENTICATION_TYPE_DRM constant defines the value of the + authenticationType property of a DRMAuthenticateEvent object.drmString + The DRMAuthenticateEvent.AUTHENTICATION_TYPE_DRM constant defines the value of the + authenticationType property of a DRMAuthenticateEvent object. + +

This event has the following properties:

+ + PropertyValueauthenticationTypeIndicates whether the supplied credentials are for + authenticating against the Flash Media Rights Management Server (FMRMS) or a proxy server.bubblesfalsecancelablefalse; there is no default behavior to cancel.headerThe encrypted content file header provided by the server.netstreamThe NetStream object that initiated this event.passwordPromptA prompt for a password credential, provided by the server.targetThe NetStream object.urlPromptA prompt for a URL to display, provided by the server.usernamePromptA prompt for a user name credential, provided by the server. + +
flash.net.NetStream.drmAuthenticateDRMAuthenticateEvent.authenticationType
AUTHENTICATION_TYPE_PROXY + The DRMAuthenticateEvent.AUTHENTICATION_TYPE_PROXY constant defines the value of the + authenticationType property of a DRMAuthenticateEvent object.proxyString + The DRMAuthenticateEvent.AUTHENTICATION_TYPE_PROXY constant defines the value of the + authenticationType property of a DRMAuthenticateEvent object. + +

This event has the following properties:

+ + PropertyValueauthenticationTypeIndicates whether the supplied credentials are for + authenticating against the Flash Media Rights Management Server (FMRMS) or a proxy server.bubblesfalsecancelablefalse; there is no default behavior to cancel.headerThe encrypted content file header provided by the server.netstreamThe NetStream object that initiated this event.passwordPromptA prompt for a password credential, provided by the server.targetThe NetStream object.urlPromptA prompt for a URL to display, provided by the server.usernamePromptA prompt for a user name credential, provided by the server. + +
flash.net.NetStream.drmAuthenticateDRMAuthenticateEvent.authenticationType
DRM_AUTHENTICATE + The DRMAuthenticateEvent.DRM_AUTHENTICATE constant defines the value of the + type property of a DRMAuthenticateEvent object.drmAuthenticateString + The DRMAuthenticateEvent.DRM_AUTHENTICATE constant defines the value of the + type property of a DRMAuthenticateEvent object. + +

This event has the following properties:

+ + PropertyValueauthenticationTypeIndicates whether the supplied credentials are for + authenticating against the Flash Media Rights Management Server (FMRMS) or a proxy server.bubblesfalsecancelablefalse there is no default behavior to cancel.headerThe encrypted content file header provided by the server.netstreamThe NetStream object that initiated this event.passwordPromptA prompt for a password credential, provided by the server.targetThe NetStream object.urlPromptA prompt for a URL to display, provided by the server.usernamePromptA prompt for a user name credential, provided by the server. + +
flash.net.NetStream.drmAuthenticate
authenticationType + Indicates whether the supplied credentials are for authenticating against Flash Media Rights Management Server (FMRMS) + or a proxy server.String + Indicates whether the supplied credentials are for authenticating against Flash Media Rights Management Server (FMRMS) + or a proxy server. For example, the "proxy" option allows the application to authenticate against a proxy server + if an enterprise requires such a step before the user can access the Internet. Unless anonymous authentication is used, + after the proxy authentication, the user still needs to authenticate against FMRMS in order to obtain the voucher + and play the content. You can use setDRMAuthenticationcredentials() a second time, with "drm" + option, to authenticate against FMRMS. + + header + The encrypted content file header provided by the server.String + The encrypted content file header provided by the server. + It contains information about the context of the encrypted content. + + netstream + The NetStream object that initiated this event.flash.net:NetStream + The NetStream object that initiated this event. + + passwordPrompt + A prompt for a password credential, provided by the server.String + A prompt for a password credential, provided by the server. + The string can include instruction for the type of password required. + + urlPrompt + A prompt for a URL string, provided by the server.String + A prompt for a URL string, provided by the server. + The string can provide the location where the username and password will be sent. + + usernamePrompt + A prompt for a user name credential, provided by the server.String + A prompt for a user name credential, provided by the server. + The string can include instruction for the type of user name required. + For example, a content provider may require an e-mail address as the user name. + +
StorageVolumeChangeEvent + The StorageVolumeInfo.storageVolumeInfo object dispatches a StorageVolumeChangeEvent event + object when a storage volume is mounted or unmounted.flash.events:Event + The StorageVolumeInfo.storageVolumeInfo object dispatches a StorageVolumeChangeEvent event + object when a storage volume is mounted or unmounted. There are two types of StorageVolumeChangeEvent: + storageVolumeMount and storageVolumeUnmount. + +

On Linux, the StorageVolumeInfo object only dispatches storageVolumeMount and + storageVolumeUnmount events for physical devices. It does not dispatch events when + the user mounts or unmounts volumes over a network.

+ +

Some devices, such as some digital cameras and phones, appear in the + StorageVolumeInfo.getStorageVolumes() array, but they do not dispatch StorageVolumeChangeEvent + objects when mounted or unmounted.

+ + + + +
flash.filesystem.StorageVolumeInfostorageVolumeMountflash.events:StorageVolumeChangeEvent:STORAGE_VOLUME_MOUNTflash.events:StorageVolumeChangeEventflash.filesystem.StorageVolumeInfostorageVolumeUnountflash.events:StorageVolumeChangeEvent:STORAGE_VOLUME_UNMOUNTflash.events:StorageVolumeChangeEventflash.filesystem.StorageVolumeInfoStorageVolumeChangeEvent + Creates a StorageVolumeChangeEvent object to pass as an argument to event listeners.typeString The type of the event, accessible in the type property. + The StorageVolumeChangeEvent class defines two event types, the storageVolumeMount event, + represented by the StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT constant, and the + storageVolumeUnmount event, represented by the StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT + constant, + + bubblesBooleanfalse Determines whether the event object participates in the bubbling + stage of the event flow. The default value is false. + + cancelableBooleanfalseDetermines whether the Event object can be cancelled. + The default value is false. + + pathflash.filesystem:FilenullThe name of the storage volume. + + volumeflash.filesystem:StorageVolumenullThe File object representing the storage volume. + + Used to create new StorageVolumeChangeEvent object. + + + Creates a StorageVolumeChangeEvent object to pass as an argument to event listeners. + + flash.errors.SQLErrorflash.events.ErrorEvent.ERRORclone + + Duplicates an instance of an Event subclass.A new Event object that is identical to the original. + flash.events:Event + + Duplicates an instance of an Event subclass. + +

Returns a new Event object that is a copy of the original instance of the Event object. + You do not normally call clone(); the EventDispatcher class calls it automatically + when you redispatch an event—that is, when you call dispatchEvent(event) from a handler + that is handling event.

+ +

The new Event object includes all the properties of the original.

+ +

When creating your own custom Event class, you must override the + inherited Event.clone() method in order for it to duplicate the + properties of your custom class. If you do not set all the properties that you add + in your event subclass, those properties will not have the correct values when listeners + handle the redispatched event.

+ +

In this example, PingEvent is a subclass of Event + and therefore implements its own version of clone().

+ + + class PingEvent extends Event { + var URL:String; + + public override function clone():Event { + return new PingEvent(type, bubbles, cancelable, URL); + } + } + + +
toString + + Returns a string containing all the properties of the Event object.A string containing all the properties of the Event object. + + String + + Returns a string containing all the properties of the Event object. The string is in the following format: +

[Event type=value bubbles=value cancelable=value]

+ +
STORAGE_VOLUME_MOUNT + The StorageVolumeChangeEvent.VOLUME_MOUNT constant defines the value of the + type property of a StorageVolumeChangeEvent when a volume is mounted.storageVolumeMountString + The StorageVolumeChangeEvent.VOLUME_MOUNT constant defines the value of the + type property of a StorageVolumeChangeEvent when a volume is mounted. + +

The event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe StorageVolumeChangeEvent object.fileA File object representing the storage volume.nameThe name of the storage volume.targetThe StorageVolumeChangeEvent object.type"storageVolumeMount" + +
flash.filesystem.StorageVolumeInfo
STORAGE_VOLUME_UNMOUNT + The StorageVolumeChangeEvent.VOLUME_MOUNT constant defines the value of the + type property of a StorageVolumeChangeEvent when a volume is unmounted.storageVolumeUnmountString + The StorageVolumeChangeEvent.VOLUME_MOUNT constant defines the value of the + type property of a StorageVolumeChangeEvent when a volume is unmounted. + +

The event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe StorageVolumeChangeEvent object.fileA File object representing the storage volume.nameThe name of the storage volume.targetThe StorageVolumeChangeEvent object.type"storageVolumeUnmount" + +
flash.filesystem.StorageVolumeInfo
rootDirectory + A File object corresponding to the root directory of the mounted volume.flash.filesystem:File + A File object corresponding to the root directory of the mounted volume. + If the volume has been unmounted (if the event type is storageVolumeUnmount, + this property is set to null. + + flash.filesystem.FilestorageVolume + A StorageVolume object containing information about a mounted volume.flash.filesystem:StorageVolume + A StorageVolume object containing information about a mounted volume. This property is null + for an unmounted volume (for an storageVolumeUnmount event). + + flash.filesystem.StorageVolume
SQLEvent + Adobe AIR dispatches SQLEvent objects when one of the operations performed by + a SQLConnection or SQLStatement instance completes successfully.flash.events:Event + Adobe AIR dispatches SQLEvent objects when one of the operations performed by + a SQLConnection or SQLStatement instance completes successfully. + + flash.data.SQLConnectionflash.data.SQLStatementanalyzeflash.events:SQLEvent:ANALYZEflash.events:SQLEventflash.data.SQLConnection.analyze()attachflash.events:SQLEvent:ATTACHflash.events:SQLEventflash.data.SQLConnection.attach()beginflash.events:SQLEvent:BEGINflash.events:SQLEventflash.data.SQLConnection.begin()cancelflash.events:SQLEvent:CANCELflash.events:SQLEventflash.data.SQLConnection.cancel()closeflash.events:SQLEvent:CLOSEflash.events:SQLEventflash.data.SQLConnection.close()commitflash.events:SQLEvent:COMMITflash.events:SQLEventflash.data.SQLConnection.commit()compactflash.events:SQLEvent:COMPACTflash.events:SQLEventflash.data.SQLConnection.compact()deanalyzeflash.events:SQLEvent:DEANALYZEflash.events:SQLEventflash.data.SQLConnection.deanalyze()detachflash.events:SQLEvent:DETACHflash.events:SQLEventflash.data.SQLConnection.detach()openflash.events:SQLEvent:OPENflash.events:SQLEventflash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()reencryptflash.events:SQLEvent:REENCRYPTflash.events:SQLEventflash.data.SQLConnection.reencrypt()releaseSavepointflash.events:SQLEvent:RELEASE_SAVEPOINTflash.events:SQLEventflash.data.SQLConnection.releaseSavepoint()resultflash.events:SQLEvent:RESULTflash.events:SQLEventflash.data.SQLStatement.execute()flash.data.SQLStatement.next()flash.data.SQLStatement.getResult()rollbackToSavepointflash.events:SQLEvent:ROLLBACK_TO_SAVEPOINTflash.events:SQLEventflash.data.SQLConnection.rollbackToSavepoint()rollbackflash.events:SQLEvent:ROLLBACKflash.events:SQLEventflash.data.SQLConnection.rollback()schemaflash.events:SQLEvent:SCHEMAflash.events:SQLEventflash.data.SQLConnection.loadSchema()setSavepointflash.events:SQLEvent:SET_SAVEPOINTflash.events:SQLEventflash.data.SQLConnection.setSavepoint()SQLEvent + Creates a SQLEvent object to pass as a parameter to event listeners.typeString The type of the event, available in the type property. + + bubblesBooleanfalse Determines whether the Event object participates in the bubbling + stage of the event flow. The default value is false. + + cancelableBooleanfalseDetermines whether the Event object can be canceled. + The default value is false. + + Used to create new SQLEvent object. + + + Creates a SQLEvent object to pass as a parameter to event listeners. + + clone + Creates a copy of the SQLEvent object and sets the value of each property to match + that of the original.A new SQLEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the SQLEvent object and sets the value of each property to match + that of the original. + + ANALYZE + The SQLEvent.ANALYZE constant defines the value of the + type property of an analyze event object.analyzeString + The SQLEvent.ANALYZE constant defines the value of the + type property of an analyze event object. + This type of event is dispatched when a + SQLConnection.analyze() method call completes successfully. + + The analyze event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.analyze()ATTACH + The SQLEvent.ATTACH constant defines the value of the + type property of an attach event object.attachString + The SQLEvent.ATTACH constant defines the value of the + type property of an attach event object. + This type of event is dispatched when a + SQLConnection.attach() method call completes successfully. + + The attach event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.attach()BEGIN + The SQLEvent.BEGIN constant defines the value of the + type property of a begin event object.beginString + The SQLEvent.BEGIN constant defines the value of the + type property of a begin event object. + This type of event is dispatched when a + SQLConnection.begin() method call completes successfully. + + The begin event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.begin()CANCEL + The SQLEvent.CANCEL constant defines the value of the + type property of a cancel event object.cancelString + The SQLEvent.CANCEL constant defines the value of the + type property of a cancel event object. + This type of event is dispatched when a SQLConnection.cancel() + method call completes successfully. + + The cancel event has the following properties: + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection or SQLStatement object that performed the operation. + + flash.data.SQLConnection.cancel()CLOSE + The SQLEvent.CLOSE constant defines the value of the + type property of a close event object.closeString + The SQLEvent.CLOSE constant defines the value of the + type property of a close event object. + This type of event is dispatched when a + SQLConnection.close() method call completes successfully. + + The close event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.close()COMMIT + The SQLEvent.COMMIT constant defines the value of the + type property of a commit event object.commitString + The SQLEvent.COMMIT constant defines the value of the + type property of a commit event object. + This type of event is dispatched when a + SQLConnection.commit() method call completes successfully. + + The commit event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.commit()COMPACT + The SQLEvent.COMPACT constant defines the value of the + type property of a compact event object.compactString + The SQLEvent.COMPACT constant defines the value of the + type property of a compact event object. + This type of event is dispatched when a + SQLConnection.compact() method call completes successfully. + + The compact event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.compact()DEANALYZE + The SQLEvent.DEANALYZE constant defines the value of the + type property of a deanalyze event object.deanalyzeString + The SQLEvent.DEANALYZE constant defines the value of the + type property of a deanalyze event object. + This type of event is dispatched when a + SQLConnection.deanalyze() method call completes successfully. + + The deanalyze event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.deanalyze()DETACH + The SQLEvent.DETACH constant defines the value of the + type property of a detach event object.detachString + The SQLEvent.DETACH constant defines the value of the + type property of a detach event object. + This type of event is dispatched when a + SQLConnection.detach() method call completes successfully. + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.detach()OPEN + The SQLEvent.OPEN constant defines the value of the + type property of a open event object.openString + The SQLEvent.OPEN constant defines the value of the + type property of a open event object. + This type of event is dispatched when a + SQLConnection.open() or SQLConnection.openAsync() method call completes successfully. + + The open event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.open()flash.data.SQLConnection.openAsync()REENCRYPT + The SQLEvent.REENCRYPT constant defines the value of the + type property of a reencrypt event object.reencryptString + The SQLEvent.REENCRYPT constant defines the value of the + type property of a reencrypt event object. + This type of event is dispatched when a + SQLConnection.reencrypt() method call completes successfully. + + The reencrypt event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.reencrypt()RELEASE_SAVEPOINT + The SQLEvent.RELEASE_SAVEPOINT constant defines the value of the + type property of a releaseSavepoint event object.releaseSavepointString + The SQLEvent.RELEASE_SAVEPOINT constant defines the value of the + type property of a releaseSavepoint event object. + This type of event is dispatched when a SQLConnection.releaseSavepoint() + method call completes successfully. + + The releaseSavepoint event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.releaseSavepoint()RESULT + The SQLEvent.RESULT constant defines the value of the + type property of a result event object.resultString + The SQLEvent.RESULT constant defines the value of the + type property of a result event object. + Dispatched when either the SQLStatement.execute() method or + SQLStatement.next() method completes successfully. Once the + SQLEvent.RESULT event is dispatched the SQLStatement.getResult() + method can be called to access the result data. + + The result event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLStatement object that performed the operation. + + flash.data.SQLStatement.execute()flash.data.SQLStatement.next()flash.data.SQLStatement.getResult()ROLLBACK_TO_SAVEPOINT + The SQLEvent.ROLLBACK_TO_SAVEPOINT constant defines the value of the + type property of a rollbackToSavepoint event object.rollbackToSavepointString + The SQLEvent.ROLLBACK_TO_SAVEPOINT constant defines the value of the + type property of a rollbackToSavepoint event object. + This type of event is dispatched when a SQLConnection.rollbackToSavepoint() + method call completes successfully. + + The rollbackToSavepoint event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.rollbackToSavepoint()ROLLBACK + The SQLEvent.ROLLBACK constant defines the value of the + type property of a rollback event object.rollbackString + The SQLEvent.ROLLBACK constant defines the value of the + type property of a rollback event object. + This type of event is dispatched when a + SQLConnection.rollback() method call completes successfully. + + The rollback event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.rollback()SCHEMA + The SQLEvent.SCHEMA constant defines the value of the + type property of a schema event object.schemaString + The SQLEvent.SCHEMA constant defines the value of the + type property of a schema event object. + Dispatched when the SQLConnection.loadSchema() method + completes successfully. Once the SQLEvent.SCHEMA event + is dispatched the SQLConnection.getSchemaResult() method can be + used to get the schema information. + + The schema event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.loadSchema()SET_SAVEPOINT + The SQLEvent.SET_SAVEPOINT constant defines the value of the + type property of a setSavepoint event object.setSavepointString + The SQLEvent.SET_SAVEPOINT constant defines the value of the + type property of a setSavepoint event object. + This type of event is dispatched when a SQLConnection.setSavepoint() + method call completes successfully. + + The setSavepoint event has the following properties: + + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the event + object with an event listener.targetThe SQLConnection object that performed the operation. + + flash.data.SQLConnection.setSavepoint()DRMErrorEvent + The DRMErrorEvent class provides information about errors that occur when playing digital rights management (DRM) + encrypted files.Event objects for DRM-enabled objects. + flash.events:ErrorEvent + The DRMErrorEvent class provides information about errors that occur when playing digital rights management (DRM) + encrypted files. + +

The runtime dispatches a DRMErrorEvent object when a NetStream object, trying to play a digital rights management + (DRM) encrypted file, encounters a DRM-related error. For example, a DRMErrorEvent object is dispatched + when the content provider does not support the viewing application, + or when the user authorization fails, possibly because the user has not purchased the content.

+

+ In the case of invalid user credentials, the DRMAuthenticateEvent object handles the error by repeatedly dispatching + until the user enters valid credentials, or the application denies further attempts. The application should listen + to any other DRM error events in order to detect, identify, and handle the DRM-related errors. +

+

+ This class provides properties containing the object throwing the exception, the error code, and, + where applicable, a suberror code and text message containing information related to the error. For + a description of DRM-related error codes, see the Runtime error codes. + The DRM-related error codes start at error 3300. +

+ +
package +{ + import flash.display.Sprite; + import flash.events.AsyncErrorEvent; + import flash.events.NetStatusEvent; + import flash.events.DRMErrorEvent; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + + public class DRMVideoExample extends Sprite + { + var videoURL:String = "Video.flv"; + var videoConnection:NetConnection; + var videoStream:NetStream; + var video:Video = new Video(); + + public function DRMVideoExample() + { + videoConnection = new NetConnection(); + videoConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + videoConnection.connect(null); + } + + private function connectStream():void { + videoStream = new NetStream(videoConnection); + videoStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + videoStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + videoStream.addEventListener(DRMErrorEvent.DRM_ERROR, drmErrorEventHandler); + video.attachNetStream(videoStream); + videoStream.play(videoURL); + addChild(video); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Unable to locate video: " + videoURL); + break; + } + } + + private function asyncErrorHandler(event:AsyncErrorEvent):void { + // ignore AsyncErrorEvent events. + } + + private function drmErrorEventHandler(event:DRMErrorEvent):void { + trace(event.toString()); + } + } +} +
flash.net.NetStreamDRMErrorEvent.DRM_ERRORRuntime error codesdrmErrorflash.events:DRMErrorEvent:DRM_ERRORflash.events:DRMErrorEventflash.net.NetStream.drmErrorDRMErrorEvent + Creates an Event object that contains specific information about DRM error events.typeStringunknown The type of the event. Event listeners can access this information through the inherited type property. There is only one type of DRMAuthenticate event: DRMAuthenticateEvent.DRM_AUTHENTICATE. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling stage of the event flow. Event listeners can access this information through the inherited bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can access this information through the inherited cancelable property. + inErrorDetailStringWhere applicable, the specific syntactical details of the error. + inErrorCodeint0The major error code. + insubErrorIDint0The minor error ID. + + inMetadataflash.net.drm:DRMContentDatanullinSystemUpdateNeededBooleanfalseinDrmUpdateNeededBooleanfalse + Creates an Event object that contains specific information about DRM error events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the DRMErrorEvent object and sets the value of each property to match + that of the original.A new DRMErrorEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the DRMErrorEvent object and sets the value of each property to match + that of the original. + + toString + Returns a string that contains all the properties of the DRMErrorEvent object.A string that contains all the properties of the DRMErrorEvent object. + + String + Returns a string that contains all the properties of the DRMErrorEvent object. + The string is in the following format: +

[DRMErrorEvent type=value bubbles=value cancelable=value + eventPhase=value errroID=value subErrorID=value text=value

+ +
DRM_ERROR + The DRMErrorEvent.DRM_ERROR constant defines the value of the + type property of a drmError event object.drmErrorString + The DRMErrorEvent.DRM_ERROR constant defines the value of the + type property of a drmError event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsecancelablefalse; there is no default behavior to cancel.errorIDA numerical error code assigned to the problem.subErrorIDAn error code that indicates more detailed information about + the underlying problem.targetThe NetStream object. + +
flash.net.NetStream.drmError
contentData + The DRMContentData for the media file.flash.net.drm:DRMContentData + The DRMContentData for the media file. + +

You can use the object referenced by the contentData property + to retrieve the related DRM voucher from the DRMManager voucher cache. The voucher + properties describe the license available to the user and may explain why the + DRM-protected content cannot be viewed.

+ +
drmUpdateNeeded + Indicates whether a DRM update is needed to play the DRM-protected content.Boolean + Indicates whether a DRM update is needed to play the DRM-protected content. + + subErrorID + An error ID that indicates more detailed information about the underlying problem.int + An error ID that indicates more detailed information about the underlying problem. + + systemUpdateNeeded + Indicates whether a system update is needed to play the DRM-protected content.Boolean + Indicates whether a system update is needed to play the DRM-protected content. + +
EventPhase + The EventPhase class provides values for the eventPhase property of the Event class.Object + The EventPhase class provides values for the eventPhase property of the Event class. + Event classEventDispatcher classAT_TARGET + The target phase, which is the second phase of the event flow.2uint + The target phase, which is the second phase of the event flow. + BUBBLING_PHASE + The bubbling phase, which is the third phase of the event flow.3uint + The bubbling phase, which is the third phase of the event flow. + CAPTURING_PHASE + The capturing phase, which is the first phase of the event flow.1uint + The capturing phase, which is the first phase of the event flow. + FocusEvent + An object dispatches a FocusEvent object when the user changes the focus from one object + in the display list to another.Event objects for Focus events. + + + flash.events:Event + An object dispatches a FocusEvent object when the user changes the focus from one object + in the display list to another. There are four types of focus events: +
  • FocusEvent.FOCUS_IN
  • FocusEvent.FOCUS_OUT
  • FocusEvent.KEY_FOCUS_CHANGE
  • FocusEvent.MOUSE_FOCUS_CHANGE
+ +
The following example uses the FocusEventExample and + CustomSprite classes to show how focus can be used in conjunction with items drawn on the Stage to capture events and print information. + This example carries out the following tasks: +
  1. It declares the properties child (of type Sprite) and childCount (of type uint).
  2. A for loop creates five light blue squares at (0,0). It begins by + assigning child to a new CustomSprite instance. Each time a CustomSprite + object is created, the following happens: +
    • The size property of type uint is set to 50 pixels and bgColor is set + to light blue.
    • The buttonMode and useHandCursor properties of the + Sprite class are set to true within the constructor.
    • An event listener of type click is instantiated, along with the associated subscriber + clickHandler(). The subscriber method creates a local variable target of + type Sprite and assigns it whichever box was clicked. The Stage's focus is then assigned to + target.
    • The draw() method is called, which creates a 50 x 50 pixel square by + calling the beginFill(), drawRect(), and endFill() methods of + the Graphics class and the instance properties.
  3. In the for loop, the configureListeners() method is called, which instantiates three event + listeners/subscribers: +
    • focusIn/focusInHandler() is dispatched after the click event + for whichever display list object (box) is clicked.
    • focusOut/focusOutHandler() is dispatched when another box is clicked or + if the focus leaves the Stage (for example, by clicking outside Flash Player).
    • keyFocusChange/keyFocusChangeHandler() is dispatched if you use the Tab key + or the left-arrow or right-arrow keys to select a display list object. The keyFocusChangeHandler() + method traps the left-arrow and right-arrow keys, however, and calls the preventDefault() method + to disable them.
  4. In the for loop, each square is added to the display list and displayed (all in + the same area) by means of addChild().
  5. The constructor then calls refreshLayout(), which distributes the orange + squares across the top (y = 0) of the display with 5 pixels separating each square.
+ +package { + import flash.display.Sprite; + import flash.display.DisplayObject; + import flash.events.FocusEvent; + import flash.events.IEventDispatcher; + + public class FocusEventExample extends Sprite { + private var gutter:uint = 5; + private var childCount:uint = 5; + + public function FocusEventExample() { + var child:Sprite; + for(var i:uint; i < childCount; i++) { + child = new CustomSprite(); + configureListeners(child); + addChild(child); + } + refreshLayout(); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(FocusEvent.FOCUS_IN, focusInHandler); + dispatcher.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler); + dispatcher.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler); + dispatcher.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler); + } + + private function refreshLayout():void { + var ln:uint = numChildren; + var child:DisplayObject = getChildAt(0); + var lastChild:DisplayObject = child; + for(var i:uint = 1; i < ln; i++) { + child = getChildAt(i); + child.x = lastChild.x + lastChild.width + gutter; + lastChild = child; + } + } + + private function focusInHandler(event:FocusEvent):void { + var target:CustomSprite = CustomSprite(event.target); + trace("focusInHandler: " + target.name); + } + + private function focusOutHandler(event:FocusEvent):void { + var target:CustomSprite = CustomSprite(event.target); + trace("focusOutHandler: " + target.name); + } + + private function keyFocusChangeHandler(event:FocusEvent):void { + if(event.keyCode == 39 || event.keyCode == 37){ + event.preventDefault() + } + var target:CustomSprite = CustomSprite(event.target); + trace("keyFocusChangeHandler: " + target.name); + } + private function mouseFocusChangeHandler(event:FocusEvent):void { + var target:CustomSprite = CustomSprite(event.target); + trace("mouseFocusChangeHandler: " + target.name); + } + } +} + +import flash.display.Sprite; +import flash.events.MouseEvent; + +class CustomSprite extends Sprite { + private var size:uint = 50; + private var bgColor:uint = 0x00CCFF; + + public function CustomSprite() { + buttonMode = true; + useHandCursor = true; + addEventListener(MouseEvent.CLICK, clickHandler); + draw(size, size); + } + + private function draw(w:uint, h:uint):void { + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, w, h); + graphics.endFill(); + } + + private function clickHandler(event:MouseEvent):void { + var target:Sprite = Sprite(event.target); + trace("clickHandler: " + target.name); + stage.focus = target; + } +} +
focusInflash.events:FocusEvent:FOCUS_INflash.events:FocusEventflash.display.InteractiveObject.focusInfocusOutflash.events:FocusEvent:FOCUS_OUTflash.events:FocusEventflash.display.InteractiveObject.focusOutkeyFocusChangeflash.events:FocusEvent:KEY_FOCUS_CHANGEflash.events:FocusEventflash.display.InteractiveObject.keyFocusChangemouseFocusChangeflash.events:FocusEvent:MOUSE_FOCUS_CHANGEflash.events:FocusEventflash.display.InteractiveObject.mouseFocusChangeFocusEvent + Creates an Event object with specific information relevant to focus events.typeString The type of the event. Possible values are: + FocusEvent.FOCUS_IN, FocusEvent.FOCUS_OUT, FocusEvent.KEY_FOCUS_CHANGE, and FocusEvent.MOUSE_FOCUS_CHANGE. + bubblesBooleantrue Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + relatedObjectflash.display:InteractiveObjectnullIndicates the complementary InteractiveObject instance that is affected by the change in focus. For example, when a focusIn event occurs, relatedObject represents the InteractiveObject that has lost focus. + shiftKeyBooleanfalseIndicates whether the Shift key modifier is activated. + keyCodeuint0Indicates the code of the key pressed to trigger a keyFocusChange event. + directionStringnoneIndicates from which direction the target interactive object is being activated. Set to + FocusDirection.NONE (the default value) for all events other than focusIn. + + Constructor for FocusEvent objects. + + + Creates an Event object with specific information relevant to focus events. + Event objects are passed as parameters to event listeners. + + FOCUS_INFOCUS_OUTKEY_FOCUS_CHANGEMOUSE_FOCUS_CHANGEflash.display.FocusDirectionclone + Creates a copy of the FocusEvent object and sets the value of each property to match that of the original.A new FocusEvent object with property values that match those of the original. + + flash.events:Event + Creates a copy of the FocusEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the FocusEvent object.A string that contains all the properties of the FocusEvent object. + + String + Returns a string that contains all the properties of the FocusEvent object. The string is in the following format: +

[FocusEvent type=value bubbles=value cancelable=value relatedObject=value shiftKey=value] keyCode=value]

+ +
FOCUS_IN + Defines the value of the type property of a focusIn event object.focusInString + Defines the value of the type property of a focusIn event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.keyCode0; applies only to keyFocusChange events.relatedObjectThe complementary InteractiveObject instance that is affected by the change in focus.shiftKeyfalse; applies only to keyFocusChange events.targetThe InteractiveObject instance that has just received focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + directionThe direction from which focus was assigned. This property reports + the value of the direction parameter of the assignFocus() method of the stage. + If the focus changed through some other means, the value will always be FocusDirection.NONE. + Applies only to focusIn events. For all other focus events the value will be + FocusDirection.NONE. + +
flash.display.InteractiveObject.focusIn
FOCUS_OUT + Defines the value of the type property of a focusOut event object.focusOutString + Defines the value of the type property of a focusOut event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.keyCode0; applies only to keyFocusChange events.relatedObjectThe complementary InteractiveObject instance that is affected by the change in focus.shiftKeyfalse; applies only to keyFocusChange events.targetThe InteractiveObject instance that has just lost focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + + +
flash.display.InteractiveObject.focusOut
KEY_FOCUS_CHANGE + Defines the value of the type property of a keyFocusChange event object.keyFocusChangeString + Defines the value of the type property of a keyFocusChange event object. + +

This event has the following properties:

+ PropertyValuebubblestruecancelabletrue; call the preventDefault() method + to cancel default behavior.currentTargetThe object that is actively processing + the Event + object with an event listener.keyCodeThe key code value of the key pressed to trigger a keyFocusChange event.relatedObjectThe complementary InteractiveObject instance that is affected by the change in focus.shiftKeytrue if the Shift key modifier is activated; false otherwise.targetThe InteractiveObject instance that currently has focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + + +
flash.display.InteractiveObject.keyFocusChange
MOUSE_FOCUS_CHANGE + Defines the value of the type property of a mouseFocusChange event object.mouseFocusChangeString + Defines the value of the type property of a mouseFocusChange event object. +

This event has the following properties:

+ PropertyValuebubblestruecancelabletrue; call the preventDefault() method + to cancel default behavior.currentTargetThe object that is actively processing the Event + object with an event listener.keyCode0; applies only to keyFocusChange events.relatedObjectThe complementary InteractiveObject instance that is affected by the change in focus.shiftKeyfalse; applies only to keyFocusChange events.targetThe InteractiveObject instance that currently has focus. + The target is not always the object in the display list + that registered the event listener. Use the currentTarget + property to access the object in the display list that is currently processing the event. + + + +
flash.display.InteractiveObject.mouseFocusChange
direction + Specifies direction of focus for a focusIn event.String + Specifies direction of focus for a focusIn event. + + flash.display.FocusDirectionflash.display.Stage.assignFocus()isRelatedObjectInaccessible + If true, the relatedObject property is set to null for + reasons related to security sandboxes.Boolean + If true, the relatedObject property is set to null for + reasons related to security sandboxes. If the nominal value of relatedObject is a reference to a + DisplayObject in another sandbox, relatedObject is set to + null unless there is permission in both directions across this sandbox boundary. Permission is + established by calling Security.allowDomain() from a SWF file, or by providing + a policy file from the server of an image file, and setting the LoaderContext.checkPolicyFile + property when loading the image. + + FocusEvent.relatedObjectSecurity.allowDomain()LoaderContext.checkPolicyFilekeyCode + The key code value of the key pressed to trigger a keyFocusChange event.uint + The key code value of the key pressed to trigger a keyFocusChange event. + + relatedObject + A reference to the complementary InteractiveObject instance that is affected by the + change in focus.flash.display:InteractiveObject + A reference to the complementary InteractiveObject instance that is affected by the + change in focus. For example, when a focusOut event occurs, the + relatedObject represents the InteractiveObject instance that has gained focus. +

The value of this property can be null in two circumstances: if there no related object, + or there is a related object, but it is in a security sandbox to which you don't have access. + Use the isRelatedObjectInaccessible() property to determine which of these reasons applies.

+ +
FocusEvent.isRelatedObjectInaccessible
shiftKey + Indicates whether the Shift key modifier is activated, in which case the value is + true.Boolean + Indicates whether the Shift key modifier is activated, in which case the value is + true. Otherwise, the value is false. This property is + used only if the FocusEvent is of type keyFocusChange. + +
GesturePhase + The GesturePhase class is an enumeration class of constant values for use with the GestureEvent, PressAndTapGestureEvent, and TransformGestureEvent + classes.Object + The GesturePhase class is an enumeration class of constant values for use with the GestureEvent, PressAndTapGestureEvent, and TransformGestureEvent + classes. Use these values to track the beginning, progress, and end of a touch gesture (such as moving several fingers across + a touch enabled screen) so your application can respond to individual stages of user contact. Some gestures (swipe and two-finger tap gestures) + do not have multiple phases, and set the event object phase property to all. + + + The following example shows event handling for the GESTURE_ROTATE events. + While the user performs a rotation gesture on the touch-enabled device, mySprite rotates and myTextField populates with the current phase. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + +var mySprite = new Sprite(); +mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE , onRotate ); +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0, 0, 100, 80); +var myTextField = new TextField(); +myTextField.y = 200; +addChild(mySprite); +addChild(myTextField); + +function onRotate(evt:TransformGestureEvent):void { + + evt.target.rotation -= 45; + + if (evt.phase==GesturePhase.BEGIN) { + myTextField.text = "Begin"; + } + if (evt.phase==GesturePhase.UPDATE) { + myTextField.text = "Update"; + } + if (evt.phase==GesturePhase.END) { + myTextField.text = "End"; + } +} +flash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventALL + A single value that encompasses all phases of simple gestures like two-finger-tap or swipe.allString + A single value that encompasses all phases of simple gestures like two-finger-tap or swipe. + For gestures that set the event object phase property to all (swipe and two-finger tap gestures), + the phase value is always all once the event is dispatched. + + flash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventBEGIN + The beginning of a new gesture (such as touching a finger to a touch enabled screen).beginString + The beginning of a new gesture (such as touching a finger to a touch enabled screen). + + + flash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventEND + The completion of a gesture (such as lifting a finger off a touch enabled screen).endString + The completion of a gesture (such as lifting a finger off a touch enabled screen). + + + flash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventUPDATE + The progress of a gesture (such as moving a finger across a touch enabled screen).updateString + The progress of a gesture (such as moving a finger across a touch enabled screen). + + + flash.events.GestureEventflash.events.TransformGestureEventflash.events.PressAndTapGestureEventBrowserInvokeEvent + The NativeApplication object of an AIR application dispatches a browserInvoke event when the + application is invoked as the result of a SWF file in the browser using the browser + invocation feature.Dispatched by the NativeApplication object when an AIR application is invoked through a web browser. + + flash.events:Event + The NativeApplication object of an AIR application dispatches a browserInvoke event when the + application is invoked as the result of a SWF file in the browser using the browser + invocation feature. The NativeApplication object also dispatches a browserInvoke event when + a user instantiates the seamless installation feature in the browser and the SWF file in + the browser passes an array to the arguments parameter of the + launchApplication() method of the air.swf file. (For details, see + "Distributing, installing and running AIR applications" in the AIR developer's guide.) + +

Browser invocation is permitted only if an application specifies the following in + the application descriptor file:

+ + <allowBrowserInvocation>true</allowBrowserInvocation> + +

If the application is not running, the NativeApplication object dispatches both an InvokeEvent + event and a browserInvoke event when launched from the browser. Otherwise, + if the application is already running, the NativeApplication object dispatches only + a browserInvoke event when launched from the browser.

+ +

If the application is launched as the result of a seamless installation from the browser (with + the user choosing to launch upon installation), the NativeApplication object dispatches a BrowserInvoke + event only if arguments were passed (via the SWF file in the browser passing an array to + the arguments parameter of the installApplication() + method of the air.swf file). For details, see "Distributing, installing, and running AIR + applications" in the AIR developer's guide.

+ +

Like the invokeEvent events, browserInvokeEvent events are dispatched by the + NativeApplication object (NativeApplication.nativeApplication). To receive browserInvoke + events, call the addEventListener() method of the NativeApplication object. When an event listener + registers for a browserInvoke event, it will also receive all browserInvoke events that + occurred before the registration. These are dispatched after the call to addEventListener() + returns, but not necessarily before other browserInvoke events that might be received after registration. + This allows you to handle browserInvoke events that have occurred before your initialization code + is executed (such as when the application was initially invoked from the browser). Keep in mind that if you + add an event listener later in execution (after application initialization), it still receives all + browserInvoke events that have occurred since the application started.

+ +
flash.events.InvokeEventflash.desktop.NativeApplicationinvokeflash.events:BrowserInvokeEvent:BROWSER_INVOKEflash.events:BrowserInvokeEventflash.desktop.NativeApplicationBrowserInvokeEvent + The constructor function for the BrowserInvokeEvent class.typeStringThe type of the event, accessible as Event.type. + + bubblesBooleanSet to false for a BrowserInvokeEvent object. + + cancelableBooleanSet to false for a BrowserInvokeEvent object. + + argumentsArrayAn array of arguments (strings) to pass to the application. + + sandboxTypeStringThe sandbox type for the content in the browser. + + securityDomainStringThe security domain for the content in the browser. + + isHTTPSBooleanWhether the content in the browser uses the HTTPS URL scheme. + + isUserEventBooleanWhether the browser invocation was the result of a user event. + + + The constructor function for the BrowserInvokeEvent class. + + Generally, developers do not call the BrowserInvokeEvent() constructor directly. + Only the runtime should create a BrowserInvokeEvent object. + + clone + Creates a new copy of this event.The copy of the event. + flash.events:Event + Creates a new copy of this event. + + BROWSER_INVOKE + The BrowserInvokeEvent.BROWSER_INVOKE constant defines the value of the type + property of a BrowserInvokeEvent object.browserInvokeString + The BrowserInvokeEvent.BROWSER_INVOKE constant defines the value of the type + property of a BrowserInvokeEvent object. + +

The BrowserInvokeEvent object has the following properties:

+ PropertiesValuesargumentsThe array of string arguments passed + during this invocation.sandBoxTypeA string representing the + the sandbox type for the content in the browser (either + Security.APPLICATION, Security.LOCAL_TRUSTED, Security.LOCAL_WITH_FILE, + Security.LOCAL_LOCAL_WITH_NETWORK, or Security.REMOTE).securityDomainA string representing the + the security domain for the content in the browser (such as "www.example.com").isHTTPSWhether the browser content uses the + HTTPS URL scheme (true) or not (false)isUserEventWhether the browser invocation resulted + from a user event (always true in AIR 1.0).bubblesNo.cancelablefalse; + There is no default behavior to cancel.currentTargetIndicates the object that is + actively processing this InvokeEvent object with an event listener.targetAlways the NativeApplication object. + + +
flash.desktop.NativeApplication
arguments + An array of arguments (strings) to pass to the application.Array + An array of arguments (strings) to pass to the application. + + isHTTPS + Whether the content in the browser uses the HTTPS + URL scheme (true) or not (false).Boolean + Whether the content in the browser uses the HTTPS + URL scheme (true) or not (false). + + isUserEvent + Whether the browser invocation resulted in a user event (such as + a mouse click).Boolean + Whether the browser invocation resulted in a user event (such as + a mouse click). In AIR 1.0, this is always set to true; + AIR requires a user event to initiate a call to the browser invocation feature. + + sandboxType + The sandbox type for the content in the browser.String + The sandbox type for the content in the browser. This can be set + to one of the following values: + +
  • Security.APPLICATION — The content is in + the application security sandbox.
  • Security.LOCAL_TRUSTED — The content is in + the local-trusted security sandbox.
  • Security.LOCAL_WITH_FILE — The content is in + the local-with-filesystem security sandbox.
  • Security.LOCAL_WITH_NETWORK — The content is in + the local-with-networking security sandbox.
  • Security.REMOTE — The content is in + a remote (network) domain
+ +
flash.system.Security.sandboxType
securityDomain + The security domain for the content in the browser, such as + "www.adobe.com" or "www.example.org".String + The security domain for the content in the browser, such as + "www.adobe.com" or "www.example.org". + This property is set only for content in the remote security + sandbox (for content from a network domain), not for content + in a local or application security sandbox. + +
OutputProgressEvent + A FileStream object dispatches OutputProgressEvent objects as pending asynchronous file write operations are + performed.Event objects for output progress events (for asynchronous file write operations). + + flash.events:Event + A FileStream object dispatches OutputProgressEvent objects as pending asynchronous file write operations are + performed. There is one type of output progress event: OutputProgressEvent.OUTPUT_PROGRESS. + + flash.filesystem.FileStreamoutputProgressflash.events:OutputProgressEvent:OUTPUT_PROGRESSflash.events:OutputProgressEventflash.filesystem.FileStreamOutputProgressEvent + Creates an Event object that contains information about output progress events.typeString The type of the event. There is only one type of error event: + OutputProgressEvent.OUTPUT_PROGRESS. + + bubblesBooleanfalse Determines whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseDetermines whether the Event object can be canceled. + bytesPendingNumber0The number of bytes not yet written. + bytesTotalNumber0The total number of bytes written or with pending writes. + + Constructor for OutputProgressEvent objects. + + Creates an Event object that contains information about output progress events. + Event objects are passed as parameters to event listeners. + + clone + Creates a copy of the OutputProgressEvent object and sets each property's value to match that of the original.A new OutputProgressEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the OutputProgressEvent object and sets each property's value to match that of the original. + + toString + Returns a string that contains all the properties of the OutputProgressEvent object.A string that contains all the properties of the OutputProgressEvent object. + String + Returns a string that contains all the properties of the OutputProgressEvent object. The string is in the following format: + +

[OutputProgressEvent type=value bubbles=value cancelable=value eventPhase=value bytesPending=value bytesTotal=value]

+ +
OUTPUT_PROGRESS + Defines the value of the type property of an outputProgress event object.outputProgressString + Defines the value of the type property of an outputProgress event object. + +

This event has the following properties:

+ + PropertyValuebubblesfalsebytesPendingThe number of bytes remaining to be written at the time the + listener processes the event.bytesTotalThe total number of bytes that ultimately + will be written if the write process succeeds.cancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe FileStream object reporting progress. + +
flash.filesystem.FileStream
bytesPending + The number of bytes not yet written when the listener processes the event.Number + The number of bytes not yet written when the listener processes the event. + + bytesTotal + The total number of bytes written so far, plus the number of pending bytes to be written.Number + The total number of bytes written so far, plus the number of pending bytes to be written. + +
StageOrientationEvent + A Stage object dispatches a StageOrientationEvent object when the orientation + of the stage changes.flash.events:Event + A Stage object dispatches a StageOrientationEvent object when the orientation + of the stage changes. This can occur when the + device is rotated, + when the user opens a slide-out keyboard, or when the setAspectRatio() + method of the Stage is called. + +

There are two types of StageOrientationEvent event: + The orientationChanging + (StageOrientationEvent.ORIENTATION_CHANGING), is dispatched + before the screen changes to a new orientation. Calling the preventDefault() + method of the event object dispatched for orientationChanging prevents the stage from + changing orientation. + The orientationChange + (StageOrientationEvent.ORIENTATION_CHANGE), is dispatched + after the screen changes to a new orientation.

+ +

Note: If the autoOrients property is false, then the stage orientation + does not change when a device is rotated. Thus, StageOrientationEvents are only dispatched for + device rotation when autoOrients is true.

+ +
Stage.deviceOrientationStage.autoOrientsorientationChangeflash.events:StageOrientationEvent:ORIENTATION_CHANGEflash.events:StageOrientationEventflash.display.StagedeviceOrientationStageOrientationEvent + Creates a StageOrientationEvent object with specific information relevant to stage orientation events.typeString The type of the event: StageOrientationEvent.ORIENTATION_CHANGE + bubblesBooleanfalse Indicates whether the Event object participates in the bubbling stage of the event flow. + cancelableBooleanfalseIndicates whether the Event object can be canceled. + beforeOrientationStringnullIndicates the orientation before the change. + afterOrientationStringnullIndicates the orientation after the change. + + + Creates a StageOrientationEvent object with specific information relevant to stage orientation events. + Event objects are passed as parameters to event listeners. Generally you do not create + this event using the constructor function. Instead, you add an event listener on the + Stage object to detect these events as they occur. + + clone + Creates a copy of the StageOrientationEvent object and sets the value of each property to match that of the original.A new StageOrientationEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of the StageOrientationEvent object and sets the value of each property to match that of the original. + + toString + Returns a string that contains all the properties of the StageOrientationEvent object.A string that contains all the properties of the StageOrientationEvent object. + String + Returns a string that contains all the properties of the StageOrientationEvent object. The string has the following format: +

[StageOrientationEvent type=value bubbles=value cancelable=value beforeDisplayState=value afterDisplayState=value]

+ +
ORIENTATION_CHANGE + The ORIENTATION_CHANGE constant defines the value of the type property of + a orientationChange event object.orientationChangeString + The ORIENTATION_CHANGE constant defines the value of the type property of + a orientationChange event object. + + This event has the following properties: + + PropertiesValuesafterOrientationThe new orientation of the stage.beforeOrientationThe old orientation of the stage.targetThe Stage object that dispatched the orientation change. + bubblestruecurrentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelablefalse; it is too late to cancel the change. + + flash.display.StagedeviceOrientationORIENTATION_CHANGING + The ORIENTATION_CHANGING constant defines the value of the type property of + a orientationChanging event object.orientationChangingString + The ORIENTATION_CHANGING constant defines the value of the type property of + a orientationChanging event object. + +

Important: ORIENTATION_CHANGING events are not dispatched on Android devices.

+ + This event has the following properties: + + PropertiesValuesafterOrientationThe new orientation of the stage.beforeOrientationThe old orientation of the stage.targetThe Stage object that dispatched the orientation change. + bubblestruecurrentTargetIndicates the object that is actively processing the Event + object with an event listener.cancelabletrue. +
afterOrientation + The orientation of the stage after the change.String + The orientation of the stage after the change. + + + beforeOrientation + The orientation of the stage before the change.String + The orientation of the stage before the change. + +
ActivityEvent +A Camera or Microphone object dispatches an ActivityEvent object whenever a camera or microphone reports that it has +become active or inactive.Event objects for ActivityEvent events. +flash.events:Event +A Camera or Microphone object dispatches an ActivityEvent object whenever a camera or microphone reports that it has +become active or inactive. There is only one type of activity event: ActivityEvent.ACTIVITY. + + The following example demonstrates the use of the ActivityEvent class by + attaching an event listener method named activityHandler() to the microphone and + generating text information every time the microphone generates an activity event. + + +package { + import flash.display.Sprite; + import flash.events.ActivityEvent; + import flash.media.Microphone; + + public class ActivityEventExample extends Sprite { + public function ActivityEventExample() { + var mic:Microphone = Microphone.getMicrophone(); + mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler); + } + + private function activityHandler(event:ActivityEvent):void { + trace("event: " + event); + trace("event.activating: " + event.activating); + } + } +} +ActivityEvent.ACTIVITYactivityflash.events:ActivityEvent:ACTIVITYflash.events:ActivityEventflash.media.Camera.activityflash.media.Microphone.activityActivityEvent + Creates an event object that contains information about activity events.typeString The type of the event. Event listeners can access this information through the + inherited type property. There is only one type of activity event: + ActivityEvent.ACTIVITY. + bubblesBooleanfalseDetermines whether the Event object participates in the bubbling phase of the + event flow. Event listeners can access this information through the inherited + bubbles property. + cancelableBooleanfalseDetermines whether the Event object can be canceled. Event listeners can + access this information through the inherited cancelable property. + activatingBooleanfalseIndicates whether the device is activating (true) or + deactivating (false). Event listeners can access this information through the + activating property. + + Constructor for ActivityEvent objects. + + Creates an event object that contains information about activity events. + Event objects are passed as parameters to Event listeners. + + ActivityEvent.ACTIVITYclone + Creates a copy of an ActivityEvent object and sets the value of each property to match that of + the original.A new ActivityEvent object with property values that match those of the original. + flash.events:Event + Creates a copy of an ActivityEvent object and sets the value of each property to match that of + the original. + + toString + Returns a string that contains all the properties of the ActivityEvent object.A string that contains all the properties of the ActivityEvent object. + String + Returns a string that contains all the properties of the ActivityEvent object. The following + format is used: +

[ActivityEvent type=value bubbles=value cancelable=value + activating=value]

+ +
ACTIVITY + The ActivityEvent.ACTIVITY constant defines the value of the type property of an activity event object.activityString + The ActivityEvent.ACTIVITY constant defines the value of the type property of an activity event object. +

This event has the following properties:

+ PropertyValueactivatingtrue if the device is activating or false if it is deactivating.bubblesfalsecancelablefalse; there is no default behavior to cancel.currentTargetThe object that is actively processing the Event + object with an event listener.targetThe object beginning or ending a session, such as a Camera or + Microphone object. + +
flash.media.Camera.activityflash.media.Microphone.activity
activating + Indicates whether the device is activating (true) or deactivating + (false).Boolean + Indicates whether the device is activating (true) or deactivating + (false). + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.external.xml b/language-server/playerglobal_docs/flash.external.xml new file mode 100644 index 0000000..d9b0949 --- /dev/null +++ b/language-server/playerglobal_docs/flash.external.xml @@ -0,0 +1,571 @@ +flash.externalExtensionContext + + The ExtensionContext class provides an interface for calling functions + in the native implementation of an ActionScript extension.flash.events:EventDispatcher + The ExtensionContext class provides an interface for calling functions + in the native implementation of an ActionScript extension. You can use this class only + in ActionScript classes that are part of the extension. + +

AIR profile support: This feature is supported + only on AIR for TV devices in applications that use the extendedTV + device profile.

+ +

An ActionScript extension is a combination of:

+ +

  • ActionScript classes.
  • Native code. Native code is code that executes on a device outside the runtime. + For example, code that you write in C is native code.

+ +

You can create an ActionScript extension to give an AIR application access + to device-specific features. Other reasons to create an ActionScript extension are to + reuse existing native code, or to provide more efficient processing using native code than + you can provide with ActionScript code. For more information about writing, building, and + packaging ActionScript extensions, see the PDF + + Developing ActionScript Extensions for Adobe AIR. +

+ +

Use the ExtensionContext class in the ActionScript side of an ActionScript extension to access + the native side of the extension. First, create an instance of the ExtensionContext class. + To do so, call the static method ExtensionContext.createExtensionContext().

+ +

After creating the ExtensionContext instance, use the instance's call() method to + call a native function.

+ +

When you are done with an ExtensionContext instance, call dispose() to release + any associated native resources. Without an explicit call to dispose(), + the runtime garbage collector calls dispose() when it disposes of the instance. + An explicit call to dispose() typically occurs much sooner than waiting for the + garbage collector.

+ +

An ExtensionContext instance can listen for StatusEvent events that the native code + dispatches when some asynchronous event occurs in the extension's native implementation. + Since the ExtensionContext class derives from EventDispatcher, it can in turn dispatch events.

+ +

The ExtensionContext class also provides a static method getExtensionDirectory() for + accessing the directory in which the extension is installed on the device. It also provides a + property, actionScriptData, for sharing data with the native implementation of the extension.

+ +

Note: AIR applications using the extendedDesktop profile can use the NativeProcess class + to execute native processes.

+ +
Developing ActionScript Extensions for Adobe AIRflash.desktop.NativeProcesscall + Calls the native function specified by functionName.No function corresponds to the name given by functionName. + + ArgumentErrorArgumentErrorThe method dispose() was already called + on this ExtensionContext instance. This error is also thrown if the native function + returns an invalid object reference. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe value returned by the native function. The return value is null + if the native function has no return value or returns an invalid object reference. + + ObjectfunctionNameStringA name that represents a function in the native implementation. + This name is not necessarily the actual name of the native function, but any name + agreed to between the ActionScript side and native side of the extension. + + argsA list of arguments for the native function. These arguments can be + any ActionScript objects: primitive types or ActionScript class objects. The types and + order of the arguments are agreed to between the ActionScript side and native side of + the extension. + + + Calls the native function specified by functionName. + Any additional arguments are passed to the native function. + + createExtensionContext + Creates an ExtensionContext instance for the given extension identifier and context type.The extensionID parameter is null or is not a valid extension ID. + + ArgumentErrorArgumentErrorThe new ExtensionContext instance. Returns null if no extension with the given + extensionID value is available. + + flash.external:ExtensionContextextensionIDStringThe extension identifier of the extension. This identifier has the same + value as the id element in the extension descriptor file. Application developers also + use this value in the extensionID element in the application descriptor file. + All extensions share a single, global namespace. Therefore, to avoid name conflicts, + use reverse DNS notation for the extension identifier. + + contextTypeStringThe context type of the extension. Depending on the context type, the native + implementation can perform different initializations. These differences can include the native + implementation specifying a different set of available native functions that the ActionScript + side can call. The value of the context type is any string agreed to between the ActionScript + side and the native side of the extension. Simple extensions often have no use for different context types. + In those cases, pass an empty string "" or null for the contextType value. + + + Creates an ExtensionContext instance for the given extension identifier and context type. + + dispose + Disposes of this ExtensionContext instance. + Disposes of this ExtensionContext instance. + +

The runtime notifies the native implementation, which can release any associated + native resources. After calling dispose(), the code cannot call the + call() method and cannot get or set the actionScriptData property.

+ +
getExtensionDirectory + Returns the directory in which the extension is installed on the device.The directory does not exist. The most likely reason is that the specified + extensionID is not valid. + + IOErrorflash.errors:IOErrorA File instance for the directory in which the extension is installed. + + flash.filesystem:FileextensionIDStringThe extension identifier of the extension. This identifier has the same + value as the extensionID parameter in createExtensionContext(). + + + Returns the directory in which the extension is installed on the device. + +

Sometimes an extension includes resources such as images that you want to access + from the extension's ActionScript code. Sometimes the code also requires information + that is available in the extension descriptor file, such as the extension version number. + You can use this method to access the base directory of the extension.

+ +

Regardless where the extension is located on the device, the extension's files are always + in the same location relative to this base directory of the extension. Using the File instance + that this method returns, you can navigate to and manipulate specific files included with + the extension.

+ +
actionScriptData + The ActionScript object, if any, associated with this context.ObjectThe method dispose() was already called + on this ExtensionContext instance. + + IllegalOperationErrorflash.errors:IllegalOperationError + The ActionScript object, if any, associated with this context. + +

You can associate any ActionScript object with an ExtensionContext instance. + The native implementation can also get and set this ActionScript object. Therefore, + you can use actionScriptData to share data between the ActionScript + side and the native side of an extension.

+ +

You can also set the value of actionScriptData to null.

+ + +
ExternalInterface + The ExternalInterface class is an application programming interface + that enables straightforward communication between ActionScript and the SWF + container&#8211; for example, an HTML page with JavaScript or a desktop application + that uses Flash Player to display a SWF file.Enables communications between ActionScript and the container. + + Object + The ExternalInterface class is an application programming interface + that enables straightforward communication between ActionScript and the SWF + container– for example, an HTML page with JavaScript or a desktop application + that uses Flash Player to display a SWF file. + + +

Using the ExternalInterface class, you can call an ActionScript function in + the Flash runtime, using JavaScript in the HTML page. The ActionScript function can return a value, + and JavaScript receives it immediately as the return value of the call.

+ +

This functionality replaces the + fscommand() method.

+ +

Use the ExternalInterface class in the following combinations of browser and + operating system:

+ BrowserOperating SystemOperating SystemInternet Explorer 5.0 and later Windows  Netscape 8.0 and later Windows  MacOS Mozilla 1.7.5 and later Windows  MacOS Firefox 1.0 and later Windows  MacOS Safari 1.3 and later  MacOS  + +

Flash Player for Linux version 9.0.31.0 and later supports the ExternalInterface class in the following browsers:

+ BrowserMozilla 1.7.x and laterFirefox 1.5.0.7 and laterSeaMonkey 1.0.5 and later +

The ExternalInterface class requires the user's web browser to support either + ActiveX® or the NPRuntime API that is exposed by some browsers for plug-in scripting. + Even if a browser and operating system combination are not listed above, they should support + the ExternalInterface class if they support the NPRuntime API. + See http://www.mozilla.org/projects/plugins/npruntime.html.

+

Note: When embedding SWF files within an HTML page, make sure that the id attribute is set and the + id and name attributes of the object and embed + tags do not include the following characters:

+
+ . - + ~~ / \
+ 
+

Note for Flash Player applications: Flash Player version 9.0.115.0 and later allows the . (period) character + within the id and name attributes.

+ +

Note for Flash Player applications: In Flash Player 10 and later running in a browser, using this class programmatically to + open a pop-up window may not be successful. Various browsers (and browser configurations) may block pop-up windows + at any time; it is not possible to guarantee any pop-up window will appear. + However, for the best chance of success, use this class to open a pop-up window only in code that executes + as a direct result of a user action (for example, in an event handler for a mouse click or key-press event.)

+ +

From ActionScript, you can do the following on the HTML page: +

  • Call any JavaScript function.
  • Pass any number of arguments, with any names.
  • Pass various data types (Boolean, Number, String, and so on).
  • Receive a return value from the JavaScript function.
+

+ +

From JavaScript on the HTML page, you can: +

  • Call an ActionScript function.
  • Pass arguments using standard function call notation.
  • Return a value to the JavaScript function.
+

+ +

Note for Flash Player applications: Flash Player does not currently support SWF files embedded within HTML forms.

+ +

Note for AIR applications: In Adobe AIR, the ExternalInterface class can be used to communicate between JavaScript + in an HTML page loaded in the HTMLLoader control and ActionScript in SWF content embedded in that HTML page.

+ +
The following example demonstrates sending data between Flash Player and an HTML container. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.external.ExternalInterface; + import flash.text.TextField; + import flash.utils.Timer; + import flash.text.TextFieldType; + import flash.text.TextFieldAutoSize; + + public class ExternalInterfaceExample extends Sprite { + private var input:TextField; + private var output:TextField; + private var sendBtn:Sprite; + + public function ExternalInterfaceExample() { + input = new TextField(); + input.type = TextFieldType.INPUT; + input.background = true; + input.border = true; + input.width = 350; + input.height = 18; + addChild(input); + + sendBtn = new Sprite(); + sendBtn.mouseEnabled = true; + sendBtn.x = input.width + 10; + sendBtn.graphics.beginFill(0xCCCCCC); + sendBtn.graphics.drawRoundRect(0, 0, 80, 18, 10, 10); + sendBtn.graphics.endFill(); + sendBtn.addEventListener(MouseEvent.CLICK, clickHandler); + addChild(sendBtn); + + output = new TextField(); + output.y = 25; + output.width = 450; + output.height = 325; + output.multiline = true; + output.wordWrap = true; + output.border = true; + output.text = "Initializing...\n"; + addChild(output); + + if (ExternalInterface.available) { + try { + output.appendText("Adding callback...\n"); + ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript); + if (checkJavaScriptReady()) { + output.appendText("JavaScript is ready.\n"); + } else { + output.appendText("JavaScript is not ready, creating timer.\n"); + var readyTimer:Timer = new Timer(100, 0); + readyTimer.addEventListener(TimerEvent.TIMER, timerHandler); + readyTimer.start(); + } + } catch (error:SecurityError) { + output.appendText("A SecurityError occurred: " + error.message + "\n"); + } catch (error:Error) { + output.appendText("An Error occurred: " + error.message + "\n"); + } + } else { + output.appendText("External interface is not available for this container."); + } + } + private function receivedFromJavaScript(value:String):void { + output.appendText("JavaScript says: " + value + "\n"); + } + private function checkJavaScriptReady():Boolean { + var isReady:Boolean = ExternalInterface.call("isReady"); + return isReady; + } + private function timerHandler(event:TimerEvent):void { + output.appendText("Checking JavaScript status...\n"); + var isReady:Boolean = checkJavaScriptReady(); + if (isReady) { + output.appendText("JavaScript is ready.\n"); + Timer(event.target).stop(); + } + } + private function clickHandler(event:MouseEvent):void { + if (ExternalInterface.available) { + ExternalInterface.call("sendToJavaScript", input.text); + } + } + } +} + + + In order to test the previous ActionScript code, embed the generated SWF file using the following HTML template: + + <!-- saved from url=(0014)about:internet --> + <html lang="en"> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title>ExternalInterfaceExample</title> + <script language="JavaScript"> + var jsReady = false; + function isReady() { + return jsReady; + } + function pageInit() { + jsReady = true; + document.forms["form1"].output.value += "\n" + "JavaScript is ready.\n"; + } + function thisMovie(movieName) { + if (navigator.appName.indexOf("Microsoft") != -1) { + return window[movieName]; + } else { + return document[movieName]; + } + } + function sendToActionScript(value) { + thisMovie("ExternalInterfaceExample").sendToActionScript(value); + } + function sendToJavaScript(value) { + document.forms["form1"].output.value += "ActionScript says: " + value + "\n"; + } + </script> + </head> + <body onload="pageInit();"> + + <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + id="ExternalInterfaceExample" width="500" height="375" + codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> + <param name="movie" value="ExternalInterfaceExample.swf" /> + <param name="quality" value="high" /> + <param name="bgcolor" value="#869ca7" /> + <param name="allowScriptAccess" value="sameDomain" /> + <embed src="ExternalInterfaceExample.swf" quality="high" bgcolor="#869ca7" + width="500" height="375" name="ExternalInterfaceExample" align="middle" + play="true" loop="false" quality="high" allowScriptAccess="sameDomain" + type="application/x-shockwave-flash" + pluginspage="http://www.macromedia.com/go/getflashplayer"> + </embed> + </object> + + <form name="form1" onsubmit="return false;"> + <input type="text" name="input" value="" /> + <input type="button" value="Send" onclick="sendToActionScript(this.form.input.value);" /><br /> + <textarea cols="60" rows="20" name="output" readonly="true">Initializing...</textarea> + </form> + + </body> + </html> + +
fscommand()addCallback + Registers an ActionScript method as callable from the container.The container does not support incoming calls. + Incoming calls are supported only in Internet Explorer for Windows and browsers + that use the NPRuntime API such as Mozilla 1.7.5 and later or Firefox 1.0 and later. + + ErrorErrorA callback with the specified name has already been + added by ActionScript in a sandbox to which you do not have access; you + cannot overwrite that callback. To work around this problem, rewrite the + ActionScript that originally called the addCallback() method so that it also + calls the Security.allowDomain() method. + + SecurityErrorSecurityErrorThe containing environment belongs to a security sandbox + to which the calling code does not have access. To fix this problem, follow these steps: + +
  1. In the object tag for the SWF file in the containing HTML page, + set the following parameter: + +

    <param name="allowScriptAccess" value="always" />

    + +
  2. In the SWF file, add the following ActionScript: + +

    flash.system.Security.allowDomain(sourceDomain)

    + +
+ + +
SecurityErrorSecurityError
functionNameStringThe name by which the container can invoke + the function. + closureFunctionThe function closure to invoke. This could be a + free-standing function, or it could be a method closure + referencing a method of an object instance. By passing + a method closure, you can direct the callback + at a method of a particular object instance. +

Note: Repeating addCallback() on an existing callback function + with a null closure value removes the callback.

+ + +
+ Registers an ActionScript method as callable from the container. + After a successful invocation of addCallBack(), the registered function in + the player can be called by JavaScript or ActiveX code in the container. + +

Note: For local content running in a browser, calls to the + ExternalInterface.addCallback() method work only if the SWF file and the + containing web page are in the local-trusted security sandbox. For more information, + see the Flash Player Developer Center Topic: Security.

+ +
flash.system.Security.allowDomain()
call + Calls a function exposed by the SWF container, passing zero or + more arguments.The container does not support outgoing calls. + Outgoing calls are supported only in Internet Explorer for Windows and browsers + that use the NPRuntime API such as Mozilla 1.7.5 and later or Firefox 1.0 and later. + + ErrorErrorThe containing environment belongs to a security sandbox + to which the calling code does not have access. To fix this problem, follow these steps: + +
  1. In the object tag for the SWF file in the containing HTML page, + set the following parameter: + +

    <param name="allowScriptAccess" value="always" />

    + +
  2. In the SWF file, add the following ActionScript: + +

    flash.system.Security.allowDomain(sourceDomain)

    + +
+
SecurityErrorSecurityError
The response received from the container. If the call failed– for example, if there is no such + function in the container, the interface is not available, a recursion occurred (with a Netscape + or Opera browser), or there is a security issue– null is returned and an error is thrown. + + functionNameStringThe alphanumeric name of the function to call in the container. Using a non-alphanumeric function name + causes a runtime error (error 2155). You can use a try..catch block to handle the error. + argumentsThe arguments to pass to the function in the + container. You can specify zero or more parameters, separating them with commas. + They can be of any ActionScript data type. + When the call is to a JavaScript function, the ActionScript + types are automatically converted into JavaScript types; when the call is to some other + ActiveX container, the parameters are encoded in the request message. + + Calls a function in the container. + +
+ Calls a function exposed by the SWF container, passing zero or + more arguments. If the function is not available, the call returns + null; otherwise it returns the value provided by the function. + Recursion is not permitted on Opera or Netscape browsers; on these browsers a recursive call + produces a null response. (Recursion is supported on Internet Explorer and Firefox browsers.) + +

If the container is an HTML page, this method invokes a JavaScript function + in a script element.

+ +

If the container is another ActiveX container, this method dispatches the + FlashCall ActiveX event with the specified name, and the container processes the event.

+ +

If the container is hosting the Netscape plug-in, you can either write custom support + for the new NPRuntime interface or embed an HTML control and embed the player within + the HTML control. If you embed an HTML control, you can communicate with the + player through a JavaScript interface to the native container application.

+ +

Note: For local content running in a browser, calls to the + ExternalInterface.call() method are permitted only if the SWF file and the + containing web page (if there is one) are in the local-trusted security sandbox. Also, you can + prevent a SWF file from using this method by setting the allowNetworking + parameter of the object and embed tags in the HTML + page that contains the SWF content. For more information, see the Flash Player Developer Center Topic: + Security.

+ + +

Note for Flash Player applications: In Flash Player 10 and Flash Player 9 Update 5, some web browsers restrict this method + if a pop-up blocker is enabled. In this scenario, you can only call this method successfully + in response to a user event (for example, in an event handler for a mouse click or keypress event).

+ +
The following example shows how you can use the ExternalInterface class (flash.external.ExternalInterface) to send a string from Flash Player + to the HTML container where it is displayed using the JavaScript alert() function. + Example provided by + ActionScriptExamples.com. + +// +// Requires: +// - A Flash Professional Label component on the Stage with an instance name of "lbl". +// - A Flash Professional Button component on the Stage with an instance name of "button". +// +var xmlResponse:String = "<invoke name=\"isReady\" returntype=\"xml\"><arguments><number>1</number><number>" + stage.stageWidth + "</number><number>" + stage.stageHeight + "</number></arguments></invoke>"; + +lbl.text = "ExternalInterface.available: " + ExternalInterface.available; +lbl.width = 200; +button.enabled = ExternalInterface.available; +button.addEventListener(MouseEvent.CLICK, button_click); + +function button_click(evt:MouseEvent):void { + ExternalInterface.call("alert", xmlResponse); +} +
marshallExceptions + Indicates whether the external interface should attempt to pass ActionScript exceptions to the + current browser and JavaScript exceptions to the player.falseBooleanPasses exceptions between AS and JS. + + Indicates whether the external interface should attempt to pass ActionScript exceptions to the + current browser and JavaScript exceptions to the player. You must explicitly set this property + to true to catch JavaScript exceptions in ActionScript and to catch ActionScript exceptions + in JavaScript. + + The following example creates an ActionScript function and registers it with + the containing browser by using the addCallback() method. The new function throws + an exception so that JavaScript code running in the browser can catch it. This example also + contains a try..catch statement to catch any exceptions thrown by the browser + when the throwit() function is called. + + +package +{ + import flash.external.* + import flash.net.*; + import flash.display.*; + import flash.system.System; + public class ext_test extends Sprite { + function ext_test():void { + ExternalInterface.marshallExceptions = true; + ExternalInterface.addCallback("g", g); + + try { + ExternalInterface.call("throwit"); + } catch(e:Error) { + trace(e) + } + } + function g() { throw new Error("exception from actionscript!!!!") } + } +} +addCallBack()try..catch..finally statementavailable + Indicates whether this player is in a container that offers an external interface.BooleanIndicates if the player is in a container that offers an external interface. + + + Indicates whether this player is in a container that offers an external interface. + If the external interface is available, this property is true; otherwise, + it is false. + +

Note: When using the External API with HTML, always check that the HTML + has finished loading before you attempt to call any JavaScript methods.

+ +
The following example uses the available property to + determine whether the player is in a container that offers an external interface. + + package { + import flash.text.TextField; + import flash.display.MovieClip; + import flash.external.ExternalInterface; + + public class extint_test extends MovieClip { + public function extint_test() { + var isAvailable:Boolean = ExternalInterface.available; + var availTxt:TextField = new TextField(); + availTxt.text = isAvailable.toString(); + addChild(availTxt); + } + } + } + + + +
objectID + Returns the id attribute of the object tag in Internet Explorer, + or the name attribute of the embed tag in Netscape.String + Returns the id attribute of the object tag in Internet Explorer, + or the name attribute of the embed tag in Netscape. +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.filesystem.xml b/language-server/playerglobal_docs/flash.filesystem.xml new file mode 100644 index 0000000..a8edb34 --- /dev/null +++ b/language-server/playerglobal_docs/flash.filesystem.xml @@ -0,0 +1,2602 @@ +flash.filesystemFileStream + + A FileStream object is used to read and write files.flash.utils:IDataInputflash.utils:IDataOutputflash.events:EventDispatcher + A FileStream object is used to read and write files. Files can be opened synchronously by calling the + open() method or asynchronously by calling the openAsync() method. + +

The advantage of opening files asynchronously is that other code can execute while Adobe AIR + runs read and write processes in the background. When opened asynchronously, progress events + are dispatched as operations proceed.

+ +

A File object that is opened synchronously behaves much like a ByteArray object; a file opened asynchronously behaves + much like a Socket or URLStream object. When a File object is opened synchronously, the caller pauses while + the requested data is read from or written to the underlying file. When opened asynchronously, any data + written to the stream is immediately buffered and later written to the file.

+ +

Whether reading from a file synchronously or asynchronously, the actual read methods are synchronous. + In both cases they read from data that is currently "available." The difference is that when reading + synchronously all of the data is available at all times, and when reading asynchronously data becomes + available gradually as the data streams into a read buffer. Either way, the data that can be synchronously + read at the current moment is represented by the bytesAvailable property.

+ +

An application that is processing asynchronous input typically registers for progress events + and consumes the data as it becomes available by calling read methods. Alternatively, an application can + simply wait until all of the data is available by registering for the complete event and + processing the entire data set when the complete event is dispatched.

+ +
complete + Signals that the end of the stream has been reached.flash.events.Event.COMPLETEflash.events.Event + Signals that the end of the stream has been reached. + + positionoutputProgress + Signals that buffered data has been written to the file.flash.events.OutputProgressEvent.OUTPUT_PROGRESSflash.events.OutputProgressEvent + Signals that buffered data has been written to the file. + + progress + Signals the availability of new data on the stream.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Signals the availability of new data on the stream. + + ioError + Indicates that an error occurred during an asynchronous file I/O operation.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Indicates that an error occurred during an asynchronous file I/O operation. + + close + Indicates that the stream has been + closed by an explicit call to the close() method.flash.events.Event.CLOSEflash.events.Event + Indicates that the stream has been + closed by an explicit call to the close() method. + + close()FileStream + Creates a FileStream object. + Creates a FileStream object. + Use the open() + or openAsync() method to open a file. + + open()openAsync()close + Closes the FileStream object. + Closes the FileStream object. + +

You cannot read or write any data after you call the close() method. If the file + was opened asynchronously (the FileStream object used the openAsync() method to open the file), + calling the close() method causes the object to dispatch the close event.

+ +

Closing the application automatically closes all files associated with FileStream objects in the application. + However, it is best to register for a closed event on all FileStream objects opened asynchronously + that have pending data to write, before closing the application (to ensure that data is written).

+ +

You can reuse the FileStream object by calling the open() or the openAsync() + method. This closes any file associated with the FileStream object, but the object does not dispatch the + close event.

+ +

For a FileStream object opened asynchronously (by using the openAsync() method), + even if you call the close() event for a FileStream object and delete properties and variables that + reference the object, the FileStream object is not garbage collected as long as there are pending operations and + event handlers are registered for their completion. In particular, an otherwise unreferenced FileStream object + persists as long as any of the following are still possible:

+ +
  • For file reading operations, the end of the file has not been reached (and the complete + event has not been dispatched).
  • Output data is still available to written, and output-related events (such as the outputProgress + event or the ioError event) have registered event listeners.
+ +
The following code opens a FileStream object asynchronously and writes a text file named + test.txt to the Apollo Test subdirectory of the user's documents directory. A call to the close() + method of the FileStream object closes the file when the data is written. + +import flash.filesystem.*; +import flash.events.Event; + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.openAsync(file, FileMode.WRITE); +fileStream.writeUTFBytes("Hello"); +fileStream.addEventListener(Event.CLOSE, fileClosed); +fileStream.close(); + +function fileClosed(event:Event):void { + trace("closed"); +} + The following code opens a FileStream object synchronously and writes a text file named + test.txt to the Apollo Test subdirectory of the user's documents directory. A call to the close() + method of the FileStream object closes the file when the data is written. + +import flash.filesystem.*; + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.open(file, FileMode.WRITE); +fileStream.writeUTF("Hello"); +fileStream.close(); +
open()close eventcloseflash.events:EventThe file, which was opened asynchronously, is closed. + + The file, which was opened asynchronously, is closed.
openAsync + Opens the FileStream object asynchronously, pointing to the file specified by the file parameter.The file location is in the application directory, and the fileMode parameter + is set to "append", "update", or "write" mode. + + SecurityErrorSecurityErrorfileflash.filesystem:FileThe File object specifying the file to open. + + fileModeStringA string from the FileMode class that defines the capabilities of the FileStream, such as + the ability to read from or write to the file. + + + Opens the FileStream object asynchronously, pointing to the file specified by the file parameter. + +

If the FileStream object is already open, calling the method closes the file before opening + and no further events (including close) are delivered for the previously opened file.

+ +

If the fileMode parameter is set to FileMode.READ or + FileMode.UPDATE, AIR reads data into the input buffer as soon as the file is opened, + and progress and open events are dispatched as the data is read to + the input buffer.

+ +

On systems that support file locking, a file opened in "write" or "update" mode (FileMode.WRITE + or FileMode.UPDATE) is not readable until it is closed.

+ +

Once you are done performing operations on the file, call the close() method of the FileStream + object. Some operating systems limit the number of concurrently open files.

+ +`
The following code shows how to asynchronously open a test.txt file in the + Apollo Test subdirectory of the user's documents directory and then read the file into a string, + using the system character set as the text encoding. + +import flash.filesystem.*; +import flash.events.Event; + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.addEventListener(Event.COMPLETE, fileCompleteHandler) +fileStream.openAsync(file, FileMode.READ); + +function fileCompleteHandler(event:Event):void { + var str:String = fileStream.readMultiByte(fileStream.bytesAvailable, File.systemCharset); + trace(str); + fileStream.close(); +} +
close()complete eventioError eventprogress eventFileModeioErrorflash.events:IOErrorEventThe file does not exist; you do not have adequate permissions to + open the file; you are opening a file for read access, and you do not have read permissions; + or you are opening a file for write access, and you do not have write permissions. + + The file does not exist; you do not have adequate permissions to + open the file; you are opening a file for read access, and you do not have read permissions; + or you are opening a file for write access, and you do not have write permissions.progressflash.events:ProgressEventDispatched as data is read to the input buffer. (The file must be opened + with the fileMode parameter set to FileMode.READ or + FileMode.UPDATE.) + + Dispatched as data is read to the input buffer.completeflash.events:EventThe file data has been read to the input buffer. (The file must be opened with + the fileMode parameter set to FileMode.READ or + FileMode.UPDATE.) + + The file data has been read to the input buffer.
open + Opens the FileStream object synchronously, pointing to the file specified by the file parameter.The file does not exist; you do not have adequate permissions to + open the file; you are opening a file for read access, and you do not have read permissions; + or you are opening a file for write access, and you do not have write permissions. + + IOErrorflash.errors:IOErrorThe file location is in the application directory, and the fileMode + parameter is set to "append", "update", or "write" mode. + + SecurityErrorSecurityErrorfileflash.filesystem:FileThe File object specifying the file to open. + + fileModeStringA string from the FileMode class that defines the capabilities of the FileStream, such as + the ability to read from or write to the file. + + + Opens the FileStream object synchronously, pointing to the file specified by the file parameter. + +

If the FileStream object is already open, calling the method closes the file before opening + and no further events (including close) are delivered for the previously opened file.

+ +

On systems that support file locking, a file opened in "write" or "update" mode (FileMode.WRITE + or FileMode.UPDATE) is not readable until it is closed.

+ +

Once you are done performing operations on the file, call the close() method of the FileStream + object. Some operating systems limit the number of concurrently open files.

+ +
The following code shows how to synchronously open a test.txt file in the + Apollo Test subdirectory of the user's documents directory and then read the file into a string, + using the system character set as the text encoding. + +import flash.filesystem.*; + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.open(file, FileMode.READ); +var str:String = fileStream.readMultiByte(file.size, File.systemCharset); +trace(str); +fileStream.close(); +
close()FileFileMode
readBoolean + + Reads a Boolean value from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorA Boolean value, true if the byte is nonzero, + false otherwise. + Boolean + + Reads a Boolean value from the file stream, byte stream, or byte array. A single byte is read + and true is returned if the byte is nonzero, + false otherwise. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readByte + + Reads a signed byte from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range -128 to 127. + int + + Reads a signed byte from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readBytes + + Reads the number of data bytes, specified by the length parameter, + from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorbytesflash.utils:ByteArrayThe ByteArray object to read + data into. + offsetuint0The offset into the bytes parameter at which data + read should begin. + lengthuint0The number of bytes to read. The default value + of 0 causes all available data to be read. + + + Reads the number of data bytes, specified by the length parameter, + from the file stream, byte stream, or byte array. The bytes are read into the + ByteArray objected specified by the bytes parameter, starting at + the position specified by offset. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readDouble + + Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorAn IEEE 754 double-precision floating point number. + Number + + Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readFloat + + Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorAn IEEE 754 single-precision floating point number. + Number + + Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readInt + + Reads a signed 32-bit integer from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range -2147483648 to 2147483647. + int + + Reads a signed 32-bit integer from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readMultiByte + + Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the + specified character set.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorUTF-8 encoded string. + StringlengthuintThe number of bytes from the byte stream to read. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift-jis", "cn-gb", + "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + +

Note: If the value for the charSet parameter is not recognized by the current + system, then Adobe® Flash® Player or + Adobe® AIR® uses the system's default + code page as the character set. For example, a value for the charSet parameter, as in + myTest.readMultiByte(22, "iso-8859-01"), that uses 01 instead of + 1 might work on your development system, but not on another system. On the other + system, Flash Player or the AIR runtime will use the system's + default code page.

+ +
+ + Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the + specified character set. + + +
File.systemCharsetioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.
readObject + + Reads an object from the file stream, byte stream, or byte array, encoded in AMF + serialized format.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe deserialized object + + + + Reads an object from the file stream, byte stream, or byte array, encoded in AMF + serialized format. + flash.net.registerClassAlias()ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readShort + + Reads a signed 16-bit integer from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range -32768 to 32767. + int + + Reads a signed 16-bit integer from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readUTFBytes + + Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters of the specified length. + StringlengthuintThe number of bytes to read. + + + Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readUTF + + Reads a UTF-8 string from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters. + + String + + Reads a UTF-8 string from the file stream, byte stream, or byte array. The string + is assumed to be prefixed with an unsigned short indicating + the length in bytes. + +

This method is similar to the readUTF() + method in the Java® IDataInput interface.

+
ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.
readUnsignedByte + + Reads an unsigned byte from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 255. + uint + + Reads an unsigned byte from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readUnsignedInt + + Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 4294967295. + uint + + Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.readUnsignedShort + + Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + read capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be read (for example, because the file is missing). + + IOErrorflash.errors:IOErrorThe position specfied for reading data exceeds the number of bytes available + (specified by the bytesAvailable property). + + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 65535. + uint + + Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array. + ioErrorflash.events:IOErrorEventThe file cannot be read or the file is not open. This event is dispatched + only for files opened for asynchronous operations (by using the openAsync() method). + + The file cannot be read or the file is not open.truncate + Truncates the file at the position specified by the position property of the FileStream + object.The file is not open for writing. + + IllegalOperationErrorflash.errors:IllegalOperationError + Truncates the file at the position specified by the position property of the FileStream + object. + +

Bytes from the position specified by the position property to the end of the file + are deleted. The file must be open for writing.

+ +
The following code synchronously opens a test.txt file in the Apollo Test subdirectory of + the user's documents directory and then trims the file to 100 characters in length if it is longer than + 100 characters. + +import flash.filesystem.*; + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.open(file, FileMode.UPDATE); +if (file.size > 100) { + fileStream.position = 100; + fileStream.truncate(); +} +fileStream.close(); + The following code asynchronously opens a test.txt file in the Apollo Test subdirectory + of the user's documents directory, and then trims the file to 100 characters in length if it is longer than 100 + characters. + +var file:File = File.documentsDirectory; +file = file.resolvePath("Apollo Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.openAsync(file, FileMode.UPDATE); +trace("start", file.size) +if (file.size > 100) { + fileStream.position = 100; + fileStream.truncate(); +} +fileStream.addEventListener(Event.CLOSE, fileClosed); +fileStream.close(); +function fileClosed(event:Event):void { + trace("closed", file.size); +} +
position
writeBoolean + + Writes a Boolean value.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueBooleanA Boolean value determining which byte is written. If the parameter is true, + 1 is written; if false, 0 is written. + + + + Writes a Boolean value. A single byte is written according to the value parameter, + either 1 if true or 0 if false. + + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeByte + + Writes a byte.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueintA byte value as an integer. + + + + Writes a byte. + The low 8 bits of the + parameter are used; the high 24 bits are ignored. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeBytes + + Writes a sequence of bytes from the + specified byte array, bytes, + starting at the byte specified by offset + (using a zero-based index) + with a length specified by length, + into the file stream, byte stream, or byte array.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorbytesflash.utils:ByteArrayThe byte array to write. + offsetuint0A zero-based index specifying the position into the array to begin writing. + lengthuint0An unsigned integer specifying how far into the buffer to write. + + + + Writes a sequence of bytes from the + specified byte array, bytes, + starting at the byte specified by offset + (using a zero-based index) + with a length specified by length, + into the file stream, byte stream, or byte array. + +

If the length parameter is omitted, the default + length of 0 is used and the entire buffer starting at + offset is written. + If the offset parameter is also omitted, the entire buffer is + written.

+ +

If the offset or length parameter + is out of range, they are clamped to the beginning and end + of the bytes array.

+
ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).
writeDouble + + Writes an IEEE 754 double-precision (64-bit) floating point number.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueNumberA double-precision (64-bit) floating point number. + + + + Writes an IEEE 754 double-precision (64-bit) floating point number. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeFloat + + Writes an IEEE 754 single-precision (32-bit) floating point number.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueNumberA single-precision (32-bit) floating point number. + + + + Writes an IEEE 754 single-precision (32-bit) floating point number. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeInt + + Writes a 32-bit signed integer.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueintA byte value as a signed integer. + + + + Writes a 32-bit signed integer. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeMultiByte + + Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueStringThe string value to be written. + charSetStringThe string denoting the character set to use. Possible character set strings + include "shift-jis", "cn-gb", "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + + + Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set. + + File.systemCharsetioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeObject + + Writes an object to the file stream, byte stream, or byte array, in AMF serialized + format.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorobjectThe object to be serialized. + + + + Writes an object to the file stream, byte stream, or byte array, in AMF serialized + format. + flash.net.registerClassAlias()ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeShort + + Writes a 16-bit integer.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueintA byte value as an integer. + + + + Writes a 16-bit integer. The low 16 bits of the parameter are used; + the high 16 bits are ignored. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeUTFBytes + + Writes a UTF-8 string.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueStringThe string value to be written. + + + + Writes a UTF-8 string. Similar to writeUTF(), + but does not prefix the string with a 16-bit length word. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeUTF + + Writes a UTF-8 string to the file stream, byte stream, or byte array.If the length of the string is larger than + 65535. + + RangeErrorRangeErrorThe file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueStringThe string value to be written. + + + + Writes a UTF-8 string to the file stream, byte stream, or byte array. The length of the UTF-8 string in bytes + is written first, as a 16-bit integer, followed by the bytes representing the + characters of the string. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).writeUnsignedInt + + Writes a 32-bit unsigned integer.The file has not been opened; the file has been opened, but it was not opened with + write capabilities; or for a file that has been opened for synchronous operations (by using the + open() method), the file cannot be written (for example, because the file is missing). + + IOErrorflash.errors:IOErrorvalueuintA byte value as an unsigned integer. + + + + Writes a 32-bit unsigned integer. + ioErrorflash.events:IOErrorEventYou cannot write to the file (for example, because the file is missing). + This event is dispatched only for files that have been opened for asynchronous operations (by using the + openAsync() method). + + You cannot write to the file (for example, because the file is missing).bytesAvailable + + Returns the number of bytes of data available for reading + in the input buffer.uint + + Returns the number of bytes of data available for reading + in the input buffer. + User code must call bytesAvailable to ensure + that sufficient data is available before trying to read + it with one of the read methods. + endian + + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant + from the Endian class.String + + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant + from the Endian class. + + objectEncoding + Specifies whether the AMF3 or AMF0 format is used when writing or reading binary data by using the + readObject() or writeObject() method.uint + Specifies whether the AMF3 or AMF0 format is used when writing or reading binary data by using the + readObject() or writeObject() method. + +

The value is a constant from the ObjectEncoding class. By default, the AMF3 format is used.

+ +
ObjectEncodingreadObject()writeObject()
position + The current position in the file.Number + The current position in the file. + +

This value is modified in any of the following ways:

+ +
  • When you set the property explicitly
  • When reading from the FileStream object (by using one of the read methods)
  • When writing to the FileStream object
+ +

The position is defined as a Number (instead of uint) in order to support files larger + than 232 bytes in length. The value of this property is always + a whole number less than 253. If you set this value to a number with a + fractional component, the value is rounded down to the nearest integer.

+ +

When reading a file asyncronously, if you set the position property, + the application begins filling the read buffer with the data starting at the specified + position, and the bytesAvailable property may be set to 0. Wait for a complete + event before using a read method to read data; or wait for a progress event + and check the bytesAvailable property before using a read method.

+ +
The following code shows how a position property of the FileStream object + is updated as the application reads data from a file. + +import flash.fileSystem.*; +import flash.utils.ByteArray; +import flash.events.Event; + +var sourceFile:File = File.documentsDirectory.resolvePath("Apollo Test/test.txt"); +var stream:FileStream = new FileStream(); +stream.addEventListener(Event.COMPLETE, readBytes); +stream.openAsync(sourceFile, FileMode.READ); + +function readBytes(e:Event):void { + var bytes:ByteArray = new ByteArray(); + trace("position 0:", stream.position); // 0 + bytes[0] = stream.readByte(); + trace("position 1:", stream.position); // 1 + fileStream.readBytes(bytes, stream.position, 4); + trace("position 2:", stream.position); // 5 + stream.close(); +} +
readAhead + The minimum amount of data to read from disk when reading files asynchronously.Number + The minimum amount of data to read from disk when reading files asynchronously. + +

This property specifies how much data an asynchronous stream attempts to read + beyond the current position. Data is read in blocks based on the file system page size. + Thus if you set readAhead to 9,000 on a computer system with an 8KB (8192 byte) + page size, the runtime reads ahead 2 blocks, or 16384 bytes at a time. + The default value of this property is infinity: by default + a file that is opened to read asynchronously reads as far as the end of the file.

+ +

Reading data from the read buffer does not change the value of the readAhead + property. When you read data from the buffer, new data is read in to refill the read buffer. +

+ +

The readAhead property has no effect on a file that is opened synchronously.

+ +

As data is read in asynchronously, the FileStream object dispatches progress events. In the + event handler method for the progress event, check to see that the required number of bytes + is available (by checking the bytesAvailable property), and then read the data from the + read buffer by using a read method.

+ +
The following code shows how to use the readAhead property to limit + the amount of data read into a file to 100 bytes: + +import flash.filesystem.*; + +var file:File = File.desktopDirectory.resolvePath("test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.readAhead = 100; +fileStream.addEventListener(ProgressEvent.PROGRESS, readProgressHandler) +fileStream.openAsync(file, FileMode.READ); +var results:ByteArray; + +function readProgressHandler(event:ProgressEvent):void { + if (fileStream.bytesAvailable >= 100) { + fileStream.readBytes(results, 0, 100); + } +} +
FileMode + The FileMode class defines string constants used in the fileMode parameter of + the open() and openAsync() methods of the FileStream class.Object + The FileMode class defines string constants used in the fileMode parameter of + the open() and openAsync() methods of the FileStream class. + The fileMode parameter of these methods determines the capabilities available + to the FileStream object once the file is opened. + +

The following capabilities are available, in various combinations, based on the fileMode + parameter value specified in the open method:

+ +
  • Reading—The FileStream object can read data from the file.
  • Writing—The FileStream object can write data to the file.
  • Creating—The FileStream object creates a nonexistent file upon opening.
  • Truncate upon opening—Data in the file is deleted upon opening (before any data is written).
  • Append written data—Data is always written to the end of the file (when any write method is called).
+ +

The following table shows the capabilities that each constant in the FileMode class provides when applied + as the fileMode parameter of an open method of a FileStream object:

+ + FileMode constantReadingWritingCreatingTruncate upon openingAppend written dataREAD WRITE APPEND UPDATE + +
FileStream.open()FileStream.openAsync()APPEND + Used for a file to be opened in write mode, with all written data appended to the end of the file.appendString + Used for a file to be opened in write mode, with all written data appended to the end of the file. + Upon opening, any nonexistent file is created. + + READ + Used for a file to be opened in read-only mode.readString + Used for a file to be opened in read-only mode. The file must exist (missing files are not created). + + UPDATE + Used for a file to be opened in read/write mode.updateString + Used for a file to be opened in read/write mode. Upon opening, any nonexistent file is created. + + WRITE + Used for a file to be opened in write-only mode.writeString + Used for a file to be opened in write-only mode. Upon opening, any nonexistent file is created, and any + existing file is truncated (its data is deleted). + +
StorageVolumeInfo + The StorageVolumeInfo object dispatches a StorageVolumeChangeEvent object when a + storage volume is mounted or unmounted.flash.events:EventDispatcher + The StorageVolumeInfo object dispatches a StorageVolumeChangeEvent object when a + storage volume is mounted or unmounted. The StorageVolume.storageVolume + static property references the singleton StorageVolumeInfo object, which dispatches + the events. The StorageVolumeInfo class also defines a getStorageVolumes + method for listing currently mounted storage volumes. + +

AIR profile support: This feature is supported + on all desktop operating systems, but it is not supported on all AIR for TV devices. + It is also not supported on mobile devices. You can test + for support at run time using the StorageVolumeInfo.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

On modern Linux distributions, the StorageVolumeInfo object only dispatches storageVolumeMount and + storageVolumeUnmount events for physical devices and network drives mounted at particular locations.

+ +
storageVolumeUnmount + Dispatched when a storage volume has been unmounted.flash.events.StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNTflash.events.StorageVolumeChangeEvent + Dispatched when a storage volume has been unmounted. + +

On modern Linux distributions, the StorageVolumeInfo object only dispatches storageVolumeMount and + storageVolumeUnmount events for physical devices and network drives mounted at particular locations.

+ +
storageVolumeMount + Dispatched when a storage volume has been mounted.flash.events.StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNTflash.events.StorageVolumeChangeEvent + Dispatched when a storage volume has been mounted. + +

On modern Linux distributions, the StorageVolumeInfo object only dispatches storageVolumeMount and + storageVolumeUnmount events for physical devices and network drives mounted at particular locations.

+ +
getStorageVolumes + Returns vector of StorageVolume objects corresponding to the currently mounted storage volumes. + Returns vector of StorageVolume objects corresponding to the currently mounted storage volumes. + +

On modern Linux distributions, this method returns objects corresponding to physical devices + and network drives mounted at particular locations.

+ +
The following code lists the native path for the root directory of each mounted storage volume: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); +for (var i:int = 0; i < volumes.length; i++) +{ + trace(volumes[i].rootDirectory.nativePath); +} +
flash.filesystem.StorageVolume
isSupported + The isSupported property is set to true if the + StorageVolumeInfo class is supported on the current platform, otherwise it is + set to false.Boolean + The isSupported property is set to true if the + StorageVolumeInfo class is supported on the current platform, otherwise it is + set to false. + + storageVolumeInfo + The singleton instance of the StorageVolumeInfo object.flash.filesystem:StorageVolumeInfo + The singleton instance of the StorageVolumeInfo object. Register event listeners + on this object for the storageVolumeMount and storageVolumeUnmount + events. + +
File + A File object represents a path to a file or directory.flash.net:FileReference + A File object represents a path to a file or directory. This can be an existing file or directory, or it can be + one that does not yet exist; for instance, it can represent the path to a file or directory that you plan to create. + +

The File class has a number of properties and methods for getting information about the file system and + for performing operations, such as copying files and directories.

+ +

You can use File objects along with the FileStream class to read and write files.

+ +

The File class extends the FileReference class. The FileReference class, which is available in Flash® Player as + well as Adobe® AIR®, represents a pointer to a file, but the File class adds properties and methods that are not + exposed in Flash Player (in a SWF running in a browser), due to security considerations.

+ +

The File class includes static properties that let you reference commonly used directory locations. These static properties include:

+ +
  • File.applicationStorageDirectory—a storage directory unique to each installed AIR application
  • File.applicationDirectory—the read-only directory where the application is installed (along with any installed assets)
  • File.desktopDirectory—the user's desktop directory
  • File.documentsDirectory—the user's documents directory
  • File.userDirectory—the user directory
+ +

These properties have meaningful values on different operating systems. For example, Mac OS, Linux, and Windows each have + different native paths to the user's desktop directory. However, the File.desktopDirectory property points to the + correct desktop directory path on each of these platforms. To write applications that work well across platforms, + use these properties as the basis for referencing other files used by the application. Then use the resolvePath() + method to refine the path. For example, this code points to the preferences.xml file in the application storage directory:

+ + var prefsFile:File = File.applicationStorageDirectory; + prefsFile = prefsFile.resolvePath("preferences.xml"); + + + +

If you use a literal native path in referencing a file, it will only work on one platform. + For example, the following File object would only work on Windows:

+ + new File("C:\Documents and Settings\joe\My Documents\test.txt") + + +

The application storage directory is particularly useful. It gives an application-specific storage + directory for the AIR application. It is defined by the File.applicationStorageDirectory + property.

+ +

Do not add or remove content from the application directory (where the AIR application is installed). + Doing so can break an AIR application and invalidate the application signature. AIR does not let you write to + the application directory by default, because the directory is not writable to all user accounts on all operating systems. + Use the application storage directory to write internal application files. Use the documents directory to write files + that a user expects to use outside your application, such as edited pictures or text files.

+ + +
FileStreamdirectoryListing + Dispatched when a directory list is available as a result of a call to the getDirectoryListingAsync() + method.flash.events.FileListEvent.DIRECTORY_LISTINGflash.events.FileListEvent + Dispatched when a directory list is available as a result of a call to the getDirectoryListingAsync() + method. + + File.getDirectoryListingAsync()selectMultiple + Dispatched when the user selects files from the dialog box opened by a call to the + browseForOpenMultiple() method.flash.events.FileListEvent.SELECT_MULTIPLEflash.events.FileListEvent + Dispatched when the user selects files from the dialog box opened by a call to the + browseForOpenMultiple() method. + + + browseForOpenMultiple()select + Dispatched when the user selects a file or directory from a file- or directory-browsing dialog box.flash.events.Event.SELECTflash.events.Event + Dispatched when the user selects a file or directory from a file- or directory-browsing dialog box. + + + securityError + Dispatched when an operation violates a security constraint.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched when an operation violates a security constraint. + + + ioError + Dispatched when an error occurs during an asynchronous file operation.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an error occurs during an asynchronous file operation. + + complete + Dispatched when an asynchronous operation is complete.flash.events.Event.COMPLETEflash.events.Event + Dispatched when an asynchronous operation is complete. + + cancel + Dispatched when a pending asynchronous operation is canceled.flash.events.Event.CANCELflash.events.Event + Dispatched when a pending asynchronous operation is canceled. + + File + The constructor function for the File class.The syntax of the path parameter is invalid. + + ArgumentErrorArgumentErrorpathStringnullThe path to the file. You can specify the path by using either a URL or + native path (platform-specific) notation. + +

If you specify a URL, you can use any of the following + URL schemes: file, app, or + app-storage. The following are valid values for the path + parameter using URL notation:

+ +
  • "app:/DesktopPathTest.xml"
  • "app-storage:/preferences.xml"
  • "file:///C:/Documents%20and%20Settings/bob/Desktop" (the desktop on Bob's Windows computer)
  • "file:///Users/bob/Desktop" (the desktop on Bob's Mac computer)
+ +

The app and app-storage URL schemes + are useful because they can point to a valid file on all file systems. However, + in the other two examples, which use the file URL scheme to point to the + user's desktop directory, it would be better to pass no path argument + to the File() constructor and then assign File.desktopDirectory + to the File object, as a way to access the desktop directory that is both platform- and + user-independent.

+ +

If you specify a native path, on Windows you can use either the backslash character or + the forward slash character as the path separator in this argument; on Mac OS and Linux, use the + forward slash. The following are valid values for the path parameter using + native path notation:

+ +
  • "C:/Documents and Settings/bob/Desktop"
  • "/Users/bob/Desktop"
+ +

However, for these two examples, you should pass no path argument + to the File() constructor and then assign File.desktopDirectory + to the File object, as a way to access the desktop directory that is both platform- and + user-independent.

+ +
+ The constructor function for the File class. + +

If you pass a path argument, the + File object points to the specified path, and the nativePath property and + and url property are set to reflect that path.

+ + +

Although you can pass a path argument to specify a file path, consider + whether doing so may result in platform-specific code. For example, a native path such as + "C:\\Documents and Settings\\bob\\Desktop" or a URL such as + "file:///C:/Documents%20and%20Settings/bob/Desktop" is only valid on Windows. + It is far better to use the following static properties, which represent commonly used directories, + and which are valid on all platforms:

+ +
  • File.applicationDirectory
  • File.applicationStorageDirectory
  • File.desktopDirectory
  • File.documentsDirectory
  • File.userDirectory
+ +

You can then use the resolvePath() method to get a path relative to these directories. + For example, the following code sets up a File object to point to the settings.xml file in the application + storage directory:

+ + var file:File = File.applicationStorageDirectory.resolvePath("settings.xml"); + + + +

Important: If you pass a URL string in the path parameter, the URL is decoded to resolve the file path. + For example, the statement, new File("file:///c:/test/demo%20file%201%2e0.txt") creates a File object + with the native path, "c:\test\demo file 1.0.txt". (A URL uses the file:, app:, or app-storage: scheme prefixes.) + However, if the valid URL prefixes are omitted, the path string is treated like a native path and no decoding takes place. + You must take this behavior into consideration when validating paths derived from potentially untrusted sources. + If you simply validate the input string, URL decoding may allow an attacker to bypass your validation checks. + Always validate the final path of the instantiated File object:

+ + + var file:File = new File( taintedString ); + validate( file.nativePath ); //where validate() is your path validation function + + + +
nativePath
browseForDirectory + Displays a directory chooser dialog box, in which the user can select a directory.A browse operation (browseForOpen(), browseForOpenMultiple(), + browseForSave(), browseForDirectory()) is currently running. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe application does not have the necessary permissions. + + SecurityErrorSecurityErrortitleStringThe string that is displayed in the title bar of the dialog box. + + + Displays a directory chooser dialog box, in which the user can select a directory. + When the user selects the directory, the select event is dispatched. + The target property of the select event is the + File object pointing to the selected directory. + +

The directory chooser dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +

Note: On Android devices, browseForDirectory() is not supported. + The File object dispatches a cancel event immediately.

+ +
The following code uses the File.browseForDirectory() method to + let the user select a directory. When the directory is selected, the code lists the contents of + the selected directory in the trace() output. + +import flash.filesystem.File; +import flash.events.Event; + +var directory:File = File.documentsDirectory; + +try +{ + directory.browseForDirectory("Select Directory"); + directory.addEventListener(Event.SELECT, directorySelected); +} +catch (error:Error) +{ + trace("Failed:", error.message); +} + +function directorySelected(event:Event):void +{ + directory = event.target as File; + var files:Array = directory.getDirectoryListing(); + for(var i:uint = 0; i < files.length; i++) + { + trace(files[i].name); + } +} +
browseForOpen()browseForSave()selectflash.net.FileFiltercancelflash.events:EventDispatched when the user clicks the Cancel button in the Open File dialog box. + + Dispatched when the user clicks the Cancel button in the Open File dialog box.selectflash.events:EventDispatched when the user selects a directory and closes the directory chooser dialog box. + + Dispatched when the user selects a directory and closes the directory chooser dialog box.ioErrorflash.events:IOErrorEventThe browse operation is unsupported on this platform. + + The browse operation is unsupported on this platform.
browseForOpenMultiple + Displays the Open File dialog box, in which the user can select one or more files to open.A browse operation (browseForOpen(), browseForOpenMultiple(), + browseForSave(), browseForDirectory()) is currently running. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe application does not have the necessary permissions. + + SecurityErrorSecurityErrortitleStringThe string that is displayed in the title bar of the dialog box. + + typeFilterArraynullAn array of FileFilter instances used to filter the files + that are displayed in the dialog box. If you omit this parameter, all files are + displayed. For more information, see the FileFilter class. + + + Displays the Open File dialog box, in which the user can select one or more files to open. + +

When the user selects the files, the selectMultiple event is dispatched. + The target property of the select event is this + File object. Unlike browseForOpen(), with the browseForOpenMultiple() + method, this File object is not updated to reference any of the chosen files. + Instead, the resulting selectMultiple event contains an array of the chosen files.

+ +

The Open File dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +

Note: On Android devices, the file dialog title cannot be set. The title + parameter is ignored.

+ +
The following code uses the File.browseForOpenMultiple() method to + let the user choose multiple files. When the files are selected, the code outputs the paths + for the selected files. + +import flash.filesystem.*; +import flash.events.FileListEvent; + +var docsDir:File = File.documentsDirectory; +try +{ + docsDir.browseForOpenMultiple("Select Files"); + docsDir.addEventListener(FileListEvent.SELECT_MULTIPLE, filesSelected); +} +catch (error:Error) +{ + trace("Failed:", error.message); +} + +function filesSelected(event:FileListEvent):void +{ + for (var i:uint = 0; i < event.files.length; i++) + { + trace(event.files[i].nativePath); + } +} +
browseForSave()browseForOpen()browseForDirectory()selectMultipleflash.net.FileFiltercancelflash.events:EventDispatched when the user clicks the Cancel button in the Open File dialog box. + + Dispatched when the user clicks the Cancel button in the Open File dialog box.selectMultipleflash.events:FileListEventDispatched when the user selects files and closes the Open File dialog box. + + Dispatched when the user selects files and closes the Open File dialog box.ioErrorflash.events:IOErrorEventThe browse operation is unsupported on this platform. + + The browse operation is unsupported on this platform.
browseForOpen + Displays the Open File dialog box, in which the user can select a file to open.A browse operation (browseForOpen(), browseForOpenMultiple(), + browseForSave(), browseForDirectory()) is currently running. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe application does not have the necessary permissions. + + SecurityErrorSecurityErrortitleStringThe string that is displayed in the title bar of the dialog box. + + typeFilterArraynullAn array of FileFilter instances used to filter the files + that are displayed in the dialog box. If you omit this parameter, all files are + displayed. For more information, see the FileFilter class. + + + Displays the Open File dialog box, in which the user can select a file to open. + +

When the user selects the file, the select event is dispatched. + The target property of the select event is the + File object pointing to the selected file.

+ +

The Open File dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +

Note: On Android devices, the file dialog title cannot be set. The title + parameter is ignored.

+ +
The following code uses the File.browseForOpen() method to + let the user choose a text file. When the file is selected, the code reads the file data + into a string. + +import flash.filesystem.*; +import flash.events.Event; +import flash.net.FileFilter; + +var fileToOpen:File = new File(); +var txtFilter:FileFilter = new FileFilter("Text", "*.as;*.css;*.html;*.txt;*.xml"); + +try +{ + fileToOpen.browseForOpen("Open", [txtFilter]); + fileToOpen.addEventListener(Event.SELECT, fileSelected); +} +catch (error:Error) +{ + trace("Failed:", error.message); +} + +function fileSelected(event:Event):void +{ + var stream:FileStream = new FileStream(); + stream.open(event.target, FileMode.READ); + var fileData:String = stream.readUTFBytes(stream.bytesAvailable); + trace(fileData); +} +
browseForSave()browseForOpenMultiple()browseForDirectory()selectflash.net.FileFiltercancelflash.events:EventDispatched when the user clicks the Cancel button in the Open File dialog box. + + Dispatched when the user clicks the Cancel button in the Open File dialog box.selectflash.events:EventDispatched when the user selects a file and closes the Open File dialog box. + + Dispatched when the user selects a file and closes the Open File dialog box.ioErrorflash.events:IOErrorEventThe browse operation is unsupported on this platform. + + The browse operation is unsupported on this platform.
browseForSave + Displays the Save File dialog box, in which the user can select a file destination.A browse operation (browseForOpen(), browseForOpenMultiple(), + browseForSave(), browseForDirectory()) is currently running. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe application does not have the necessary permissions. + + SecurityErrorSecurityErrortitleStringThe string that is displayed in the title bar of the dialog box. + + + Displays the Save File dialog box, in which the user can select a file destination. + +

When the user selects the file, the select event is dispatched. + The target property of the select event is the + File object pointing to the selected Save destination.

+ +

The Save File dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +

Note: On Android devices, the file dialog title cannot be set. The title + parameter is ignored.

+ +
The following code uses the File.browseForSave() method to + let the user select a path for saving a file. When the files are selected, the code saves + data to the selected file path. + +import flash.filesystem.*; +import flash.events.Event; + +var docsDir:File = File.documentsDirectory; +try +{ + docsDir.browseForSave("Save As"); + docsDir.addEventListener(Event.SELECT, saveData); +} +catch (error:Error) +{ + trace("Failed:", error.message); +} + +function saveData(event:Event):void +{ + var newFile:File = event.target as File; + var str:String = "Hello."; + if (!newFile.exists) + { + var stream:FileStream = new FileStream(); + stream.open(newFile, FileMode.WRITE); + stream.writeUTFBytes(str); + stream.close(); + } +} +
browseForDirectory()browseForOpen()selectflash.net.FileFiltercancelflash.events:EventDispatched when the user clicks the Cancel button in the Save File dialog box. + + Dispatched when the user clicks the Cancel button in the Save File dialog box.selectflash.events:EventDispatched when the user selects a file and closes the Save File dialog box. + + Dispatched when the user selects a file and closes the Save File dialog box.ioErrorflash.events:IOErrorEventThe browse operation is unsupported on this platform. + + The browse operation is unsupported on this platform.
cancel + Cancels any pending asynchronous operation. + Cancels any pending asynchronous operation. + canonicalize + Canonicalizes the File path. + Canonicalizes the File path. + +

If the File object represents an existing file or directory, canonicalization + adjusts the path so that it matches the case of the actual file or directory name. + If the File object is a symbolic link, canonicalization adjusts the path so that + it matches the file or directory that the link points to, regardless of whether the + file or directory that is pointed to exists. On case sensitive file systems + (such as Linux), when multiple files exist with names differing only in case, + the canonicalize() method adjusts the path to + match the first file found (in an order determined by the file system).

+ +

In addition, canonicalization converts short filenames to long filenames on Windows.

+ +
The following code shows how to use the canonicalize() method to find the + correct capitalization of a directory name. Before running this example, create a directory named AIR Test + on the desktop of your computer. + +import flash.filesystem.*; + +var path:File = File.desktopDirectory.resolvePath("air test"); +trace(path.nativePath); +path.canonicalize(); +trace(path.nativePath); // ...\AIR Test + + The following code shows how to use the canonicalize() method to find the + long name of a Windows directory based on its short name. This example assumes that there is an AIR Test + directory at the root of the C: drive, and that the system has assigned the short name AIR~1 to the directory. + +import flash.filesystem.*; + +var path:File = new File(); +path.nativePath = "C:\\AIR~1"; +path.canonicalize(); +trace(path.nativePath); // C:\AIR Test +
clone + Returns a copy of this File object.flash.filesystem:File + Returns a copy of this File object. Event registrations are not copied. + +

Note: This method does not copy the file itself. It simply makes a + copy of the instance of the ActionScript + File object. To copy a file, use the + copyTo() method.

+ +
copyToAsync + Begins copying the file or directory at the location specified by this File object to + the location specified by the destination parameter.The application does not have the necessary permissions to write to the destination. + + SecurityErrorSecurityErrornewLocationflash.net:FileReferenceThe target location of the new file. Note that this File object specifies + the resulting (copied) file or directory, not the path to the containing directory. + + overwriteBooleanfalseIf false, the copy fails if the file specified by the target + file already exists. If true, the operation overwrites any existing file or directory + of the same name. + + + Begins copying the file or directory at the location specified by this File object to + the location specified by the destination parameter. + +

Upon completion, either a complete event (successful) or an ioError event + (unsuccessful) is dispatched. The copy process creates any required parent directories (if possible).

+ +
The following code shows how to use the copyToAsync() method to copy a file. + Before running this code, be sure to create a test1.txt file in the AIR Test subdirectory of the documents directory on your + computer. The resulting copied file is named test2.txt, and it is also in the AIR Test subdirectory. When you set the + overwrite parameter to true, the operation overwrites any existing test2.txt file. + +import flash.filesystem.File; +import flash.events.Event; + +var sourceFile:File = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("AIR Test/test1.txt"); +var destination:File = File.documentsDirectory; +destination = destination.resolvePath("AIR Test/test2.txt"); + +sourceFile.copyToAsync(destination, true); +sourceFile.addEventListener(Event.COMPLETE, fileCopiedHandler); + +function fileCopiedHandler(event:Event):void { + trace("Done."); +} +
copyTo()moveToAsync()completeflash.events:EventDispatched when the file or directory has been successfully copied. + + Dispatched when the file or directory has been successfully copied.ioErrorflash.events:IOErrorEventThe source does not exist; or the destination exists and overwrite + is false; or the source could not be copied to the target; or the source and destination refer + to the same file or folder and overwrite is set to true. On Windows, you cannot + copy a file that is open or a directory that contains a file that is open. + + The source does not exist; or the destination exists and overwrite + is false; or the source could not be copied to the target; or the source and destination refer + to the same file or folder and overwrite is set to true.
copyTo + Copies the file or directory at the location specified by this File object to + the location specified by the newLocation parameter.The source does not exist; or the destination exists and overwrite is false; + or the source could not be copied to the target; or the source and destination refer to the same file or folder and + overwrite is set to true. On Windows, you cannot copy a file that is open or a directory + that contains a file that is open. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions to write to the destination. + + SecurityErrorSecurityErrornewLocationflash.net:FileReferenceThe target location of the new file. Note that this File object specifies + the resulting (copied) file or directory, not the path to the containing directory. + + overwriteBooleanfalseIf false, the copy fails if the file specified by the target + parameter already exists. If true, the operation overwrites existing file or directory + of the same name. + + + Copies the file or directory at the location specified by this File object to + the location specified by the newLocation parameter. The copy process + creates any required parent directories (if possible). + + The following code shows how to use the copyTo() method to copy a file. + Before running this code, create a test1.txt file in the AIR Test subdirectory of the documents directory on + your computer. The resulting copied file is named test2.txt, and it is also in the AIR Test subdirectory. When + you set the overwrite parameter to true, the operation overwrites any existing test2.txt file. + +import flash.filesystem.File; +import flash.events.Event; + +var sourceFile:FileReference = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("AIR Test/test1.txt"); +var destination:FileReference = File.documentsDirectory; +destination = destination.resolvePath("AIR Test/test2.txt"); + +if (sourceFile.copyTo(destination, true)) { + trace("Done."); +} + The following code shows how to use the copyTo() method to copy a file. + Before running this code, create a test1.txt file in the AIR Test subdirectory of the home directory on your + computer. The resulting copied file is named test2.txt. The try and catch statements + show how to respond to errors. + +import flash.filesystem.File; + +var sourceFile:File = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("AIR Test/test1.txt"); +var destination:File = File.documentsDirectory; +destination = destination.resolvePath("AIR Test/test2.txt"); + +try +{ + sourceFile.copyTo(destination, true); +} +catch (error:Error) +{ + trace("Error:", error.message); +} +copyToAsync()moveTo()createDirectory + Creates the specified directory and any necessary parent directories.The directory did not exist and could not be created. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions. + + SecurityErrorSecurityError + Creates the specified directory and any necessary parent directories. If the + directory already exists, no action is taken. + + The following code moves a file named test.txt on the desktop to the AIR Test + subdirectory of the documents directory. The call to the createDirectory() method + ensures that the AIR Test directory exists before the file is moved. + +import flash.filesystem.*; + +var source:File = File.desktopDirectory.resolvePath("test.txt"); +var target:File = File.documentsDirectory.resolvePath("AIR Test/test.txt"); +var targetParent:File = target.parent; +targetParent.createDirectory(); +source.moveTo(target, true); +createTempDirectory + Returns a reference to a new temporary directory.A File object referencing the new temporary directory. + + flash.filesystem:File + Returns a reference to a new temporary directory. This is a new directory + in the system's temporary directory path. + +

This method lets you identify a new, unique directory, without having to + query the system to see that the directory is new and unique.

+ +

You may want to delete the temporary directory before closing the application, + since on some devices it is not deleted automatically.

+ +
The following code uses the createTempFile() method to obtain a + reference to a new temporary directory. + +import flash.File; + +var temp:File = File.createTempDirectory(); +trace(temp.nativePath); + Each time you run this code, a new (unique) file is created. +
createTempFile()
createTempFile + Returns a reference to a new temporary file.A File object referencing the new temporary file. + + flash.filesystem:File + Returns a reference to a new temporary file. This is a new file + in the system's temporary directory path. + +

This method lets you identify a new, unique file, without having to + query the system to see that the file is new and unique.

+ +

You may want to delete the temporary file before closing the application, + since it is not deleted automatically.

+ +
The following code uses the createTempFile() method to obtain a + reference to a new temporary file. + +import flash.File; + +var temp:File = File.createTempFile(); +trace(temp.nativePath); + Each time you run this code, a new (unique) file is created. +
createTempDirectory()
deleteDirectoryAsync + Deletes the directory asynchronously.The application does not have the necessary permissions to delete the directory. + + SecurityErrorSecurityErrordeleteDirectoryContentsBooleanfalseSpecifies whether or not to delete a directory that contains files or + subdirectories. When false, if the directory contains files or directories, + the File object dispatches an ioError event. + + + Deletes the directory asynchronously. If this File is actually a symbolic link to a directory, + then the link, and not the directory, is removed. + + deleteDirectory()deleteFileAsync()moveToTrashAsync()completeflash.events:EventDispatched when the directory has been deleted successfully. + + Dispatched when the directory has been deleted successfully.ioErrorflash.events:IOErrorEventThe directory does not exist or could not be deleted. On Windows, + you cannot delete a directory that contains a file that is open. + + The directory does not exist or could not be deleted.deleteDirectory + Deletes the directory.The directory does not exist, or the directory could not be deleted. On Windows, + you cannot delete a directory that contains a file that is open. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions to delete the directory. + + SecurityErrorSecurityErrordeleteDirectoryContentsBooleanfalseSpecifies whether or not to delete a directory that contains files or + subdirectories. When false, if the directory contains files or directories, a call to + this method throws an exception. + + + Deletes the directory. If this File is actually a symbolic link to a directory, + then the link, and not the directory, is removed. + + The following code creates an empty directory and then uses the + deleteDirectory() method to delete the directory. + +import flash.filesystem.File; + +var directory:File = File.documentsDirectory.resolvePath("Empty Junk Directory/"); +File.createDirectory(directory); +trace(directory.exists); // true +directory.deleteDirectory(); +trace(directory.exists); // false +deleteDirectoryAsync()deleteFile()moveToTrash()deleteFileAsync + Deletes the file asynchronously.The application does not have the necessary permissions to delete the file. + + SecurityErrorSecurityError + Deletes the file asynchronously. If this File is actually a symbolic link, then the link, + not the target file, is removed. + + deleteDirectoryAsync()deleteFile()moveToTrashAsync()completeflash.events:EventDispatched when the file has been deleted successfully. + + Dispatched when the file has been deleted successfully.ioErrorflash.events:IOErrorEventThe file does not exist or could not be deleted. On Windows, + you cannot delete a file that is currently open. + + The file does not exist or could not be deleted.deleteFile + Deletes the file.The file does not exist or could not to be deleted. On Windows, + you cannot delete a file that is currently open. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions to delete the file. + + SecurityErrorSecurityError + Deletes the file. If this File is actually a symbolic link, then the link, + not the target file, is removed. + + The following code creates a temporary file and then calls the deleteFile() + method to delete it. + +import flash.filesystem.*; + +var file:File = File.createTempFile(); +trace(file.exists); // true +file.deleteFile(); +trace(file.exists); // false +deleteDirectory()deleteFileAsync()moveToTrash()getDirectoryListingAsync + Asynchronously retrieves an array of File objects corresponding to the contents of the directory represented + by this File object. + Asynchronously retrieves an array of File objects corresponding to the contents of the directory represented + by this File object. + + The following code shows how to use the getDirectoryListingAsync() method to + enumerate the contents of the user directory. + +import flash.filesystem.File; +import flash.events.FileListEvent; + +var directory:File = File.userDirectory; +directory.getDirectoryListingAsync(); +directory.addEventListener(FileListEvent.DIRECTORY_LISTING, directoryListingHandler); + +function directoryListingHandler(event:FileListEvent):void { + var list:Array = event.files; + for (var i:uint = 0; i < list.length; i++) { + trace(list[i].nativePath); + } +} +getDirectoryListing()getRootDirectories()directoryListing eventioErrorflash.events:ErrorEventYou do not have adequate permissions to read this directory, or the directory does + not exist. + + You do not have adequate permissions to read this directory, or the directory does + not exist.directoryListingflash.events:FileListEventThe directory contents have been enumerated successfully. The + contents event includes a files property, which is the resulting array of File objects. + + The directory contents have been enumerated successfully.getDirectoryListing + Returns an array of File objects corresponding to files and directories in the directory represented by this + File object.An array of File objects. + + Array + Returns an array of File objects corresponding to files and directories in the directory represented by this + File object. This method does not explore the contents of subdirectories. + + The following code shows how to use the getDirectoryListing() method to + enumerate the contents of the user directory. + +import flash.filesystem.File; + +var directory:File = File.userDirectory; +var list:Array = directory.getDirectoryListing(); +for (var i:uint = 0; i < list.length; i++) { + trace(list[i].nativePath); +} +getDirectoryListingAsync()getRootDirectories()getRelativePath + Finds the relative path between two File paths.The reference is null. + + ArgumentErrorArgumentErrorThe caller is not in the application security sandbox. + + SecurityErrorSecurityErrorThe relative path between this file (or directory) and the ref file + (or directory), if possible; otherwise null. + + Stringrefflash.net:FileReference A File object against which the path is given. + + useDotDotBooleanfalse Specifies whether the resulting relative path can use ".." components. + + + Finds the relative path between two File paths. + +

The relative path is the list of components that can be appended to + (resolved against) this reference in order to locate the second (parameter) + reference. The relative path is returned using the "/" separator character.

+ +

Optionally, relative paths may include ".." references, but such paths + will not cross conspicuous volume boundaries.

+ +
getRootDirectories + Returns an array of File objects, listing the file system root directories.An array of File objects, listing the root directories. + + Array + Returns an array of File objects, listing the file system root directories. + +

For example, on Windows this is a list of volumes such as the C: drive and the + D: drive. An empty drive, such as a CD or DVD drive in which no disc is inserted, + is not included in this array. On Mac OS and Linux, this method always returns the + unique root directory for the machine (the "/" directory)

+ +

On file systems for which the root is not readable, such as the Android file system, + the properties of the returned File object do not always reflect the true value. For + example, on Android, the spaceAvailable property reports 0.

+ +
The following code outputs a list of root directories: + +import flash.filesystem.File; +var rootDirs:Array = File.getRootDirectories(); + +for (var i:uint = 0; i < rootDirs.length; i++) { + trace(rootDirs[i].nativePath); +} +
moveToAsync + Begins moving the file or directory at the location specified by this File object to + the location specified by the newLocation parameter.The application does not have the necessary permissions to move the file. + + SecurityErrorSecurityErrornewLocationflash.net:FileReferenceThe target location for the move. This object specifies the path to the resulting + (moved) file or directory, not the path to the containing directory. + + overwriteBooleanfalseIf false, the move fails if the target file + already exists. If true, the operation overwrites any existing file or directory + of the same name. + + + Begins moving the file or directory at the location specified by this File object to + the location specified by the newLocation parameter. + +

To rename a file, set the destination parameter to point to a path that is + in the file's directory, but with a different filename.

+ +

The move process creates any required parent directories (if possible).

+ +
The following code shows how to use the moveToAsync() method to rename a + file. The original filename is test1.txt and the resulting name is test2.txt. Since both the source and destination File + object point to the same directory (the Apollo Test subdirectory of the user's documents directory), the + moveToAsync() method renames the file, rather than moving it to a new directory. + Before running this code, create a test1.txt file in the Apollo Test subdirectory of the documents directory on your + computer. When you set overwrite parameter to true, the operation overwrites any + existing test2.txt file. + +import flash.filesystem.File; +import flash.events.Event; + +var sourceFile:File = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("Apollo Test/test1.txt"); +var destination:File = File.documentsDirectory; +destination = destination.resolvePath("Apollo Test/test2.txt"); + +var sourceFile.moveToAsync(destination, true); +sourceFile.addEventListener(Event.COMPLETE, fileMoveCompleteHandler); + +function fileMoveCompleteHandler(event:Event):void +{ + trace("Done.") +} +
copyToAsync()moveTo()moveToTrashAsync()completeflash.events:EventDispatched when the file or directory has been successfully moved. + + Dispatched when the file or directory has been successfully moved.ioErrorflash.events:IOErrorEventThe source does not exist; or the destination exists and overwrite + is false; or the source could not be moved to the target; or the source and destination refer + to the same file or folder and overwrite is set to true. On Windows, you cannot move + a file that is open or a directory that contains a file that is open. + + The source does not exist; or the destination exists and overwrite + is false; or the source could not be moved to the target; or the source and destination refer + to the same file or folder and overwrite is set to true.
moveToTrashAsync + Asynchronously moves a file or directory to the trash.The application does not have the necessary permissions to move the file to the trash. + + SecurityErrorSecurityError + Asynchronously moves a file or directory to the trash. + +

Note: On operating systems that do not support the concept of a recoverable trash folder, the files are removed immediately.

+ +
moveToTrash()ioErrorflash.events:IOErrorEventThe operating system did not allow the operation; or the file + or directory does not exist. On Windows, you cannot move a file that is open or a directory + that contains a file that is currently open. + + The operating system did not allow the operation; or the file + or directory does not exist.completeflash.events:EventDispatched when the file or directory has been successfully moved to the trash. + + Dispatched when the file or directory has been successfully moved to the trash.
moveToTrash + Moves a file or directory to the trash.The operating system did not allow the operation; or the file + or directory does not exist. On Windows, you cannot move a file that is open or a directory + that contains a file that is currently open. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions to move the file to the trash. + + SecurityErrorSecurityError + Moves a file or directory to the trash. + +

Note: On operating systems that do not support the concept of a recoverable trash folder, the files are removed immediately.

+ +
moveToTrashAsync()
moveTo + Moves the file or directory at the location specified by this File object to + the location specified by the destination parameter.The source does not exist; or the destination exists and overwrite is + set to false; or the source file or directory could not be moved to the target location; + or the source and destination refer to the same file or folder and overwrite is set to + true. On Windows, you cannot move a file that is open or a directory that contains a file + that is open. + + IOErrorflash.errors:IOErrorThe application does not have the necessary permissions to move the file. + + SecurityErrorSecurityErrornewLocationflash.net:FileReferenceThe target location for the move. This object specifies the path to the resulting + (moved) file or directory, not the path to the containing directory. + + overwriteBooleanfalseIf false, the move fails if the target file + already exists. If true, the operation overwrites any existing file or directory + of the same name. + + + Moves the file or directory at the location specified by this File object to + the location specified by the destination parameter. + +

To rename a file, set the destination parameter to point to a path that is + in the file's directory, but with a different filename.

+ +

The move process creates any required parent directories (if possible).

+ +
The following code shows how to use the moveTo() method to rename + a file. The original filename is test1.txt and the resulting filename is test2.txt. Since both the source and destination File + object point to the same directory (the Apollo Test subdirectory of the user's documents directory), the + moveTo() method renames the file, rather than moving it to a new directory. Before running + this code, create a test1.txt file in the AIR Test subdirectory of the documents directory on your + computer. When you set the overwrite parameter to true, the operation overwrites + any existing test2.txt file. + + +import flash.filesystem.File; +import flash.events.Event; + +var sourceFile:File = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("AIR Test/test1.txt"); +var destination:File = File.documentsDirectory; +destination = destination.resolvePath("Apollo Test/test2.txt"); + +try +{ + sourceFile.moveTo(destination, true); +} +catch (error:Error) +{ + trace("Error:" + error.message); +} + The following code shows how to use the moveTo() method to move a file. + The original file is the test1.txt file in the Apollo Test subdirectory of the user's documents directory, + and the method moves the file to the Results subdirectory. Before running this code, create a + test1.txt file in the AIR Test subdirectory of the home directory on your computer. The try + and catch statements show how to respond to errors. + +import flash.filesystem.File; + +var sourceFile:File = File.documentsDirectory; +sourceFile = sourceFile.resolvePath("AIR Test/test1.txt"); +var destination:File = File.documentsDirectory; +destination = destination.resolvePath("AIR Test/Results/test1.txt"); + +try +{ + sourceFile.moveTo(destination, true); +} +catch (error:Error) +{ + trace("Error:" + error.message); +} +
copyTo()moveToAsync()moveToTrash()
openWithDefaultApplication + Opens the file in the application registered by the operating system to open this file type.(Mac OS and Linux) No application was found that can open the file. + (On Windows, attempting to open a file that has no associated application fails silently, + without an exception.) + + ErrorErrorThe file is in the application directory or it is of a + prohibited file type. This error does not apply for AIR applications installed with a + native application installer (extended desktop profile applications). + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe file does not exist or no application is registered to open the file. + + IOErrorflash.errors:IOErrorThe file does not exist. + + ReferenceErrorReferenceError + Opens the file in the application registered by the operating system to open this file type. + +

AIR prevents you from using the File.openWithDefaultApplication() method to open certain files. + On Windows, AIR prevents you from opening files that have certain file types (files with specific extensions, listed below). + On Mac OS and Linux, AIR prevents you from opening files that will launch in specific applications, + specified below. Attempting to open one of these files using the openWithDefaultApplication() method + results in an exception. However, AIR applications installed with a native installer (extended desktop profile applications) + are not restricted by these limitations; they can open files of any type.

+ +

You cannot open documents from the application directory.

+ +

The tables below list file extensions that are prohibited on Windows, as well as the prevented applications on Mac OS and Linux:

+ +

+ Windows Document Extension Kind Mac OS Application Counterpart Linux Application Counterpart bat Batch file command Terminal No default application cmd DOS and Windows command file Terminal No default application com Command Terminal No default application csh UNIX csh shell script Terminal /bin/csh dash UNIX dash shell script Terminal /bin/dash ksh UNIX ksh shell script Terminal /bin/ksh sh UNIX shell script Terminal /bin/bash tcsh UNIX tcsh shell script Terminal /bin/tcsh zsh UNIX zsh shell script Terminal /bin/zsh exe Executable file Executable bit, .app extension /lib/ld.so lnk Windows shortcut file Executable bit, .app extension Links in Linux, executable bit set, no default application pif Program Information File Executable bit, .app extension N/A reg Registration Information/Key for Windows 95/98, Registry Data File N/A N/A scf Windows Explorer command ScriptEditor, AutomatorRunner N/A shb, shs Shell Scrap Object file N/A N/A prg Program file N/A N/A vb, vbe, vbs VBScript files N/A N/A vsmacros Visual Studio .NET binary-based macro project N/A N/A ws, wsc, wsf, wsh Windows script files ScriptEditor, AutomatorRunner N/A fxp Fox Pro compiled source code N/A N/A mas Microsoft Access stored procedures N/A N/A scr Windows screen saver N/A N/A py, pyc Python script file Python Python pl Perl script file Terminal perl cgi Common Gateway Interface script file Terminal perl msi, msm, msp, mst, idt, cub, pcp Windows installer file installer N/A job Windows Task Scheduler task object N/A N/A jar, js, jse Java archive file, JavaScript file, JScript encoded script file JarLauncher jar url Internet shortcut N/A N/A hta HTML application N/A N/A +

+ +

+ Mac OS X Only Kind Mac OS X Application Linux Application Counterpart N/A Mac OS X Java applet AppletLauncher N/A N/A Mac OS X AppleScript plugin systemevents N/A N/A Mac OS X widget dock, dashboardlauncher N/A +

+ +

+ Linux-only Document Extension Kind Mac OS X Application Counterpart Linux Application rb Ruby shell script N/A ruby desktop Desktop files and shortcuts N/A No default application directory Directory files and shortcuts N/A No default application +

+ + +
The following code lets the user navigate to an MP3 file and open it + in the default application for playing MP3 files. + +import flash.filesystem.File; +import flash.net.FileFilter; + +var file:File = File.documentsDirectory; +var mp3Filter:FileFilter = new FileFilter("MP3 Files", "*.mp3"); +file.browseForOpen("Open", [mp3Filter]); +file.addEventListener(Event.SELECT, fileSelected); + +function fileSelected(e:Event):void +{ + file.openWithDefaultApplication(); +} +
downloadedNativeProcess
resolvePath + Creates a new File object with a path relative to this File object's path, based on the + path parameter (a string).A new File object pointing to the resulting path. + + flash.filesystem:FilepathStringThe path to append to this File object's path (if the path parameter + is a relative path); or the path to return (if the path parameter is an absolute + path). + + + Creates a new File object with a path relative to this File object's path, based on the + path parameter (a string). + +

You can use a relative path or absolute path as the path parameter.

+ +

If you specify a relative path, the given path is "appended" + to the path of the File object. However, use of ".." in the path + can return a resulting path that is not a child of the File object. The resulting reference need not + refer to an actual file system location.

+ +

If you specify an absolute file reference, the method returns the File object pointing to that + path. The absolute file reference should use valid native path syntax for the user's operating + system (such as "C:\\test" on Windows). Do not use a URL (such as + "file:///c:/test") as the path parameter.

+ +

All resulting paths are normalized as follows:

+ +
  • Any "." element is ignored.
  • Any ".." element consumes its parent entry.
  • No ".." reference that reaches the file system root or the application-persistent + storage root passes that node; it is ignored.
+ +

You should always use the forward slash (/) character as the path separator. + On Windows, you can also use the backslash (\) character, but you should not. + Using the backslash character can lead to applications that do not work on other platforms.

+ +

Filenames and directory names are case-sensitive on Linux.

+ +
applicationDirectory + The folder containing the application's installed files.flash.filesystem:File + The folder containing the application's installed files. + +

The url property for this object uses the app URL scheme + (not the file URL scheme). This means that the url string is specified starting + with "app:" (not "file:"). Also, if you create a File object relative to the + File.applicationDirectory directory (by using the resolvePath() method), + the url property of the File object also uses the app URL scheme. +

+ +

Note: You cannot write to files or directories that have paths that use the app: + URL scheme. Also, you cannot delete or create files or folders that have paths that use the app: + URL scheme. Modifying content in the application directory is a bad practice, for security reasons, and is + blocked by the operating system on some platforms. + If you want to store application-specific data, consider using the application storage directory + (File.applicationStorageDirectory). If you want any of the content in the application storage directory + to have access to the application-privileged functionality (AIR APIs), you can expose that functionality + by using a sandbox bridge.

+ + +

The applicationDirectory property provides a way to reference the + application directory that works across platforms. If you set a File object to reference + the application directory using the nativePath or url property, + it will only work on the platform for which that path is valid.

+ +

On Android, the nativePath property of a File object pointing to the application directory is an empty + string. Use the url property to access application files.

+
applicationStorageDirectory
applicationStorageDirectory + The application's private storage directory.flash.filesystem:File + The application's private storage directory. + +

Each AIR application has a unique, persistent application storage directory, which + is created when you first access File.applicationStorageDirectory. This directory + is a convenient location to store application-specific data.

+ +

When you uninstall an AIR application, whether the uninstaller deletes the application storage directory + and its files depends on the platform.

+ +

The url property for this object uses the app-storage URL scheme + (not the file URL scheme). This means that the url string is specified starting + with "app-storage:" (not "file:"). Also, if you create a File object relative to the + File.applicationStoreDirectory directory (by using the resolvePath() method), + the url of the File object also uses the app-storage URL scheme + (as in the example).

+ +

The applicationStorageDirectory property provides a way to reference the + application storage directory that works across platforms. If you set a File object to reference + the application storage directory using the nativePath or url property, + it will only work on the platform for which that path is valid.

+ + +
The following code creates a File object pointing to the "images" subdirectory of + the application storage directory. + +import flash.filesystem.File; + +var tempFiles:File = File.applicationStorageDirectory; +tempFiles = tempFiles.resolvePath("images/"); +trace(tempFiles.url); // app-storage:/images +
desktopDirectory + The user's desktop directory.flash.filesystem:File + The user's desktop directory. + +

The desktopDirectory property provides a way to reference the desktop + directory that works across platforms. If you set a File object to reference + the desktop directory using the nativePath or url property, + it will only work on the platform for which that path is valid.

+ +

If an operating system does not support a desktop directory, a suitable directory in the + file system is used instead.

+ +

AIR for TV devices have no concept of a user's desktop directory. + Therefore, the desktopDirectory property + references the same directory location as File.userDirectory property. + The user directory is unique to the application.

+ + +
The following code outputs a list of files and directories contained in the user's desktop directory. + +import flash.filesystem.File; +var desktop:File = File.desktopDirectory; + +var files:Array = desktop.getDirectoryListing(); + +for (var i:uint = 0; i < files.length; i++) { + trace(files[i].nativePath); +} +
documentsDirectory + The user's documents directory.flash.filesystem:File + The user's documents directory. + +

On Windows, this is the My Documents directory (for example, C:\Documents and Settings\userName\My Documents). + On Mac OS, the default location is /Users/userName/Documents. On Linux, the default location is /home/userName/Documents + (on an English system), and the property observes the xdg-user-dirs setting.

+ + +

The documentsDirectory property provides a way to reference the documents + directory that works across platforms. If you set a File object to reference + the documents directory using the nativePath or url property, + it will only work on the platform for which that path is valid.

+ +

If an operating system does not support a documents directory, a suitable directory in the + file system is used instead.

+ +

AIR for TV devices have no concept of a user's documents directory. + Therefore, the documentsDirectory property + references the same directory location as the File.userDirectory property. + The user directory is unique to the application.

+ +
The following code uses the File.documentsDirectory property and the + File.createDirectory() method to ensure that a directory named "AIR Test" exists + in the user's documents directory. + +import flash.filesystem.File; + +var directory:File = File.documentsDirectory; +directory = directory.resolvePath("AIR Test"); + +File.createDirectory(directory); +trace(directory.exists); // true +
downloaded + Indicates whether the referenced file or directory was downloaded (from the internet) or not.Boolean + Indicates whether the referenced file or directory was downloaded (from the internet) or not. + +

This property is only meaningful on operating systems in which files can be flagged as downloaded:

+ +
  • Windows XP service pack 2 and later, and on Windows Vista
  • Mac OS 10.5 and later
+ +

On systems that do not flag downloaded files, such as Linux, + the property is not meaningful (and it is set to false).

+ +
openWithDefaultApplication()
exists + Indicates whether the referenced file or directory exists.Boolean + Indicates whether the referenced file or directory exists. + The value is true if the File object points to an existing file or directory, + false otherwise. + + The following code creates a temporary file, then deletes it and uses the + File.exists property to check for the existence of the file. + +import flash.filesystem.*; + +var temp:File = File.createTempFile(); +trace(temp.exists); // true +temp.deleteFile(); +trace(temp.exists); // false +icon + An Icon object containing the icons defined for the file.flash.desktop:Icon + An Icon object containing the icons defined for the file. An Icon object is an array of BitmapData + objects corresponding to the various icon states. On Linux, the Icon object contains no icons. On + Android, the icon property is null. + + The following code shows how to find the image in the icon array that has + the greatest height, and it sets a Bitmap object to that image. + +import flash.filesystem.File; +import flash.display.*; + +var directory:File = File.documentsDirectory; +var bitmaps:Array = directory.icon.bitmaps; +var bmpData:BitmapData = new BitmapData(1, 1); +for (var i:uint = 0; i < bitmaps.length; i++) { + if (bitmaps[i].height > bmpData.height) { + bmpData = directory.icon.bitmaps[i]; + } +} +var iconBmp:Bitmap = new Bitmap(bmpData); + You might add this Bitmap object as a child of a display object container, + such as a Sprite object or a Flex UIComponent object. +isDirectory + Indicates whether the reference is to a directory.Boolean + Indicates whether the reference is to a directory. + The value is true if the File object points to a directory; false otherwise. + + The following code creates an array of File objects pointing to files and directories in the + user directory and then uses the isDirectory property to list only those File objects that point to + directories (not to files). + +import flash.filesystem.*; + +var userDirFiles:Array = File.userDirectory.getDirectoryListing(); +for (var i:uint = 0; i < userDirFiles.length; i++) { + if (userDirFiles[i].isDirectory) { + trace(userDirFiles[i].nativePath); + } +} +isHidden + Indicates whether the referenced file or directory is "hidden." + The value is true if the referenced file or directory is hidden, false otherwise.Boolean + Indicates whether the referenced file or directory is "hidden." + The value is true if the referenced file or directory is hidden, false otherwise. + + The following code creates an array of File objects pointing to files and directories in the + user directory and then uses the isHidden property to list hidden files and directories. + +import flash.filesystem.*; + +var userDirFiles:Array = File.userDirectory.getDirectoryListing(); +for (var i:uint = 0; i < userDirFiles.length; i++) { + if (userDirFiles[i].isHidden) { + trace(userDirFiles[i].nativePath); + } +} +isPackage + Indicates whether the referenced directory is a package.Boolean + Indicates whether the referenced directory is a package. + +

The value is true if the referenced directory is a package, false otherwise. + Note that the File class does not allow creating packages directly.

+ +
  • On Mac OS, directories can be designated as packages and will show up in the Finder as a + single file rather than as a directory. This property is set to true if the referenced + directory is a package, and false if the file is not a directory, does not exist, or + is not a package.
  • On other operating systems, this property is always set to false.
+ +
isSymbolicLink + Indicates whether the reference is a symbolic link.Boolean + Indicates whether the reference is a symbolic link. + +

The value is true if the File object is a symbolic link, false otherwise. + Note that the File class does not allow creating symbolic links directly.

+ +

Symbolic links allow a file to point to another file or directory on disk. Although similar, symbolic + links are not the same as aliases on Mac OS and shortcuts on Windows. An alias or a shortcut is always + reported as a file (rather than a directory), and reading or writing to an alias or shortcut + never affects the original file or directory that it points to. + On the other hand, a symbolic link generally behaves like the file or directory it points to. It can be + reported as a file or a directory, and reading or writing to a symbolic link affects the file or directory + that it points to, not the symbolic link itself. Deleting a symbolic link, however, deletes the link + and not the target of the link.

+ +

Mac® OS®, Linux, and Windows® Vista® + support symbolic links. Additionally, on Windows the isSymbolicLink + property for a File object referencing a junction point (used in the NTFS file system) is set to + true.

+ +
lineEnding + The line-ending character sequence used by the host operating system.String + The line-ending character sequence used by the host operating system. + +

On Mac OS and Linux, this is the line-feed character (character code 0x0A hexadecimal). + On Windows, this is the carriage return character (character code 0x0D hexadecimal) followed + by the line-feed character (character code 0x0A hexadecimal).

+ +
The following code writes a string (str) to a text file and uses the + File.lineEnding static property to replace all instances of the new-line character + (represented in the code by the regular expression /\n/g) with the preferred + line-ending character for the host operating system. + +import flash.filesystem.*; + +var str:String = "Hello\n" + + "World\n"; +str = str.replace(/\n/g, File.lineEnding); +var file:File = File.documentsDirectory.resolvePath("AIR Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.open(file, FileMode.WRITE); +fileStream.writeUTF(str); +fileStream.close(); +
nativePath + The full path in the host operating system representation.StringThe syntax of the path is invalid. + + ArgumentErrorArgumentErrorThe caller is not in the application security sandbox. + + SecurityErrorSecurityError + The full path in the host operating system representation. On Mac OS and Linux, + the forward slash (/) character is used as the path separator. + However, in Windows, you can set the nativePath property + by using the forward slash character or the backslash (\) character as the + path separator, and AIR automatically replaces forward slashes with + the appropriate backslash character. + +

Before writing code to set the nativePath property directly, + consider whether doing so may result in platform-specific code. For example, a native + path such as "C:\\Documents and Settings\\bob\\Desktop" is only valid on Windows. + It is far better to use the following static properties, which represent commonly used directories, + and which are valid on all platforms:

+ +
  • File.applicationDirectory
  • File.applicationStorageDirectory
  • File.desktopDirectory
  • File.documentsDirectory
  • File.userDirectory
+ +

You can use the resolvePath() method to get a path relative to these directories.

+ +

Some Flex APIs, such as the source property of the SWFLoader class, use a + URL (the url property of a File object), not a native path (the nativePath + property).

+ + + +
The following code shows the difference between the nativePath + property and the url property of a File object. The comments show results on an + example Windows computer. + +import flash.filesystem.File; + +var docs:File = File.documentsDirectory; +trace(docs.nativePath); // C:\Documents and Settings\turing\My Documents +trace(docs.url); // file:///C:/Documents%20and%20Settings/turing/My%20Documents +
parent + The directory that contains the file or directory referenced by this File object.flash.filesystem:File + The directory that contains the file or directory referenced by this File object. + +

If the file or directory does not exist, the parent property still returns the + File object that points to the containing directory, even if that directory does not exist.

+ +

This property is identical to the return value for resolvePath("..") except that the parent of a root + directory is null.

+ +
The following code uses the parent property to show the directory + that contains a temporary file. + +import flash.filesystem.File; + +var tempFile:File = File.createTempDirectory(); +trace(tempFile.parent.nativePath); +tempFile.deleteFile(); +
separator + The host operating system's path component separator character.String + The host operating system's path component separator character. + +

On Mac OS and Linux, this is the forward slash (/) character. On Windows, it is the backslash + (\) character.

+ +

Note: When using the backslash character in a String literal, remember to + type the character twice (as in "directory\\file.ext"). Each pair of backslashes + in a String literal represent a single backslash in the String.

+ +
The following code uses the getRelativePath() method to get the relative path + between a directory and a file. The code then uses the File.separator static property + to replace forward slash (/) characters in the path with the separator character used by the operating + system, which is the backslash character (\) on Windows and the forward slash character on other + operating systems. + +import flash.filesystem.File; + +var directory:File = File.documentsDirectory.resolvePath("Apollo Test"); +var file:File = File.documentsDirectory.resolvePath("Apollo Test/employees/bob/test.txt"); + +var relativePath:String = directory.getRelativePath(file); // employees/bob/test.txt +relativePath = relativePath.replace(/\//g, File.separator); +trace(relativePath); + In this example, the replace() method uses a regular expression, + /\//g, to match all forward slash characters. +
spaceAvailable + The space available for use at this File location, in bytes.Number + The space available for use at this File location, in bytes. + +

If the File object references a directory, + spaceAvailable indicates the space in the directory that files can use. If + the File object references a file, spaceAvailable indicates the space into which the file + could grow. If the file location does not exist, spaceAvailable is set to 0. If the File + object references a symbolic link, spaceAvailable indicates the space available at the + location the symbolic link points to.

+ +

Typically the space available for a directory or file is the same as the space available on the + volume containing the directory or file. However, space available can take into account quotas and + per-directory limits.

+ +

Adding a file or directory to a volume generally requires more space than the actual size of the file + or the size of the contents of the directory. For example, the operating system may require more space to + store index information. Or the disk sectors required may use additional space. Also, available + space changes dynamically. So, you cannot expect to allocate all of the reported space + for file storage.

+ +
systemCharset + The default encoding used by the host operating system.String + The default encoding used by the host operating system. + +

Possible values include "windows-1252" + "shift-jis", "cn-gb", "iso-8859-1", and others. + For a complete list, see Supported Character Sets.

+ +

You can use this value when using the readMultiByte() and writeMultiByte() + methods of the FileStream class.

+ +
The following code opens a file (a test.txt file in the AIR Test subdirectory of the + user's documents directory), and uses the File.systemCharset static property + as the charSet parameter of a call to the readMultiByte() method + of a FileStream object. + +import flash.filesystem.File; + +var file:File = File.documentsDirectory.resolvePath("AIR Test/test.txt"); +var fileStream:FileStream = new FileStream(); +fileStream.open(file, FileMode.READ); +var str:String = fileStream.readMultiByte(file.size, File.systemCharset); +trace(str); +
FileStream.readMultiByte()FileStream.writeMultiByte()
url + The URL for this file path.StringThe URL syntax is invalid. + + ArgumentErrorArgumentErrorThe caller is not in the application security sandbox. + + SecurityErrorSecurityError + The URL for this file path. + +

If this is a reference to a path in the application storage directory, the URL scheme is + "app-storage"; if it is a reference to a path in the application directory, the + URL scheme is "app"; otherwise the scheme is "file".

+ +

You can use blank space characters (rather than "%20") when + assigning a value to the url property; AIR automatically + encodes the strings (for instance, converting spaces to "%20").

+ +
The following code shows the difference between the nativePath + property and the url property of a File object. The comments show results on an + example Windows computer. + +import flash.filesystem.File; + +var docs:File = File.documentsDirectory; +trace(docs.nativePath); // C:\Documents and Settings\turing\My Documents +trace(docs.url); // file:///C:/Documents%20and%20Settings/turing/My%20Documents +
nativePathdecodeURI() global functiondecodeURIComponent() global functiondecodeURI() global functiondecodeURIComponent() global function
userDirectory + The user's directory.flash.filesystem:File + The user's directory. + +

On Windows, this is the parent of the My Documents directory + (for example, C:\Documents and Settings\userName). On + Mac OS, it is /Users/userName. On Linux, it is /home/userName.

+ +

The userDirectory property provides a way to reference the user + directory that works across platforms. If you set the nativePath or url + property of a File object directly, it will only work on the platform for which that path is valid.

+ +

If an operating system does not support a user directory, a suitable directory in the + file system is used instead.

+ +

On AIR for TV devices, the userDirectory property + references a user directory that is unique to the application.

+ +
The following code outputs a list of files and directories contained in the root level + of the user directory: + +import flash.filesystem.File; + +var files:Array = File.userDirectory.listDirectory(); +for (var i:uint = 0; i < files.length; i++) { + trace(files[i].nativePath); +} +
StorageVolume + A StorageVolume object includes properties defining a mass storage volume.Object + A StorageVolume object includes properties defining a mass storage volume. + This class is used in two ways: + +
  • The storageVolume property of a StorageVolumeChangeEvent object + is a StorageVolume object. This object represents the storage volume that has been + mounted or unmounted.
  • The StorageVolumeInfo.storageVolumeInfo.getStorageVolumes() method returns a + vector of StorageVolume objects. Each of these StorageVolume objects represents a + mounted storage volume.
+ +
The following code lists the properties of each mounted storage volume: + +package +{ + import flash.display.Sprite; + import flash.filesystem.StorageVolume; + import flash.filesystem.StorageVolumeInfo; + + public class StorageVolumeExample extends Sprite + { + public function StorageVolumeExample() + { + var volumes:Vector.<StorageVolume> = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); + for (var i:int = 0; i < volumes.length; i++) + { + var volume:StorageVolume = volumes[i]; + trace("nativePath:", volume.rootDirectory.nativePath); + trace("fileSystemType:", volume.fileSystemType); + trace("isRemovable:", volume.isRemovable); + trace("isWritable:", volume.isWritable); + trace("drive:", volume.drive); + trace("name:", volume.name); + trace("________________________________________________________"); + } + } + } +} + The following code lists the properties of each storage volume that becomes mounted or unmounted. + Note that the storageVolume property of the StorageVolumeChangeEvent is only set for the storageVolumeMount + event; it is null for the storageVolumeUnmount event: + +package +{ + import flash.display.Sprite; + import flash.events.StorageVolumeChangeEvent; + import flash.filesystem.StorageVolume; + import flash.filesystem.StorageVolumeInfo; + + public class StorageVolumeChangeEventExample extends Sprite + { + public function StorageVolumeChangeEventExample() + { + StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, mountEventHandler); + StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, unmountEventHandler); + } + public function mountEventHandler(event:StorageVolumeChangeEvent):void + { + var volume:StorageVolume = event.storageVolume; + trace("VOLUME MOUNTED:"); + trace("nativePath:", event.rootDirectory.nativePath); + trace("fileSystemType:", volume.fileSystemType); + trace("isRemovable:", volume.isRemovable); + trace("isWritable:", volume.isWritable); + trace("drive:", volume.drive); + trace("name:", volume.name); + trace(); + } + public function unmountEventHandler(event:StorageVolumeChangeEvent):void + { + trace("VOLUME UNMOUNTED:"); + trace("nativePath:", event.rootDirectory.nativePath); + trace(); + } + } +} +
flash.filesystem.StorageVolumeInfo.getStorageVolumes()flash.events.StorageVolumeChangeEvent.storageVolumeStorageVolume + The constructor function.rootDirPathflash.filesystem:FilenameStringwritableBooleanremovableBooleanfileSysTypeStringdriveString + The constructor function. Generally, you do not call this constructor function directly + (to create new StorageVolume objects). Rather, you reference StorageVolume objects + by accessing the storageVolume property of a StorageVolumeChangeEvent object + or by calling StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(). + + drive + The volume drive letter on Windows.String + The volume drive letter on Windows. On other platforms, this property is set + to null. + + fileSystemType + The type of file system on the storage volume (such as "FAT", "NTFS", + "HFS", or "UFS").String + The type of file system on the storage volume (such as "FAT", "NTFS", + "HFS", or "UFS"). + + The following code lists the native path for the root directory and the file system type of each mounted storage volume: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); +for (var i:int = 0; i < volumes.length; i++) +{ + trace(volumes[i].rootDirectory.nativePath, "(" + volumes[i].fileSystemType + ")"); +} +isRemovable + Whether the operating system considers the storage volume to be removable (true) + or not (false).Boolean + Whether the operating system considers the storage volume to be removable (true) + or not (false). + +

The following table lists the values StorageVolume.isRemovable property for various types + of devices:

+ + Type of deviceMac OSWindowsLinuxCD/DVD (fixed)truetruetrueUSB flash drivetruetruetrueUSB hard srivefalsefalsetrueFireWire hard drivefalsefalsetrueShared volumetruefalse- 1Network drivefalsefalsefalseStorage card reader (empty)- 2false- 2Storage card reader (with SD/CF card)truetruetrue + +

1 Linux does not have a concept of a shared volume.

+ +

2 On Windows, an empty card reader is listed as a non-removable device. On Mac OS and Linux, + empty car readers are not listed as storage volumes.

+ +
The following code outputs a list of non-removable storage volumes, followed by a list of removable storage volumes: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); + +trace("Non-removeable volumes:"); +for (var i:int = 0; i < volumes.length; i++) +{ + if (!volumes[i].isRemovable) + { + trace(volumes[i].rootDirectory.nativePath); + } +} + +trace("\nRemoveable volumes:"); +for (i = 0; i < volumes.length; i++) +{ + if (volumes[i].isRemovable) + { + trace(volumes[i].rootDirectory.nativePath); + } +} +
isWritable + Whether a volume is writable (true) or not (false).Boolean + Whether a volume is writable (true) or not (false). + +

Note: You can determine the amount of space available on a + volume by calling the rootDirectory.spaceAvailble property of the + StorageVolume object.

+ +
The following code outputs a list of writable storage volumes and the space available on each: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); + +for (var i:int = 0; i < volumes.length; i++) +{ + if(volumes[i].isWritable) + { + trace(volumes[i].rootDirectory.nativePath, volumes[i].rootDirectory.spaceAvailable); + } +} +
flash.fileSystem.File.spaceAvailable
name + The name of the volume.String + The name of the volume. If there is no name, this property is set to null. + + The following code lists the native path for the root directory and the file system name (if there is one) of each mounted storage volume: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); +for (var i:int = 0; i < volumes.length; i++) +{ + var name:String = new String(); + if (volumes[i].name) + { + name = "(" + volumes[i].name + ")"; + } + trace(volumes[i].rootDirectory.nativePath, name); +} +rootDirectory + A File object corresponding to the root directory of the volume.flash.filesystem:File + A File object corresponding to the root directory of the volume. + + The following code lists the native path for the root directory of each mounted storage volume: + +var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>; +volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes(); +for (var i:int = 0; i < volumes.length; i++) +{ + trace(volumes[i].rootDirectory.nativePath); +} +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.filters.xml b/language-server/playerglobal_docs/flash.filters.xml new file mode 100644 index 0000000..640f77c --- /dev/null +++ b/language-server/playerglobal_docs/flash.filters.xml @@ -0,0 +1,5745 @@ +flash.filtersGradientGlowFilter + + The GradientGlowFilter class lets you apply a gradient glow effect to display objects.Lets you create a gradient glow effect. + flash.filters:BitmapFilter + The GradientGlowFilter class lets you apply a gradient glow effect to display objects. + A gradient glow is a realistic-looking glow with a color gradient that + you can control. You can apply a gradient glow around + the inner or outer edge of an object or on top of an object. + You can apply the filter to any display object (objects that inherit from the DisplayObject class), + such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to display objects, use the + filters property. Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the cacheAsBitmap property of the + display object is set to true. If you clear all filters, the original value of + cacheAsBitmap is restored.

+ +

This filter supports Stage scaling. However, it does not support general scaling, rotation, + and skewing; if the object itself is scaled (if scaleX and scaleY are set + to a value other than 1.0), the + filter effect is not scaled. It is scaled only when the user zooms in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + For example, if you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example draws a square and applies a gradient glow filter to it. + The general workflow of the example is as follows: +
  1. Import the required classes.
  2. Declare global variables used to define the square and filter.
  3. Create the constructor function, which does the following: +
    • Calls the draw() method, which uses methods of the Graphics class + accessed through the graphics property of Sprite to draw a square.
    • Creates a BitmapFilter object named filter and assigns it + the return value of a call to getBitmapFilter(), which creates the filter.
    • Creates a new array named myFilters and adds filter to it.
    • Assigns myFilters to the filters property of the + GradientGlowFilterExample object. This applies all filters found in myFilters, + which in this case is only filter.
    +
+ +package { + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BitmapFilterType; + import flash.filters.GradientGlowFilter; + import flash.display.Sprite; + + public class GradientGlowFilterExample extends Sprite { + private var bgColor:uint = 0xCCCCCC; + private var size:uint = 80; + private var offset:uint = 50; + + private var distance:Number = 0; + private var angleInDegrees:Number = 45; + private var colors:Array = [0xFFFFFF, 0xFF0000, 0xFFFF00, 0x00CCFF]; + private var alphas:Array = [0, 1, 1, 1]; + private var ratios:Array = [0, 63, 126, 255]; + private var blurX:Number = 50; + private var blurY:Number = 50; + private var strength:Number = 2.5; + private var quality:Number = BitmapFilterQuality.HIGH; + private var type:String = BitmapFilterType.OUTER; + private var knockout:Boolean = false; + + public function GradientGlowFilterExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + return new GradientGlowFilter(distance, + angleInDegrees, + colors, + alphas, + ratios, + blurX, + blurY, + strength, + quality, + type, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
GradientGlowFilter.ratiosflash.display.BitmapData.applyFilter()flash.display.DisplayObject.cacheAsBitmapflash.display.DisplayObject.filtersGlowFilter classGradientGlowFilter + Initializes the filter with the specified parameters.distanceNumber4.0The offset distance of the glow. + + angleNumber45The angle, in degrees. Valid values are 0 to 360. + + colorsArraynullAn array of colors that defines a gradient. + For example, red is 0xFF0000, blue is 0x0000FF, and so on. + + alphasArraynullAn array of alpha transparency values for the corresponding colors in + the colors array. Valid values for each element in the array are 0 to 1. + For example, a value of .25 sets the alpha transparency value to 25%. + + ratiosArraynullAn array of color distribution ratios. Valid values are + 0 to 255. This value defines the percentage of the width where the color + is sampled at 100 percent. + + blurXNumber4.0The amount of horizontal blur. Valid values are 0 to 255. A blur of 1 or + less means that the original image is copied as is. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + blurYNumber4.0The amount of vertical blur. Valid values are 0 to 255. A blur of 1 or less + means that the original image is copied as is. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + strengthNumber1The strength of the imprint or spread. The higher the value, the more color is + imprinted and the stronger the contrast between the glow and the background. + Valid values are 0 to 255. The larger the value, the stronger the imprint. A value of 0 + means the filter is not applied. + + qualityint1The number of times to apply the filter. Use the BitmapFilterQuality constants: +
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

For more information, see the description of the quality property.

+ +
typeStringinnerThe placement of the filter effect. Possible values are the + flash.filters.BitmapFilterType constants: +
  • BitmapFilterType.OUTER — Glow on the outer edge of the object
  • BitmapFilterType.INNER — Glow on the inner edge of the object; the default.
  • BitmapFilterType.FULL — Glow on top of the object
+ + +
knockoutBooleanfalseSpecifies whether the object has a knockout effect. A knockout effect + makes the object's fill transparent and reveals the background color of the document. + The value true specifies a knockout effect; + the default is false (no knockout effect). + +
+ Initializes the filter with the specified parameters. + +
clone + Returns a copy of this filter object.A new GradientGlowFilter instance with all the + same properties as the original GradientGlowFilter instance. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + alphas + An array of alpha transparency values for the corresponding colors in + the colors array.ArrayThe Array is null when being set + + TypeErrorTypeErrorAn array of alpha transparency values. + + + An array of alpha transparency values for the corresponding colors in + the colors array. Valid values for each element in the array are 0 to 1. + For example, .25 sets the alpha transparency value to 25%. + +

The alphas property cannot be changed by directly modifying its values. + Instead, you must get a reference to alphas, make the change to the + reference, and then set alphas to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +
GradientGlowFilter.colorsGradientGlowFilter.ratios
angle + The angle, in degrees.Number + The angle, in degrees. Valid values are 0 to 360. The default is 45. + +

The angle value represents the angle of the theoretical light source falling on the object and + determines the placement of the effect relative to the object. If distance is set to 0, the effect + is not offset from the object, and therefore the angle property has no effect.

+ +
blurX + The amount of horizontal blur.Number + The amount of horizontal blur. Valid values are 0 to 255. A blur of 1 or + less means that the original image is copied as is. The default value + is 4. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) are optimized + to render more quickly than other values. + + blurY + The amount of vertical blur.Number + The amount of vertical blur. Valid values are 0 to 255. A blur of 1 or less + means that the original image is copied as is. The default value is + 4. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) are optimized + to render more quickly than other values. + + colors + An array of colors that defines a gradient.ArrayThe Array is null when being set + + TypeErrorTypeError + An array of colors that defines a gradient. + For example, red is 0xFF0000, blue is 0x0000FF, and so on. + +

The colors property cannot be changed by directly modifying its values. + Instead, you must get a reference to colors, make the change to the + reference, and then set colors to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +
GradientGlowFilter.alphasGradientGlowFilter.ratios
distance + The offset distance of the glow.Number + The offset distance of the glow. The default value is 4. + + knockout + Specifies whether the object has a knockout effect.Boolean + Specifies whether the object has a knockout effect. A knockout effect + makes the object's fill transparent and reveals the background color of the document. + The value true specifies a knockout effect; + the default value is false (no knockout effect). + + quality + The number of times to apply the filter.int + The number of times to apply the filter. The default value is BitmapFilterQuality.LOW, + which is equivalent to applying the filter once. The value BitmapFilterQuality.MEDIUM + applies the filter twice; the value BitmapFilterQuality.HIGH applies it three times. + Filters with lower values are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing the values + of the blurX and blurY properties.

+ +
flash.filters.BitmapFilterQuality
ratios + An array of color distribution ratios for the corresponding colors in the + colors array.ArrayThe Array is null when being set + + TypeErrorTypeError + An array of color distribution ratios for the corresponding colors in the + colors array. Valid values are + 0 to 255. + +

The ratios property cannot be changed by directly modifying its values. + Instead, you must get a reference to ratios, make the change to the + reference, and then set ratios to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +

Think of the gradient glow filter as a glow that emanates from + the center of the object (if the distance value is set to 0), + with gradients that are stripes of color blending into each other. The first color + in the colors array is the outermost color of the glow. + The last color is the innermost color of the glow.

+ +

Each value in the ratios array sets + the position of the color on the radius of the gradient, where 0 represents + the outermost point of the gradient and 255 represents the innermost point of + the gradient. The ratio values can range from 0 to 255 pixels, + in increasing value; for example [0, 64, 128, 200, 255]. Values from 0 to 128 + appear on the outer edges of the glow. Values from 129 to 255 appear in the inner + area of the glow. Depending on the ratio values of the colors and the type + value of the filter, the filter colors might be obscured by the object to which + the filter is applied.

+ +

In the following code and image, a filter is applied to a black circle movie + clip, with the type set to "full". For instructional purposes, the first color + in the colors array, pink, has an alpha value of 1, + so it shows against the white document background. (In practice, you probably would + not want the first color showing in this way.) The last color in the + array, yellow, obscures the black circle to which the filter is applied:

+ +

+	var colors:Array = [0xFFCCFF, 0x0000FF, 0x9900FF, 0xFF0000, 0xFFFF00];
+	var alphas:Array = [1, 1, 1, 1, 1];
+	var ratios:Array = [0, 32, 64, 128, 225];
+	var myGGF:GradientGlowFilter = new GradientGlowFilter(0, 0, colors, alphas, ratios, 50, 50, 1, 2, "full", false);
+	

+

+ +

To achieve a seamless effect with your document background when you set the type + value to "outer" or "full", set the first color in the + array to the same color as the document background, or set the + alpha value of the first color to 0; either technique makes the filter blend in with the background.

+ +

If you make two small changes in the code, the effect of the glow can be very + different, even with the same ratios and colors arrays. Set + the alpha value of the first + color in the array to 0, to make the filter blend in with the document's + white background; and set the type property to + "outer" or "inner". + Observe the results, as shown in the following images.

+

+

+

Keep in mind that the spread of the colors in the gradient varies based on the values + of the blurX, blurY, strength, and quality + properties, as well as the ratios values.

+ +
GradientGlowFilter.colorsGradientGlowFilter.alphasflash.display.Graphics.beginGradientFill()
strength + The strength of the imprint or spread.Number + The strength of the imprint or spread. The higher the value, the more color is imprinted + and the stronger the contrast between the glow and the background. Valid values are 0 to 255. + A value of 0 means that the filter is not applied. The default value is 1. + + type + The placement of the filter effect.StringThe string is null when being set + + TypeErrorTypeError + The placement of the filter effect. Possible values are flash.filters.BitmapFilterType constants: +
  • BitmapFilterType.OUTER — Glow on the outer edge of the object
  • BitmapFilterType.INNER — Glow on the inner edge of the object; the default.
  • BitmapFilterType.FULL — Glow on top of the object
+ +
ColorMatrixFilter +The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the RGBA color and alpha values +of every pixel in the input image to produce a result with a new set of RGBA color and alpha values.Applies a color matrix transformation on the color and alpha transparency values of each pixel. +flash.filters:BitmapFilter +The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the RGBA color and alpha values +of every pixel in the input image to produce a result with a new set of RGBA color and alpha values. +It allows saturation changes, hue rotation, luminance to alpha, and various other effects. +You can apply the filter to any display object (that is, objects that inherit from the DisplayObject class), +such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

Note: For RGBA values, the most significant byte represents the red channel value, +followed by green, blue, and then alpha.

+ +

To create a new color matrix filter, use the syntax new ColorMatrixFilter(). +The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to movie clips, text fields, buttons, and video, use the +filters property (inherited from DisplayObject). Setting the filters +property of an object does not modify the object, and you can remove the filter by clearing the +filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. +Calling applyFilter() on a BitmapData object takes the source BitmapData object +and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the cacheAsBitmap property of the +display object is set to true. If you remove all filters, the original value of +cacheAsBitmap is restored.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. +In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, +and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels +wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, +the limitation is 2,880 pixels in height and 2,880 pixels in width. +For example, if you zoom in on a large movie clip with a filter applied, the +filter is turned off if the resulting image reaches the maximum dimensions.

+ +
The following example applies different color matrix filters to + an image file. The filter constructor calls + buildChild() four times to load and display four instances of the image. + The first call to buildChild() takes null as an argument, + applying no filter to the first instance. Each subsequent call to buildChild() + takes as an argument a function that applies a different color matrix filter to each + subsequent instance of the image. +

The buildChild() function creates a new Loader object named + loader. For each call to buildChild(), + attach an event listener to the Loader object to listen for complete events, + which are handled by the function passed to buildChild().

+ +

The applyRed(), applyGreen(), and applyBlue() + functions use different values for the matrix array to achieve different + effects.

+

Note: For best results, use an image approximately 80 pixels in width. + The name and location of the image file should match the value you pass to the + url property. For example, the value passed to url in the example + points to an image file named "Image.jpg" that is in the same directory as your SWF file. +

+ + +package { + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.filters.ColorMatrixFilter; + import flash.net.URLRequest; + + public class ColorMatrixFilterExample extends Sprite { + private var size:uint = 140; + private var url:String = "Image.jpg"; + + public function ColorMatrixFilterExample() { + buildChild(null); + buildChild(applyRed); + buildChild(applyGreen); + buildChild(applyBlue); + } + + private function buildChild(loadHandler:Function):void { + var loader:Loader = new Loader(); + loader.x = numChildren * size; + loader.y = size; + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + if (loadHandler != null) { + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadHandler); + } + + var request:URLRequest = new URLRequest(url); + loader.load(request); + addChild(loader); + } + + private function applyRed(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = new Array(); + matrix = matrix.concat([1, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 0, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 0, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + + applyFilter(child, matrix); + } + + private function applyGreen(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = new Array(); + matrix = matrix.concat([0, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 1, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 0, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + + applyFilter(child, matrix); + } + + private function applyBlue(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = new Array(); + matrix = matrix.concat([0, 0, 0, 0, 0]); // red + matrix = matrix.concat([0, 0, 0, 0, 0]); // green + matrix = matrix.concat([0, 0, 1, 0, 0]); // blue + matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha + + applyFilter(child, matrix); + } + + private function applyFilter(child:DisplayObject, matrix:Array):void { + var filter:ColorMatrixFilter = new ColorMatrixFilter(matrix); + var filters:Array = new Array(); + filters.push(filter); + child.filters = filters; + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load image: " + url); + } + } +} +
flash.display.BitmapData.getPixel()flash.display.BitmapData.applyFilter()flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapColorMatrixFilter + Initializes a new ColorMatrixFilter instance with the specified parameters.matrixArraynullAn array of 20 items arranged as a 4 x 5 matrix. + Initializes a new ColorMatrixFilter instance. + + + Initializes a new ColorMatrixFilter instance with the specified parameters. + + clone + Returns a copy of this filter object.A new ColorMatrixFilter instance with all of the same properties as the original + one. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + + matrix + An array of 20 items for 4 x 5 color transform.ArrayThe Array is null when being set + + TypeErrorTypeError + An array of 20 items for 4 x 5 color transform. The matrix property cannot + be changed by directly modifying its value (for example, myFilter.matrix[2] = 1;). + Instead, you must get a reference to the array, make the change to the reference, and reset the + value. + +

The color matrix filter separates each source pixel into its red, green, blue, + and alpha components as srcR, srcG, srcB, srcA. To calculate the result of each of + the four channels, the value of each pixel in the image is multiplied by the values in + the transformation matrix. An offset, between -255 and 255, can optionally be added + to each result (the fifth item in each row of the matrix). The filter combines each + color component back into a single pixel and writes out the result. In the following formula, + a[0] through a[19] correspond to entries 0 through 19 in the 20-item array that is + passed to the matrix property:

+
+	redResult   = (a[0]  ~~ srcR) + (a[1]  ~~ srcG) + (a[2]  ~~ srcB) + (a[3]  ~~ srcA) + a[4]
+	greenResult = (a[5]  ~~ srcR) + (a[6]  ~~ srcG) + (a[7]  ~~ srcB) + (a[8]  ~~ srcA) + a[9]
+	blueResult  = (a[10] ~~ srcR) + (a[11] ~~ srcG) + (a[12] ~~ srcB) + (a[13] ~~ srcA) + a[14]
+	alphaResult = (a[15] ~~ srcR) + (a[16] ~~ srcG) + (a[17] ~~ srcB) + (a[18] ~~ srcA) + a[19]
+	
+ +

For each color value in the array, a value of 1 is equal to 100% of that channel + being sent to the output, preserving the value of the color channel.

+ +

The calculations are performed on unmultiplied color values. If the input graphic consists + of premultiplied color values, those values are automatically converted into unmultiplied color + values for this operation.

+ +

Two optimized modes are available:

+ +

Alpha only. When you pass to the filter a matrix that adjusts only the alpha component, as shown here, the filter optimizes its performance:

+
+	    1 0 0 0 0
+	    0 1 0 0 0
+	    0 0 1 0 0
+	    0 0 0 N 0  (where N is between 0.0 and 1.0)
+	
+ +

Faster version. Available only with SSE/AltiVec accelerator-enabled processors, + such as Intel® Pentium® 3 and later and Apple® G4 and later. The accelerator is used when the multiplier terms are in the range + -15.99 to 15.99 and the adder terms a[4], a[9], a[14], and a[19] are in the range -8000 to 8000.

+ +
DisplacementMapFilter +The DisplacementMapFilter class uses the pixel values from the specified BitmapData object +(called the displacement map image) to perform a displacement of an object.Displaces the original object to which the filter is applied. +flash.filters:BitmapFilter +The DisplacementMapFilter class uses the pixel values from the specified BitmapData object +(called the displacement map image) to perform a displacement of an object. +You can use this filter to apply a warped +or mottled effect to any object that inherits from the DisplayObject class, +such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to a display object, use the +filters property of the display object. Setting the filters +property of an object does not modify the object, and you can remove the filter by clearing the +filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. +Calling applyFilter() on a BitmapData object takes the source BitmapData object +and the filter object and generates a filtered image.
+ +

If you apply a filter to a display object, the value of the cacheAsBitmap property of the +display object is set to true. If you clear all filters, the original value of +cacheAsBitmap is restored.

+ +

The filter uses the following formula:

+ + +dstPixel[x, y] = srcPixel[x + ((componentX(x, y) - 128) ~~ scaleX) / 256, y + ((componentY(x, y) - 128) ~~scaleY) / 256) + + +

where componentX(x, y) gets the componentX property color value +from the mapBitmap property at (x - mapPoint.x ,y - mapPoint.y).

+ +

The map image used by the filter is scaled to match the Stage scaling. +It is not scaled when the object itself is scaled.

+ +

This filter supports Stage scaling. However, general scaling, rotation, and +skewing are not supported. If the object itself is scaled (if the scaleX +and scaleY properties are set to a value other than 1.0), +the filter effect is not scaled. It is scaled only when the user zooms in on the Stage.

+ +
The following example draws a square with a radial gradient fill, creates a text field, + creates a BitmapData object, and applies a displacement map filter to the + DisplacementMapFilterExample object. The general workflow for this example is as follows: +
  1. The class defines variables for the background color, for the text field label, + and for the size and offset that will be used in various functions.
  2. The constructor function calls the draw() method, + which uses the methods of the Graphics class to draw a square with a radial gradient fill. + Note that graphics is a property of the DisplacementMapFilterExample object, + which extends Sprite.
  3. The constructor function calls the createLabel() method, which creates a text field + displaying the value of labelText and adds it to the display list.
  4. The constructor function calls the createFilter() method, which does the following: +
    • Creates a variable named filter for the filter object.
    • Calls the getDisplacementMapFilter() method and assigns its return value + to the filter variable.
    • Passes filter to the filters property of the + DisplacementFilterExample object (the main class).
    +
  5. The getBitmapFilter() method creates a BitmapData object + named mapBitmap and assigns it the results of + the createBitmapData() method. The mapBitmap object, + along with other variables, defines a new displacement map filter.
  6. The createBitmapData() method creates a new BitmapData object that is based on + the current contents of the DisplacementMapFilterExample object. It creates a new bitmap + based on bitmapData and adds the bitmap to the Stage.
+ +package { + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.BitmapDataChannel; + import flash.display.GradientType; + import flash.display.SpreadMethod; + import flash.display.Sprite; + import flash.filters.BitmapFilter; + import flash.filters.DisplacementMapFilter; + import flash.filters.DisplacementMapFilterMode; + import flash.geom.Matrix; + import flash.geom.Point; + import flash.text.TextField; + + public class DisplacementMapFilterExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 200; + private var offset:uint = 90; + private var labelText:String = "Watch the text bend with the displacement map"; + + public function DisplacementMapFilterExample() { + draw(); + createLabel(); + createFilter(); + } + + private function createFilter():void { + var filter:BitmapFilter = getBitmapFilter(); + filters = new Array(filter); + } + + private function getBitmapFilter():BitmapFilter { + var mapBitmap:BitmapData = createBitmapData(); + var mapPoint:Point = new Point(0, 0); + var channels:uint = BitmapDataChannel.RED; + var componentX:uint = channels; + var componentY:uint = channels; + var scaleX:Number = 0.5; + var scaleY:Number = -30; + var mode:String = DisplacementMapFilterMode.CLAMP; + var color:uint = 0; + var alpha:Number = 0; + return new DisplacementMapFilter(mapBitmap, + mapPoint, + componentX, + componentY, + scaleX, + scaleY, + mode, + color, + alpha); + } + + private function draw():void { + var matrix:Matrix = new Matrix(); + matrix.createGradientBox(size, size); + graphics.beginGradientFill(GradientType.RADIAL, + [0xFF0000, 0x0000FF], + [100, 100], + [55, 200], + matrix, + SpreadMethod.PAD); + graphics.drawRect(0, 0, size, size); + } + + private function createBitmapData():BitmapData { + var bitmapData:BitmapData = new BitmapData(size, size, true, bgColor); + bitmapData.draw(this, new Matrix()); + var bitmap:Bitmap = new Bitmap(bitmapData); + bitmap.x = size; + addChild(bitmap); + return bitmapData; + } + + private function createLabel():void { + var tf:TextField = new TextField(); + tf.text = labelText; + tf.y = offset; + tf.width = size; + addChild(tf); + } + } +} +
flash.display.BitmapData.applyFilter()flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapDisplacementMapFilter + Initializes a DisplacementMapFilter instance with the specified parameters.mapBitmapflash.display:BitmapDatanullA BitmapData object containing the displacement map data. + mapPointflash.geom:PointnullA value that contains the offset of the upper-left corner of the + target display object from the upper-left corner of the map image. + componentXuint0Describes which color channel to use in the map image to displace the x result. + Possible values are the BitmapDataChannel constants. + componentYuint0Describes which color channel to use in the map image to displace the y result. + Possible values are the BitmapDataChannel constants. + scaleXNumber0.0The multiplier to use to scale the x displacement result from the map calculation. + scaleYNumber0.0The multiplier to use to scale the y displacement result from the map calculation. + modeStringwrapThe mode of the filter. Possible values are the DisplacementMapFilterMode + constants. + coloruint0Specifies the color to use for out-of-bounds displacements. The valid range of + displacements is 0.0 to 1.0. Use this parameter if mode is set to DisplacementMapFilterMode.COLOR. + alphaNumber0.0Specifies what alpha value to use for out-of-bounds displacements. + It is specified as a normalized value from 0.0 to 1.0. For example, + .25 sets a transparency value of 25%. + Use this parameter if mode is set to DisplacementMapFilterMode.COLOR. + + Initializes a DisplacementMapFilter instance. + + + Initializes a DisplacementMapFilter instance with the specified parameters. + + flash.display.BitmapDataChannelflash.filters.DisplacementMapFilterModeclone + Returns a copy of this filter object.A new DisplacementMapFilter instance with all the same properties as the + original one. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + alpha + Specifies the alpha transparency value to use for out-of-bounds displacements.Number + Specifies the alpha transparency value to use for out-of-bounds displacements. + It is specified as a normalized value from 0.0 to 1.0. For example, + .25 sets a transparency value of 25%. The default value is 0. + Use this property if the mode property is set to DisplacementMapFilterMode.COLOR. + + color + Specifies what color to use for out-of-bounds displacements.uint + Specifies what color to use for out-of-bounds displacements. The valid range of + displacements is 0.0 to 1.0. Values are in hexadecimal format. The default value + for color is 0. Use this property if the mode property + is set to DisplacementMapFilterMode.COLOR. + + componentX + Describes which color channel to use in the map image to displace the x result.uintThe color channel to use to displace the x result. + + + Describes which color channel to use in the map image to displace the x result. + Possible values are BitmapDataChannel constants: +
  • BitmapDataChannel.ALPHA
  • BitmapDataChannel.BLUE
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.RED
+ +
flash.display.BitmapDataChannel
componentY + Describes which color channel to use in the map image to displace the y result.uint + Describes which color channel to use in the map image to displace the y result. + Possible values are BitmapDataChannel constants: +
  • BitmapDataChannel.ALPHA
  • BitmapDataChannel.BLUE
  • BitmapDataChannel.GREEN
  • BitmapDataChannel.RED
+
flash.display.BitmapDataChannel
mapBitmap + A BitmapData object containing the displacement map data.flash.display:BitmapDataThe BitmapData is null when being set + + TypeErrorTypeError + A BitmapData object containing the displacement map data. + + flash.display.BitmapDatamapPoint + A value that contains the offset of the upper-left corner of + the target display object from the upper-left corner of the map image.flash.geom:PointThe Point is null when being set + + TypeErrorTypeError + A value that contains the offset of the upper-left corner of + the target display object from the upper-left corner of the map image. + + flash.geom.Pointmode + The mode for the filter.StringThe String is null when being set + TypeErrorTypeErrorThe mode string is not one of the valid types + + ArgumentErrorArgumentError + The mode for the filter. Possible values are DisplacementMapFilterMode + constants: +
  • DisplacementMapFilterMode.WRAP — Wraps the displacement value to the other side of the source image.
  • DisplacementMapFilterMode.CLAMP — Clamps the displacement value to the edge of the source image.
  • DisplacementMapFilterMode.IGNORE — If the displacement value is out of range, ignores the displacement and uses the source pixel.
  • DisplacementMapFilterMode.COLOR — If the displacement value is outside the image, substitutes the values in the color and alpha properties.
+ +
flash.filters.DisplacementMapFilterMode
scaleX + The multiplier to use to scale the x displacement result from the map calculation.Number + The multiplier to use to scale the x displacement result from the map calculation. + scaleY + The multiplier to use to scale the y displacement result from the map calculation.Number + The multiplier to use to scale the y displacement result from the map calculation. + +
BitmapFilterType +The BitmapFilterType class contains values to set the type of a BitmapFilter.Object +The BitmapFilterType class contains values to set the type of a BitmapFilter. + + The following example draws a gray square and applies a BevelFilter object to it. + The example sets the type property by using the constant BitmapFilterType.HIGH. + + +package { + import flash.display.Sprite; + import flash.filters.BevelFilter; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BitmapFilterType; + + public class BitmapFilterTypeExample extends Sprite { + private var bgColor:uint = 0x999999; + private var size:uint = 80; + private var offset:uint = 50; + + public function BitmapFilterTypeExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + var distance:Number = 5; + var angleInDegrees:Number = 45; + var highlightColor:Number = 0xCCCCCC; + var highlightAlpha:Number = 0.8; + var shadowColor:Number = 0x808080; + var shadowAlpha:Number = 0.8; + var blurX:Number = 5; + var blurY:Number = 5; + var strength:Number = 5; + var quality:Number = BitmapFilterQuality.HIGH; + var type:String = BitmapFilterType.INNER; + var knockout:Boolean = false; + + return new BevelFilter(distance, + angleInDegrees, + highlightColor, + highlightAlpha, + shadowColor, + shadowAlpha, + blurX, + blurY, + strength, + quality, + type, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +BevelFilterGradientBevelFilterGradientGlowFilterFULL + Defines the setting that applies a filter to the entire area of an object.fullString + Defines the setting that applies a filter to the entire area of an object. + + INNER + Defines the setting that applies a filter to the inner area of an object.innerString + Defines the setting that applies a filter to the inner area of an object. + + OUTER + Defines the setting that applies a filter to the outer area of an object.outerString + Defines the setting that applies a filter to the outer area of an object. + + DropShadowFilter +The DropShadowFilter class lets you add a drop shadow to display objects.flash.filters:BitmapFilter +The DropShadowFilter class lets you add a drop shadow to display objects. +The shadow algorithm is based on the same box filter that the blur filter uses. You have +several options for the style of the drop shadow, including inner or outer shadow and knockout mode. +You can apply the filter to any display object (that is, objects that inherit from the DisplayObject class), +such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to display objects use the + filters property (inherited from DisplayObject). Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the value of the cacheAsBitmap property of the +display object is set to true. If you clear all filters, the original value of +cacheAsBitmap is restored.

+

This filter supports Stage scaling. However, it does not support general scaling, rotation, and + skewing. If the object itself is scaled (if scaleX and scaleY are + set to a value other than 1.0), the filter is not scaled. It is scaled only when + the user zooms in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + If, for example, you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example creates a yellow square and applies a drop shadow to it. + The general workflow of this example is as follows: +
  1. Declare three properties that are used to draw the square to which the + filter is applied.
  2. Create the constructor function. The constructor calls the draw() method, + which uses methods of the Graphics class accessed through the graphics + property of Sprite to draw an orange square.
  3. In the constructor, declare a variable filter as a BitmapFilter object + and assign it to the return value of a call to getBitmapFilter(). + The getBitmapFilter() method defines the drop shadow filter used.
  4. Create a new Array object myFilters and add filter to + the array. Assign the myFilters array to the filters property of + the DropShadowFilterExample object. This applies all filters found in myFilters, which in this case + is only filter.
+ + +package { + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.DropShadowFilter; + + public class DropShadowFilterExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + private var offset:uint = 50; + + public function DropShadowFilterExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + var color:Number = 0x000000; + var angle:Number = 45; + var alpha:Number = 0.8; + var blurX:Number = 8; + var blurY:Number = 8; + var distance:Number = 15; + var strength:Number = 0.65; + var inner:Boolean = false; + var knockout:Boolean = false; + var quality:Number = BitmapFilterQuality.HIGH; + return new DropShadowFilter(distance, + angle, + color, + alpha, + blurX, + blurY, + strength, + quality, + inner, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
flash.display.BitmapData.applyFilter()flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapDropShadowFilter + Creates a new DropShadowFilter instance with the specified parameters.distanceNumber4.0Offset distance for the shadow, in pixels. + + angleNumber45Angle of the shadow, 0 to 360 degrees (floating point). + + coloruint0Color of the shadow, in hexadecimal format + 0xRRGGBB. The default value is 0x000000. + + alphaNumber1.0Alpha transparency value for the shadow color. Valid values are 0.0 to 1.0. + For example, + .25 sets a transparency value of 25%. + + blurXNumber4.0Amount of horizontal blur. Valid values are 0 to 255.0 (floating point). + + blurYNumber4.0Amount of vertical blur. Valid values are 0 to 255.0 (floating point). + + strengthNumber1.0The strength of the imprint or spread. The higher the value, + the more color is imprinted and the stronger the contrast between the shadow and the background. + Valid values are 0 to 255.0. + + qualityint1The number of times to apply the filter. Use the BitmapFilterQuality constants: +
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

For more information about these values, see the quality property description.

+ +
innerBooleanfalseIndicates whether or not the shadow is an inner shadow. A value of true specifies + an inner shadow. A value of false specifies an outer shadow (a + shadow around the outer edges of the object). + + knockoutBooleanfalseApplies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document. + + hideObjectBooleanfalseIndicates whether or not the object is hidden. A value of true + indicates that the object itself is not drawn; only the shadow is visible. + +
+ Creates a new DropShadowFilter instance with the specified parameters. +
flash.filters.BitmapFilterQuality
clone + Returns a copy of this filter object.A new DropShadowFilter instance with all the + properties of the original DropShadowFilter instance. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + alpha + The alpha transparency value for the shadow color.Number + The alpha transparency value for the shadow color. Valid values are 0.0 to 1.0. + For example, + .25 sets a transparency value of 25%. The default value is 1.0. + + angle + The angle of the shadow.Number + The angle of the shadow. Valid values are 0 to 360 degrees (floating point). The + default value is 45. + + blurX + The amount of horizontal blur.Number + The amount of horizontal blur. Valid values are 0 to 255.0 (floating point). The + default value is 4.0. + + blurY + The amount of vertical blur.Number + The amount of vertical blur. Valid values are 0 to 255.0 (floating point). The + default value is 4.0. + + color + The color of the shadow.uint + The color of the shadow. Valid values are in hexadecimal format 0xRRGGBB. The + default value is 0x000000. + + distance + The offset distance for the shadow, in pixels.Number + The offset distance for the shadow, in pixels. The default + value is 4.0 (floating point). + + hideObject + Indicates whether or not the object is hidden.Boolean + Indicates whether or not the object is hidden. The value true + indicates that the object itself is not drawn; only the shadow is visible. + The default is false (the object is shown). + + inner + Indicates whether or not the shadow is an inner shadow.Boolean + Indicates whether or not the shadow is an inner shadow. The value true indicates + an inner shadow. The default is false, an outer shadow (a + shadow around the outer edges of the object). + + knockout + Applies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document.Boolean + Applies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document. The + default is false (no knockout). + + quality + The number of times to apply the filter.int + The number of times to apply the filter. + The default value is BitmapFilterQuality.LOW, which is equivalent to applying + the filter once. The value BitmapFilterQuality.MEDIUM applies the filter twice; + the value BitmapFilterQuality.HIGH applies it three times. Filters with lower values + are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing + the values of the blurX and blurY properties.

+
flash.filters.BitmapFilterQuality
strength + The strength of the imprint or spread.Number + The strength of the imprint or spread. The higher the value, + the more color is imprinted and the stronger the contrast between the shadow and the background. + Valid values are from 0 to 255.0. The default is 1.0. + +
BitmapFilterQuality +The BitmapFilterQuality class contains values to set the rendering quality of a BitmapFilter object.Object +The BitmapFilterQuality class contains values to set the rendering quality of a BitmapFilter object. + + The following example draws a gray square and applies a BevelFilter object to it. + The example sets the quality property by using the + constant BitmapFilterQuality.HIGH. + + +package { + import flash.display.Sprite; + import flash.filters.BevelFilter; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BitmapFilterType; + + public class BitmapFilterQualityExample extends Sprite { + private var bgColor:uint = 0x999999; + private var size:uint = 80; + private var offset:uint = 50; + + public function BitmapFilterQualityExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + var distance:Number = 5; + var angleInDegrees:Number = 45; + var highlightColor:Number = 0xCCCCCC; + var highlightAlpha:Number = 0.8; + var shadowColor:Number = 0x808080; + var shadowAlpha:Number = 0.8; + var blurX:Number = 5; + var blurY:Number = 5; + var strength:Number = 5; + var quality:Number = BitmapFilterQuality.HIGH; + var type:String = BitmapFilterType.INNER; + var knockout:Boolean = false; + + return new BevelFilter(distance, + angleInDegrees, + highlightColor, + highlightAlpha, + shadowColor, + shadowAlpha, + blurX, + blurY, + strength, + quality, + type, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +BevelFilterBlurFilterGlowFilterDropShadowFilterGradientBevelFilterGradientGlowFilterHIGH + Defines the high quality filter setting.3int + Defines the high quality filter setting. + + LOW + Defines the low quality filter setting.1int + Defines the low quality filter setting. + + MEDIUM + Defines the medium quality filter setting.2int + Defines the medium quality filter setting. + + DisplacementMapFilterMode +The DisplacementMapFilterMode class provides values for the mode property +of the DisplacementMapFilter class.Object +The DisplacementMapFilterMode class provides values for the mode property +of the DisplacementMapFilter class. + +CLAMP + Clamps the displacement value to the edge of the source image.clampString + Clamps the displacement value to the edge of the source image. + + Use with the DisplacementMapFilter.mode property. + + flash.filters.DisplacementMapFilter.modeCOLOR + If the displacement value is outside the image, substitutes the values in + the color and alpha properties.colorString + If the displacement value is outside the image, substitutes the values in + the color and alpha properties. + + Use with the DisplacementMapFilter.mode property. + + flash.filters.DisplacementMapFilter.modeIGNORE + If the displacement value is out of range, ignores the displacement and uses the source pixel.ignoreString + If the displacement value is out of range, ignores the displacement and uses the source pixel. + + Use with the DisplacementMapFilter.mode property. + + flash.filters.DisplacementMapFilter.modeWRAP + Wraps the displacement value to the other side of the source image.wrapString + Wraps the displacement value to the other side of the source image. + Use with the DisplacementMapFilter.mode property. + + flash.filters.DisplacementMapFilter.modeBevelFilter + The BevelFilter class lets you add a bevel effect to display objects.Adds a bevel effect. + + flash.filters:BitmapFilter + The BevelFilter class lets you add a bevel effect to display objects. + A bevel effect gives objects such as buttons a three-dimensional look. You can customize + the look of the bevel with different highlight and shadow colors, the amount + of blur on the bevel, the angle of the bevel, the placement of the bevel, + and a knockout effect. + You can apply the filter to any display object (that is, objects that inherit from the + DisplayObject class), such as MovieClip, SimpleButton, TextField, and Video objects, + as well as to BitmapData objects. + +

To create a new filter, use the constructor new BevelFilter(). + The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to movie clips, text fields, buttons, and video, use the + filters property (inherited from DisplayObject). Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the value of the cacheAsBitmap property of the + object is set to true. If you remove all filters, the original value of + cacheAsBitmap is restored.

+ +

This filter supports Stage scaling. However, it does not support general scaling, rotation, and + skewing. If the object itself is scaled (if the scaleX and scaleY properties are + not set to 100%), the filter is not scaled. It is scaled only when the user zooms in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + If, for example, you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example creates a dark yellow square and applies a bevel with a + bright yellow (0xFFFF00) highlight and a blue (0x0000FF) shadow. The general workflow for this + example is as follows: +
  1. Import the required classes.
  2. Declare three properties used in the draw() function, which draws the + object to which the bevel filter is applied.
  3. Create the BevelFilterExample() constructor function, which does the following: +
    • Calls the draw() function, which is declared later.
    • Declares a variable filter as a BitmapFilter object + and assigns it to the return of a call to getBitmapFilter().
    • Creates a new Array object myFilters and adds filter to + the array, and assigns myFilters to the filters property of + BevelFilterExample object. This applies all filters found in myFilters, which in this case + is only filter.
    +
  4. Create the getBitmapFilter function to create and set properties for the filter.
  5. Create the draw() function. This function + uses methods of the Graphics class, accessed through the graphics property + of the Sprite class, to draw the square.
+ +package { + import flash.display.Sprite; + import flash.filters.BevelFilter; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BitmapFilterType; + + public class BevelFilterExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + private var offset:uint = 50; + + public function BevelFilterExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + var distance:Number = 5; + var angleInDegrees:Number = 45; + var highlightColor:Number = 0xFFFF00; + var highlightAlpha:Number = 0.8; + var shadowColor:Number = 0x0000FF; + var shadowAlpha:Number = 0.8; + var blurX:Number = 5; + var blurY:Number = 5; + var strength:Number = 5; + var quality:Number = BitmapFilterQuality.HIGH; + var type:String = BitmapFilterType.INNER; + var knockout:Boolean = false; + + return new BevelFilter(distance, + angleInDegrees, + highlightColor, + highlightAlpha, + shadowColor, + shadowAlpha, + blurX, + blurY, + strength, + quality, + type, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapflash.display.BitmapData.applyFilter()BevelFilter + Initializes a new BevelFilter instance with the specified parameters.distanceNumber4.0The offset distance of the bevel, in pixels (floating point). + angleNumber45The angle of the bevel, from 0 to 360 degrees. + highlightColoruint0xFFFFFFThe highlight color of the bevel, 0xRRGGBB. + highlightAlphaNumber1.0The alpha transparency value of the highlight color. Valid values are 0.0 to + 1.0. For example, + .25 sets a transparency value of 25%. + shadowColoruint0x000000The shadow color of the bevel, 0xRRGGBB. + shadowAlphaNumber1.0The alpha transparency value of the shadow color. Valid values are 0.0 to 1.0. For example, + .25 sets a transparency value of 25%. + blurXNumber4.0The amount of horizontal blur in pixels. Valid values are 0 to 255.0 (floating point). + blurYNumber4.0The amount of vertical blur in pixels. Valid values are 0 to 255.0 (floating point). + strengthNumber1The strength of the imprint or spread. The higher the value, the more color is imprinted and the stronger the contrast between the bevel and the background. Valid values are 0 to 255.0. + qualityint1The quality of the bevel. Valid values are 0 to 15, but for most applications, + you can use BitmapFilterQuality constants: +
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

Filters with lower values render faster. You can use + the other available numeric values to achieve different effects.

+ +
typeStringinnerThe type of bevel. Valid values are BitmapFilterType constants: + BitmapFilterType.INNER, BitmapFilterType.OUTER, or + BitmapFilterType.FULL. + knockoutBooleanfalseApplies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document. + +
+ Initializes a new BevelFilter instance with the specified parameters. + +
BitmapFilterQualityBitmapFilterType
clone + Returns a copy of this filter object.A new BevelFilter instance with all the same properties as + the original BevelFilter instance. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + + angle + The angle of the bevel.Number + The angle of the bevel. Valid values are from 0 to 360°. The default value is 45°. + +

The angle value represents the angle of the theoretical light source falling on the object + and determines the placement of the effect relative to the object. If the distance + property is set to 0, the effect is not offset from the object and, therefore, + the angle property has no effect.

+ +
blurX + The amount of horizontal blur, in pixels.Number + The amount of horizontal blur, in pixels. Valid values are from 0 to 255 (floating point). + The default value is 4. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) are optimized + to render more quickly than other values. + + blurY + The amount of vertical blur, in pixels.Number + The amount of vertical blur, in pixels. Valid values are from 0 to 255 (floating point). + The default value is 4. Values that are a power of 2 (such as 2, 4, 8, 16, and 32) are optimized + to render more quickly than other values. + + distance + The offset distance of the bevel.Number + The offset distance of the bevel. Valid values are in pixels (floating point). The default is 4. + + highlightAlpha + The alpha transparency value of the highlight color.Number + The alpha transparency value of the highlight color. The value is specified as a normalized + value from 0 to 1. For example, + .25 sets a transparency value of 25%. The default value is 1. + + highlightColor + The highlight color of the bevel.uint + The highlight color of the bevel. Valid values are in hexadecimal format, + 0xRRGGBB. The default is 0xFFFFFF. + knockout + Applies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document.Boolean + Applies a knockout effect (true), which effectively + makes the object's fill transparent and reveals the background color of the document. The + default value is false (no knockout). + + quality + The number of times to apply the filter.int + The number of times to apply the filter. The default value is BitmapFilterQuality.LOW, + which is equivalent to applying the filter once. The value BitmapFilterQuality.MEDIUM + applies the filter twice; the value BitmapFilterQuality.HIGH applies it three times. + Filters with lower values are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing the values + of the blurX and blurY properties.

+ +

You can use the following BitmapFilterQuality constants to specify values of the quality property: +

  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

+ +
shadowAlpha + The alpha transparency value of the shadow color.Number + The alpha transparency value of the shadow color. This value is specified as a normalized + value from 0 to 1. For example, + .25 sets a transparency value of 25%. The default is 1. + + shadowColor + The shadow color of the bevel.uint + The shadow color of the bevel. Valid values are in hexadecimal format, 0xRRGGBB. The default + is 0x000000. + + strength + The strength of the imprint or spread.Number + The strength of the imprint or spread. Valid values are from 0 to 255. The larger the value, + the more color is imprinted and the stronger the contrast between the bevel and the background. + The default value is 1. + + type + The placement of the bevel on the object.StringThe string is null when being set + + TypeErrorTypeError + The placement of the bevel on the object. Inner and outer bevels are placed on + the inner or outer edge; a full bevel is placed on the entire object. + Valid values are the BitmapFilterType constants: + +
  • BitmapFilterType.INNER
  • BitmapFilterType.OUTER
  • BitmapFilterType.FULL
+ +
BitmapFilter + The BitmapFilter class is the base class for all image filter effects.Base class for all image filter effects. + Object + The BitmapFilter class is the base class for all image filter effects. + +

The BevelFilter, BlurFilter, ColorMatrixFilter, ConvolutionFilter, DisplacementMapFilter, + DropShadowFilter, GlowFilter, GradientBevelFilter, and GradientGlowFilter classes all extend the + BitmapFilter class. You can apply these filter effects to any display object.

+ +

You can neither directly instantiate nor extend BitmapFilter.

+ +
The following example shows how several filters may be applied to a given + DisplayObject object and tracked using the filters property. + +package { + import flash.display.Sprite; + import flash.filters.*; + + public class BitmapFilterExample extends Sprite { + public function BitmapFilterExample() { + trace(this.filters.length); // 0 + + var tmpFilters:Array = this.filters; + tmpFilters.push(FilterFactory.createFilter(FilterFactory.BEVEL_FILTER)); + tmpFilters.push(FilterFactory.createFilter(FilterFactory.GLOW_FILTER)); + this.filters = tmpFilters; + + trace(this.filters.length); // 2 + trace(this.filters[0] is BitmapFilter); // true + trace(this.filters[0] is BevelFilter); // true + trace(this.filters[1] is BitmapFilter); // true + trace(this.filters[1] is GlowFilter); // true + } + } +} + +import flash.filters.*; +class FilterFactory { + public static var BEVEL_FILTER:String = "BevelFilter"; + public static var BevelFilterConstructor:Class = BevelFilter; + + public static var BLUR_FILTER:String = "BlurFilter"; + public static var BlurFilterConstructor:Class = BlurFilter; + + public static var COLOR_MATRIX_FILTER:String = "ColorMatrixFilter"; + public static var ColorMatrixFilterConstructor:Class = ColorMatrixFilter; + + public static var CONVOLUTION_FILTER:String = "ConvolutionFilter"; + public static var ConvolutionFilterConstructor:Class = ConvolutionFilter; + + public static var DISPLACEMENT_MAP_FILTER:String = "DisplacementMapFilter"; + public static var DisplacementMapFilterConstructor:Class = DisplacementMapFilter; + + public static var DROP_SHADOW_FILTER:String = "DropShadowFilter"; + public static var DropShadowFilterConstructor:Class = DropShadowFilter; + + public static var GLOW_FILTER:String = "GlowFilter"; + public static var GlowFilterConstructor:Class = GlowFilter; + + public static var GRADIENT_BEVEL_FILTER:String = "GradientBevelFilter"; + public static var GradientBevelFilterConstructor:Class = GradientBevelFilter; + + public static var GRADIENT_GLOW_FILTER:String = "GradientGlowFilter"; + public static var GradientGlowFilterConstructor:Class = GradientGlowFilter; + + public static function createFilter(type:String):BitmapFilter { + return new FilterFactory[type + "Constructor"](); + } +} +
clone + Returns a BitmapFilter object that is an exact copy of the original + BitmapFilter object.A BitmapFilter object. + + flash.filters:BitmapFilterA copy of the BitmapFilter object. + + Returns a BitmapFilter object that is an exact copy of the original + BitmapFilter object. + +
BlurFilter + The BlurFilter class lets you apply a blur visual effect to display objects.A blur effect. + + flash.filters:BitmapFilter + The BlurFilter class lets you apply a blur visual effect to display objects. + A blur effect softens the details of an image. You can produce blurs that + range from a softly unfocused look to a Gaussian blur, a hazy + appearance like viewing an image through semi-opaque glass. When the quality property + of this filter is set to low, the result is a softly unfocused look. + When the quality property is set to high, it approximates a Gaussian blur + filter. You can apply the filter to any display object (that is, objects that inherit + from the DisplayObject class), + such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

To create a new filter, use the constructor new BlurFilter(). + The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to movie clips, text fields, buttons, and video, use the + filters property (inherited from DisplayObject). Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the cacheAsBitmap property of the + display object is set to true. If you remove all filters, the original value of + cacheAsBitmap is restored.

+ +

This filter supports Stage scaling. However, it does not support general scaling, + rotation, and skewing. If the object itself is scaled (scaleX and scaleY are not set to 100%), the + filter effect is not scaled. It is scaled only when the user zooms in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + If, for example, you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example creates a dark yellow square and applies a Gaussian-style blur filter + to it. The general workflow for this example is as follows: +
  1. Import the required classes.
  2. Declare three properties used in the draw() function, which draws the object + to which the blur filter is applied.
  3. Create the BlurFilterExample() constructor function, which does the following: +
    • Calls the draw() function, which is declared later.
    • Declares a filter variable as a BitmapFilter object + and assigns it to the return of a call to getBitmapFilter().
    • Creates a new Array object myFilters and adds filter to + the array, and assigns myFilters to the filters property of + the BlurFilterExample object. This applies all filters found in myFilters, which in this case + is only filter.
    +
  4. Create the getBitmapFilter() function to create and set properties for the filter.
  5. Create the draw() function. This function + uses methods of the Graphics class, accessed through the graphics property + of the Sprite class, to draw the square.
+ + +package { + import flash.display.Sprite; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BlurFilter; + + public class BlurFilterExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + private var offset:uint = 50; + + public function BlurFilterExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + var blurX:Number = 30; + var blurY:Number = 30; + return new BlurFilter(blurX, blurY, BitmapFilterQuality.HIGH); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapflash.display.BitmapData.applyFilter()BlurFilter + Initializes the filter with the specified parameters.blurXNumber4.0The amount to blur horizontally. Valid values are from 0 to 255.0 (floating-point + value). + blurYNumber4.0The amount to blur vertically. Valid values are from 0 to 255.0 (floating-point + value). + qualityint1The number of times to apply the filter. You can specify the quality using + the BitmapFilterQuality constants: +
  • flash.filters.BitmapFilterQuality.LOW
  • flash.filters.BitmapFilterQuality.MEDIUM
  • flash.filters.BitmapFilterQuality.HIGH
+

High quality approximates a Gaussian blur. + For most applications, these three values are sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, be aware + that higher values are rendered more slowly.

+ +
Initializes the filter. +
+ Initializes the filter with the specified parameters. + + The default values create a soft, unfocused image. + +
clone + Returns a copy of this filter object.A new BlurFilter instance with all the same + properties as the original BlurFilter instance. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + blurX + The amount of horizontal blur.Number + The amount of horizontal blur. Valid values are from 0 to 255 (floating point). The + default value is 4. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + blurY + The amount of vertical blur.Number + The amount of vertical blur. Valid values are from 0 to 255 (floating point). The + default value is 4. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + quality + The number of times to perform the blur.int + The number of times to perform the blur. The default value is BitmapFilterQuality.LOW, + which is equivalent to applying the filter once. The value BitmapFilterQuality.MEDIUM + applies the filter twice; the value BitmapFilterQuality.HIGH applies it three times + and approximates a Gaussian blur. Filters with lower values are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to increase the number of times the blur + is applied, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing the values + of the blurX and blurY properties.

+ +

You can use the following BitmapFilterQuality constants to specify values of the + quality property:

+
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+ +
GradientBevelFilter +The GradientBevelFilter class lets you apply a gradient bevel effect to +display objects.Lets you apply a gradient bevel effect. +flash.filters:BitmapFilter +The GradientBevelFilter class lets you apply a gradient bevel effect to +display objects. A gradient bevel is a beveled edge, enhanced with gradient color, +on the outside, inside, or top of an object. Beveled edges make objects look +three-dimensional. +You can apply the filter to any display object (that is, objects that inherit from the DisplayObject class), +such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to display objects, use the + filters property. Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the cacheAsBitmap property of the +display object is set to true. If you clear all filters, the original value of +cacheAsBitmap is restored.

+ +

This filter supports Stage scaling. However, it does not support general scaling, rotation, +and skewing; if the object itself is scaled (if scaleX and scaleY are set +to a value other than 1.0), the +filter effect is not scaled. It is scaled only when the user zooms in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. +In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, +and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels +wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, +the limitation is 2,880 pixels in height and 2,880 pixels in width. +For example, if you zoom in on a large movie clip with a filter applied, the filter is +turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example draws a square and applies a gradient bevel filter to it. + The general workflow of this example is as follows: +
  1. Import the required classes.
  2. Declare global variables to define the square and the filter.
  3. Create the constructor functions, which does the following: +
    • Calls the draw() method, which uses methods of the Graphics class + accessed through the graphics property of Sprite to draw a gray square.
    • Creates a BitmapFilter object named filter and assigns it + the return value of a call to getBitmapFilter(), which creates the filter.
    • Creates a new array named myFilters and adds filter to it.
    • Assigns myFilters to the filters property of the + GradientBevelFilterExample object. This applies all filters found in myFilters, which in this case + is only filter.
    +
+ + +package { + import flash.display.Sprite; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.BitmapFilterType; + import flash.filters.GradientBevelFilter; + + public class GradientBevelFilterExample extends Sprite { + private var bgColor:uint = 0xCCCCCC; + private var size:uint = 80; + private var offset:uint = 50; + private var distance:Number = 5; + private var angleInDegrees:Number = 225; // opposite 45 degrees + private var colors:Array = [0xFFFFFF, 0xCCCCCC, 0x000000]; + private var alphas:Array = [1, 0, 1]; + private var ratios:Array = [0, 128, 255]; + private var blurX:Number = 8; + private var blurY:Number = 8; + private var strength:Number = 2; + private var quality:Number = BitmapFilterQuality.HIGH + private var type:String = BitmapFilterType.INNER; + private var knockout:Boolean = true; + + public function GradientBevelFilterExample() { + draw(); + var filter:BitmapFilter = getBitmapFilter(); + var myFilters:Array = new Array(); + myFilters.push(filter); + filters = myFilters; + } + + private function getBitmapFilter():BitmapFilter { + return new GradientBevelFilter(distance, + angleInDegrees, + colors, + alphas, + ratios, + blurX, + blurY, + strength, + quality, + type, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
GradientBevelFilter.ratiosflash.display.BitmapData.applyFilter()BevelFilterflash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapGradientBevelFilter + Initializes the filter with the specified parameters.distanceNumber4.0The offset distance. Valid values are 0 to 8. + angleNumber45The angle, in degrees. Valid values are 0 to 360. + colorsArraynullAn array of RGB hexadecimal color values to use in the gradient. + For example, red is 0xFF0000, blue is 0x0000FF, and so on. + alphasArraynullAn array of alpha transparency values for the corresponding colors in + the colors array. Valid values for each element in the array are 0 to 1. + For example, .25 sets a transparency value of 25%. + ratiosArraynullAn array of color distribution ratios; valid values are + 0 to 255. + blurXNumber4.0The amount of horizontal blur. Valid values are 0 to 255. A blur of 1 or + less means that the original image is copied as is. The default value + is 4. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + blurYNumber4.0The amount of vertical blur. Valid values are 0 to 255. A blur of 1 or less + means that the original image is copied as is. Values that are a power of 2 + (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + strengthNumber1The strength of the imprint or spread. The higher the value, the more color + is imprinted and the stronger the contrast between the bevel and the background. + Valid values are 0 to 255. A value of 0 means that the filter is not applied. + + qualityint1The quality of the filter. Use BitmapFilterQuality constants: +
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

For more information, see the description of the quality property.

+ +
typeStringinnerThe placement of the bevel effect. Possible values are BitmapFilterType constants: +
  • BitmapFilterType.OUTER — Bevel on the outer edge of the object
  • BitmapFilterType.INNER — Bevel on the inner edge of the object
  • BitmapFilterType.FULL — Bevel on top of the object
+
knockoutBooleanfalseSpecifies whether a knockout effect is applied. The value true + makes the object's fill transparent and reveals the background color of the document. + +
+ Initializes the filter with the specified parameters. +
GradientBevelFilter.qualityGradientBevelFilter.ratios
clone + Returns a copy of this filter object.A new GradientBevelFilter instance with all the + same properties as the original GradientBevelFilter instance. + flash.filters:BitmapFilter + Returns a copy of this filter object. + alphas + An array of alpha transparency values for the corresponding colors in the + colors array.ArrayThe Array is null when being set + + TypeErrorTypeErrorAn array of alpha values. + + An array of alpha transparency values for the corresponding colors in the + colors array. Valid values for each element + in the array are 0 to 1. For example, .25 sets a transparency value of 25%. + +

The alphas property cannot be changed by directly modifying its values. + Instead, you must get a reference to alphas, make the change to the + reference, and then set alphas to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +
GradientBevelFilter.colorsGradientBevelFilter.ratios
angle + The angle, in degrees.Number + The angle, in degrees. Valid values are 0 to 360. The default is 45. + +

The angle value represents the angle of the theoretical light source falling on the object. + The value determines the angle at which the gradient colors are applied to the object: + where the highlight and the shadow appear, or where the first color in the array appears. + The colors are then applied in the order in which they appear in the array.

+ +
GradientBevelFilter.ratios
blurX + The amount of horizontal blur.Number + The amount of horizontal blur. Valid values are 0 to 255. A blur of 1 or + less means that the original image is copied as is. The default value + is 4. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + blurY + The amount of vertical blur.Number + The amount of vertical blur. Valid values are 0 to 255. A blur of 1 or less + means that the original image is copied as is. The default value is + 4. Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + + colors + An array of RGB hexadecimal color values to use in the gradient.ArrayThe Array is null when being set + + TypeErrorTypeErrorAn array of RGB hexadecimal color values. + + An array of RGB hexadecimal color values to use in the gradient. + For example, red is 0xFF0000, blue is 0x0000FF, and so on. + +

The colors property cannot be changed by directly modifying its values. + Instead, you must get a reference to colors, make the change to the + reference, and then set colors to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +
GradientBevelFilter.alphasGradientBevelFilter.ratios
distance + The offset distance.Number + The offset distance. Valid values are 0 to 8. The default value is 4.0. + + + knockout + Specifies whether the object has a knockout effect.Boolean + Specifies whether the object has a knockout effect. A knockout effect + makes the object's fill transparent and reveals the background color of the document. + The value true specifies a knockout effect; + the default is false (no knockout effect). + + quality + The number of times to apply the filter.int + The number of times to apply the filter. The default value is BitmapFilterQuality.LOW, + which is equivalent to applying the filter once. The value BitmapFilterQuality.MEDIUM + applies the filter twice; the value BitmapFilterQuality.HIGH applies it three times. + Filters with lower values are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing the values + of the blurX and blurY properties.

+ +
BitmapFilterQualityGradientBevelFilter.ratios
ratios + An array of color distribution ratios for the corresponding colors in the + colors array.ArrayThe Array is null when being set + + TypeErrorTypeError + An array of color distribution ratios for the corresponding colors in the + colors array. Valid values for each element + in the array are 0 to 255. + +

The ratios property cannot be changed by directly modifying its values. + Instead, you must get a reference to ratios, make the change to the + reference, and then set ratios to the reference.

+ +

The colors, alphas, and ratios properties are related. + The first element in the colors array + corresponds to the first element in the alphas array + and in the ratios array, and so on.

+ +

To understand how the colors in a gradient bevel are distributed, think first of the colors + that you want in your gradient bevel. Consider that a simple bevel has a highlight color and shadow + color; a gradient bevel has a highlight gradient and a shadow gradient. Assume that the highlight + appears on the top-left corner, and the shadow appears on the bottom-right corner. Assume that one + possible usage of the filter has four colors in the highlight and four in the shadow. In addition + to the highlight and shadow, the filter uses a base fill color that appears where the edges of the + highlight and shadow meet. Therefore the total number of colors is nine, and the corresponding number + of elements in the ratios array is nine.

+ +

If you think of a gradient as composed of stripes of various colors, blending into each other, + each ratio value sets the position of the color on the radius of the gradient, where 0 represents + the outermost point of the gradient and 255 represents the innermost point of the gradient. + For a typical usage, + the middle value is 128, and that is the base fill value. To get the bevel effect shown in the + image below, assign the + ratio values as follows, using the example of nine colors:

+ +
  • The first four colors range from 0-127, increasing in value so that each value is greater than + or equal to the previous one. This is the highlight bevel edge.
  • The fifth color (the middle color) is the base fill, set to 128. The pixel value of 128 + sets the base fill, which appears either outside the shape (and around the bevel edges) if the type + is set to outer; or inside the shape, effectively covering the object's own fill, if the type + is set to inner.
  • The last four colors range from 129-255, increasing in value so that each value + is greater than or equal to the previous one. This is the shadow bevel edge.
+ +

If you want an equal distribution of colors for each edge, use an odd number of colors, + where the middle color is the base fill. Distribute the values between 0-127 and 129-255 + equally among your colors, then adjust the value to change the width of each stripe of color + in the gradient. For a gradient bevel with nine colors, a possible array is + [16, 32, 64, 96, 128, 160, 192, 224, 235]. The following image depicts the gradient bevel + as described:

+ +

+ +

Keep in mind that the spread of the colors in the gradient varies based on the values + of the blurX, blurY, strength, and quality + properties, as well as the ratios values.

+ +
GradientBevelFilter.alphasGradientBevelFilter.colorsflash.display.Graphics.beginGradientFill()
strength + The strength of the imprint or spread.Number + The strength of the imprint or spread. The higher the value, the more color is imprinted + and the stronger the contrast between the bevel and the background. + Valid values are 0 to 255. + A value of 0 means that the filter is not applied. The default value is 1. + + GradientBevelFilter.ratiostype + The placement of the bevel effect.String + The placement of the bevel effect. Possible values are BitmapFilterType constants: +
  • BitmapFilterType.OUTER — Bevel on the outer edge of the object
  • BitmapFilterType.INNER — Bevel on the inner edge of the object
  • BitmapFilterType.FULL — Bevel on top of the object
+ +
ConvolutionFilter +The ConvolutionFilter class applies a matrix convolution filter effect.Applies a matrix convolution filter. + +flash.filters:BitmapFilter +The ConvolutionFilter class applies a matrix convolution filter effect. A convolution combines pixels +in the input image with neighboring pixels to produce an image. A wide variety of image +effects can be achieved through convolutions, including blurring, edge detection, sharpening, +embossing, and beveling. You can apply the filter to any display object (that is, objects that +inherit from the DisplayObject class), +such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

To create a convolution filter, use the syntax new ConvolutionFilter(). +The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to movie clips, text fields, buttons, and video, use the +filters property (inherited from DisplayObject). Setting the filters +property of an object does not modify the object, and you can remove the filter by clearing the +filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. +Calling applyFilter() on a BitmapData object takes the source BitmapData object +and the filter object and generates a filtered image as a result.
+ +

If you apply a filter to a display object, the value of the cacheAsBitmap property of the +object is set to true. If you clear all filters, the original value of +cacheAsBitmap is restored.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. +In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, +and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels +wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, +the limitation is 2,880 pixels in height and 2,880 pixels in width. +For example, if you zoom in on a large movie clip with a filter applied, the filter is +turned off if the resulting image exceeds maximum dimensions.

+ +
The following example applies different convolution filters to + an image file. The filter constructor calls + buildChild() four times to load and display four instances of the image. + Each call to buildChild() takes as an argument a function that applies + no filter to the first instance and a different convolution filter to each + subsequent instance. +

The buildChild() function creates a new Loader object named + loader. For each call to buildChild(), + attach an event listener to the Loader object to listen for complete events, + which are handled by the function passed to buildChild().

+ +

The applyBrightness(), applySharpness(), and applyOutline() + functions use different values for the matrix array to achieve different + ConvolutionFilter effects.

+

Note: For best results, use an image approximately 80 pixels in width. + The name and location of the image file should match the value you pass to the + url property. For example, the value passed to url in the example + points to an image file named "Image.jpg" that is in the same directory as your SWF file. +

+ + + +package { + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.*; + import flash.filters.BitmapFilter; + import flash.filters.ConvolutionFilter; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class ConvolutionFilterExample extends Sprite { + private var size:uint = 140; + private var url:String = "Image.jpg"; + + public function ConvolutionFilterExample() { + buildChild(applyNothing); + buildChild(applyBrightness); + buildChild(applySharpness); + buildChild(applyOutline); + } + + private function buildChild(loadHandler:Function):void { + var loader:Loader = new Loader(); + loader.x = numChildren * size; + loader.y = size; + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + if(loadHandler != null) { + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadHandler); + } + + var request:URLRequest = new URLRequest(url); + loader.load(request); + addChild(loader); + } + + private function applyNothing(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + applyLabel(child, "no filter"); + } + + private function applyBrightness(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = [5, 5, 5, + 5, 0, 5, + 5, 5, 5]; + applyFilter(child, matrix); + applyLabel(child, "brightness"); + } + + private function applySharpness(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = [0, -1, 0, + -1, 20, -1, + 0, -1, 0]; + applyFilter(child, matrix); + applyLabel(child, "sharpness"); + } + + private function applyOutline(event:Event):void { + var child:DisplayObject = DisplayObject(event.target.loader); + var matrix:Array = [-30, 30, 0, + -30, 30, 0, + -30, 30, 0]; + applyFilter(child, matrix); + applyLabel(child, "outline"); + } + + private function applyFilter(child:DisplayObject, matrix:Array):void { + var matrixX:Number = 3; + var matrixY:Number = 3; + var divisor:Number = 9; + var filter:BitmapFilter = new ConvolutionFilter(matrixX, matrixY, matrix, divisor); + var filters:Array = new Array(); + filters.push(filter); + child.filters = filters; + } + + private function applyLabel(child:DisplayObject, label:String):void { + var tf:TextField = new TextField(); + tf.x = child.x; + tf.y = child.height; + tf.autoSize = TextFieldAutoSize.LEFT; + tf.text = label; + addChild(tf); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load image: " + url); + } + } +} +
flash.display.BitmapData.applyFilter()flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapmatrixConvolutionFilter + Initializes a ConvolutionFilter instance with the specified parameters.matrixXNumber0The x dimension of the matrix (the number of columns in the matrix). The + default value is 0. + matrixYNumber0The y dimension of the matrix (the number of rows in the matrix). The + default value is 0. + matrixArraynullThe array of values used for matrix transformation. The number of + items in the array must equal matrixX ~~ matrixY. + divisorNumber1.0The divisor used during matrix transformation. The default value is 1. + A divisor that is the sum of all the matrix values evens out the overall color intensity of the + result. A value of 0 is ignored and the default is used instead. + biasNumber0.0The bias to add to the result of the matrix transformation. The default value is 0. + preserveAlphaBooleantrueA value of false indicates that the alpha value is not + preserved and that the convolution applies to all + channels, including the alpha channel. A value of true indicates that + the convolution applies only to the color channels. The default value is true. + clampBooleantrueFor pixels that are off the source image, a value of true indicates that the + input image is extended along each of its borders as necessary by duplicating the color values + at the given edge of the input image. A value of false indicates that another + color should be used, as specified in the color and alpha properties. + The default is true. + coloruint0The hexadecimal color to substitute for pixels that are off the source image. + alphaNumber0.0The alpha of the substitute color. + + + Initializes a ConvolutionFilter instance with the specified parameters. + clone + Returns a copy of this filter object.BitmapFilter A new ConvolutionFilter instance with all the same properties as the original + ConvolutionMatrixFilter instance. + + flash.filters:BitmapFilter + Returns a copy of this filter object. + + alpha + The alpha transparency value of the substitute color.Number + The alpha transparency value of the substitute color. Valid values are 0 to 1.0. The default is 0. For example, + .25 sets a transparency value of 25%. + + bias + The amount of bias to add to the result of the matrix transformation.Number + The amount of bias to add to the result of the matrix transformation. + The bias increases the color value of each channel, so that dark colors + appear brighter. The default value is 0. + + clamp + Indicates whether the image should be clamped.Boolean + Indicates whether the image should be clamped. For pixels off the source image, a value of + true indicates that the input + image is extended along each of its borders as necessary by duplicating the color values at each + respective edge of the input image. A value of false indicates that another color should + be used, as specified in the color and alpha properties. + The default is true. + + The following example creates two boxes using the BitmapData class, one of which is half the size of the other. + When the example first loads, the larger box is drawn inside mc using the attachBitmap(). + When mc is clicked and the applyFilter() method is called, the largeBox instance of BitmapData is redrawn with smallBox as a source bitmap. + Since applyFilter() draws smallBox over a Rectangle whose width and height is specified as those of largeBox, the source bitmap is smaller than the drawing area. + The clamp property of ConvolutionFilter in this case is set to false and the area which is not covered by the source bitmap, smallBox, is a solid red as determined by the clampColor and clampAlpha variables. + + package { + import flash.display.Sprite; + import flash.display.BitmapData; + import flash.filters.ConvolutionFilter; + import flash.text.TextField; + import flash.geom.Rectangle; + import flash.geom.Point; + + public class ConvolutionClampExample extends Sprite { + // Variables that affect clamping: + var clamp:Boolean = false; + var clampColor:Number = 0xFF0000; + var clampAlpha:Number = 1; + + // For illustration, keep other ConvolutionFilter variables neutral: + var bias:Number = 0; + var preserveAlpha:Boolean = false; + // Also, construct a neutral matrix + var matrixCols:Number = 3; + var matrixRows:Number = 3; + var matrix:Array = [ 1,1,1, + 1,1,1, + 1,1,1 ]; + + var filter:ConvolutionFilter = new ConvolutionFilter(matrixCols, matrixRows, matrix, matrix.length, bias, preserveAlpha, clamp, clampColor, clampAlpha); + + var largeBoxWidth:Number = 100; + var largeBoxHeight:Number = 100; + var largeBox:BitmapData = new BitmapData(largeBoxWidth, largeBoxWidth, true, 0xCC00FF00); + var smallBoxWidth:Number = largeBoxWidth / 2; + var smallBoxHeight:Number = largeBoxHeight / 2; + var smallBox:BitmapData = new BitmapData(smallBoxWidth, smallBoxWidth, true, 0xCC0000FF); + + var mc:MovieClip = this.createEmptyMovieClip("mc", this.getNextHighestDepth()); + mc.attachBitmap(largeBox, this.getNextHighestDepth()); + + mc.onPress = function() { + largeBox.applyFilter(smallBox, + new Rectangle(0,0, largeBoxWidth, largeBoxHeight), + new Point(0,0), + filter); + } + } +} +color + The hexadecimal color to substitute for pixels that are off the source image.uint + The hexadecimal color to substitute for pixels that are off the source image. + It is an RGB value with no alpha component. The default is 0. + + divisor + The divisor used during matrix transformation.Number + The divisor used during matrix transformation. The default value is 1. + A divisor that is the sum of all the matrix values smooths out the overall color intensity of the + result. A value of 0 is ignored and the default is used instead. + + matrixX + The x dimension of the matrix (the number of columns in the matrix).Number + The x dimension of the matrix (the number of columns in the matrix). The default + value is 0. + + matrixY + The y dimension of the matrix (the number of rows in the matrix).Number + The y dimension of the matrix (the number of rows in the matrix). The default value + is 0. + + matrix + An array of values used for matrix transformation.ArrayThe Array is null when being set + + TypeErrorTypeError + An array of values used for matrix transformation. The number of items + in the array must equal matrixX ~~ matrixY. +

A matrix convolution is based on an n x m matrix, which describes how a given pixel value in the + input image is combined with its neighboring pixel values to produce a resulting pixel value. Each + result pixel is determined by applying the matrix to the corresponding source pixel and its + neighboring pixels.

+ +

For a 3 x 3 matrix convolution, the following formula is used for each independent color channel: +


+	dst (x, y) = ((src (x-1, y-1) ~~ a0 + src(x, y-1) ~~ a1....
+	                  src(x, y+1) ~~ a7 + src (x+1,y+1) ~~ a8) / divisor) + bias
+	
+

+ +

Certain filter specifications perform faster when run by a processor + that offers SSE (Streaming SIMD Extensions). The following are criteria + for faster convolution operations:

+
  • The filter must be a 3x3 filter.
  • All the filter terms must be integers between -127 and +127.
  • The sum of all the filter terms must not have an absolute value greater than 127.
  • If any filter term is negative, the divisor must be between 2.00001 and 256.
  • If all filter terms are positive, the divisor must be between 1.1 and 256.
  • The bias must be an integer.
+

Note: If you create a ConvolutionFilter instance using the + constructor without parameters, the order you assign values to matrix properties affects + the behavior of the filter. In the following case, the matrix array is assigned while the + matrixX and matrixY properties are still set to 0 + (the default value):

+ + public var myfilter:ConvolutionFilter = new ConvolutionFilter(); + myfilter.matrix = [0, 0, 0, 0, 1, 0, 0, 0, 0]; + myfilter.matrixX = 3; + myfilter.matrixY = 3; + +

In the following case, the matrix array is assigned while the matrixX + and matrixY properties are set to 3:

+ + public var myfilter:ConvolutionFilter = new ConvolutionFilter(); + myfilter.matrixX = 3; + myfilter.matrixY = 3; + myfilter.matrix = [0, 0, 0, 0, 1, 0, 0, 0, 0]; + + +
preserveAlpha + Indicates if the alpha channel is preserved without the filter effect + or if the convolution filter is applied + to the alpha channel as well as the color channels.Boolean + Indicates if the alpha channel is preserved without the filter effect + or if the convolution filter is applied + to the alpha channel as well as the color channels. + A value of false indicates that the + convolution applies to all channels, including the + alpha channel. A value of true indicates that the convolution applies only to the + color channels. The default value is true. + +
GlowFilter + The GlowFilter class lets you apply a glow effect to display objects.Lets you add a glow effect. + + + flash.filters:BitmapFilter + The GlowFilter class lets you apply a glow effect to display objects. + You have several options for the style of the + glow, including inner or outer glow and knockout mode. + The glow filter is similar to the drop shadow filter with the distance + and angle properties of the drop shadow filter set to 0. + You can apply the filter to any display object (that is, objects that inherit from the DisplayObject class), + such as MovieClip, SimpleButton, TextField, and Video objects, as well as to BitmapData objects. + +

The use of filters depends on the object to which you apply the filter:

+
  • To apply filters to display objects, use the + filters property (inherited from DisplayObject). Setting the filters + property of an object does not modify the object, and you can remove the filter by clearing the + filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() method. + Calling applyFilter() on a BitmapData object takes the source BitmapData object + and the filter object and generates a filtered image as a result.
+ + +

If you apply a filter to a display object, the cacheAsBitmap property of the +display object is set to true. If you clear all filters, the original value of +cacheAsBitmap is restored.

+ +

This filter supports Stage scaling. However, it does not support general scaling, rotation, and + skewing. If the object itself is scaled (if scaleX and scaleY are + set to a value other than 1.0), the filter is not scaled. It is scaled only when the user zooms + in on the Stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + For example, if you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +
The following example draws a square and applies a blur filter to it. + The general workflow of the example is as follows: +
  1. Import the required classes.
  2. Declare three properties used in the draw method, which uses methods + of the Graphics class accessed through the graphics property of Sprite + to draw an orange square.
  3. Create the constructor function, which does the following: +
    • Calls the draw function to create a rectangle.
    • Creates a BitmapFilter object glowFilter and assigns it the return values from the getBitmapFilter() function.
    • Assigns the array of values from the glowFilter object to the filters property of the root display object. In this case, + all display object children of the root display object inherit the glow filter properties. So, the rectangle created in the the draw() + function displays the glow filter properties.
    +
+ + +package { + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.filters.BitmapFilter; + import flash.filters.BitmapFilterQuality; + import flash.filters.GlowFilter; + + public class GlowFilterExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + private var offset:uint = 50; + + public function GlowFilterExample() { + //draw the rectangle using the draw() function below + draw(); + + //assign the values from getBitmapFilter function below + //to a BitmapFilter object "glowFilter" + var glowFilter:BitmapFilter = getBitmapFilter(); + + //populate the filters property of the root display object with the array of values + //from the glowFilter object. + filters = [ glowFilter ]; + } + + private function getBitmapFilter():BitmapFilter { + var color:Number = 0x33CCFF; + var alpha:Number = 0.8; + var blurX:Number = 35; + var blurY:Number = 35; + var strength:Number = 2; + var inner:Boolean = false; + var knockout:Boolean = false; + var quality:Number = BitmapFilterQuality.HIGH; + + return new GlowFilter(color, + alpha, + blurX, + blurY, + strength, + quality, + inner, + knockout); + } + + private function draw():void { + graphics.beginFill(bgColor); + graphics.drawRect(offset, offset, size, size); + graphics.endFill(); + } + } +} +
flash.display.BitmapData.applyFilter()flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapflash.display.DisplayObject.scaleXflash.display.DisplayObject.scaleYflash.filters.DropShadowFilter.distanceflash.filters.DropShadowFilter.angleGlowFilter + Initializes a new GlowFilter instance with the specified parameters.coloruint0xFF0000The color of the glow, in the hexadecimal format + 0xRRGGBB. The default value is 0xFF0000. + alphaNumber1.0The alpha transparency value for the color. Valid values are 0 to 1. For example, + .25 sets a transparency value of 25%. + blurXNumber6.0The amount of horizontal blur. Valid values are 0 to 255 (floating point). Values + that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + blurYNumber6.0The amount of vertical blur. Valid values are 0 to 255 (floating point). + Values that are a power of 2 (such as 2, 4, 8, 16 and 32) are optimized + to render more quickly than other values. + strengthNumber2The strength of the imprint or spread. The higher the value, + the more color is imprinted and the stronger the contrast between the glow and the background. + Valid values are 0 to 255. + qualityint1The number of times to apply the filter. Use the BitmapFilterQuality constants: +
  • BitmapFilterQuality.LOW
  • BitmapFilterQuality.MEDIUM
  • BitmapFilterQuality.HIGH
+

For more information, see the description of the quality property.

+
innerBooleanfalseSpecifies whether the glow is an inner glow. The value true specifies + an inner glow. The value false specifies an outer glow (a glow + around the outer edges of the object). + knockoutBooleanfalseSpecifies whether the object has a knockout effect. The value true + makes the object's fill transparent and reveals the background color of the document. +
+ Initializes a new GlowFilter instance with the specified parameters. +
BitmapFilterQualityGlowFilter.quality
clone + Returns a copy of this filter object.A new GlowFilter instance with all the + properties of the original GlowFilter instance. + flash.filters:BitmapFilter + Returns a copy of this filter object. + alpha + The alpha transparency value for the color.Number + The alpha transparency value for the color. Valid values are 0 to 1. + For example, + .25 sets a transparency value of 25%. The default value is 1. + + blurX + The amount of horizontal blur.Number + The amount of horizontal blur. Valid values are 0 to 255 (floating point). The + default value is 6. Values that are a power of 2 (such as 2, 4, + 8, 16, and 32) are optimized + to render more quickly than other values. + + blurY + The amount of vertical blur.Number + The amount of vertical blur. Valid values are 0 to 255 (floating point). The + default value is 6. Values that are a power of 2 (such as 2, 4, + 8, 16, and 32) are optimized + to render more quickly than other values. + + color + The color of the glow.uint + The color of the glow. Valid values are in the hexadecimal format + 0xRRGGBB. The default value is 0xFF0000. + + inner + Specifies whether the glow is an inner glow.Boolean + Specifies whether the glow is an inner glow. The value true indicates + an inner glow. The default is false, an outer glow (a glow + around the outer edges of the object). + + knockout + Specifies whether the object has a knockout effect.Boolean + Specifies whether the object has a knockout effect. A value of true + makes the object's fill transparent and reveals the background color of the document. The + default value is false (no knockout effect). + + quality + The number of times to apply the filter.int + The number of times to apply the filter. The default value is BitmapFilterQuality.LOW, + which is equivalent to applying the filter once. The value BitmapFilterQuality.MEDIUM + applies the filter twice; the value BitmapFilterQuality.HIGH applies it three times. + Filters with lower values are rendered more quickly. + +

For most applications, a quality value of low, medium, or high is sufficient. + Although you can use additional numeric values up to 15 to achieve different effects, + higher values are rendered more slowly. Instead of increasing the value of quality, + you can often get a similar effect, and with faster rendering, by simply increasing the values + of the blurX and blurY properties.

+ +
flash.filters.BitmapFilterQuality
strength + The strength of the imprint or spread.Number + The strength of the imprint or spread. The higher the value, + the more color is imprinted and the stronger the contrast between the glow and the background. + Valid values are 0 to 255. The default is 2. + +
ShaderFilter + The ShaderFilter class applies a filter by executing a shader on the object + being filtered.flash.filters:BitmapFilter + The ShaderFilter class applies a filter by executing a shader on the object + being filtered. The filtered object is used as an input to the shader, and the + shader output becomes the filter result. + +

To create a new filter, use the constructor new ShaderFilter(). The + use of filters depends on the object to which you apply the filter:

+ +
  • To apply filters to movie clips, text fields, buttons, and video, use the + filters property (inherited from DisplayObject). Setting the + filters property of an object does not modify the object, and you + can remove the filter by clearing the filters property.
  • To apply filters to BitmapData objects, use the BitmapData.applyFilter() + method. Calling applyFilter() on a BitmapData object takes the source + BitmapData object and the filter object and generates a filtered image as a + result.
+ +

If you apply a filter to a display object, the value of the cacheAsBitmap + property of the object is set to true. If you remove all filters, the original value of + cacheAsBitmap is restored.

+ +

This filter supports stage scaling. However, it does not support general scaling, + rotation, and skewing. If the object itself is scaled (if the scaleX and + scaleY properties are not set to 100%), the filter is not scaled. It is + scaled only when the user zooms in on the stage.

+ +

A filter is not applied if the resulting image exceeds the maximum dimensions. + In AIR 1.5 and Flash Player 10, the maximum is 8,191 pixels in width or height, + and the total number of pixels cannot exceed 16,777,215 pixels. (So, if an image is 8,191 pixels + wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, + the limitation is 2,880 pixels in height and 2,880 pixels in width. + If, for example, you zoom in on a large movie clip with a filter applied, the filter is + turned off if the resulting image exceeds the maximum dimensions.

+ +

To specify the Shader instance to use with the filter, pass the Shader instance + as an argument to the ShaderFilter() + constructor, or set it as the value of the shader property.

+ +

To allow the shader output to extend beyond the bounds of the filtered object, + use the leftExtension, rightExtension, topExtension, + and bottomExtension properties.

+ +
The following example loads a shader and uses it as the shader property + of a ShaderFilter. The code draws a circle in a Sprite instance and adds it to the stage. When + the shader loads, the shader filter is applied to that Sprite. + +

Note that this example assumes there's a shader bytecode file named "gradient.pbj" in the same + directory as the output directory for the application.

+ + +// +// Source code for the shader: +// +<languageVersion : 1.0;> + +kernel RedGradientFilter +< + namespace: "Adobe::Example"; + vendor: "Adobe examples"; + version: 1; + description: "Applies a gradient across the red channel of the input image."; +> +{ + input image4 src; + output pixel4 dst; + + parameter float width + < + description: "The width of the image to which the shader is applied."; + minValue: 0.0; + >; + + void evaluatePixel() + { + pixel4 temp = sampleNearest(src, outCoord()); + temp.r = 1.0 - (outCoord().x * (1.0 / width)); + dst = temp; + } +} + +// +// ActionScript source code: +// +package { + import flash.display.Shader; + import flash.display.Sprite; + import flash.events.Event; + import flash.filters.ShaderFilter; + import flash.net.URLLoader; + import flash.net.URLLoaderDataFormat; + import flash.net.URLRequest; + + public class ShaderFilterExample extends Sprite { + + private var loader:URLLoader; + private var s:Sprite; + + public function ShaderFilterExample() { + loader = new URLLoader(); + loader.dataFormat = URLLoaderDataFormat.BINARY; + loader.addEventListener(Event.COMPLETE, loadCompleteHandler); + loader.load(new URLRequest("gradient.pbj")); + + s = new Sprite(); + s.graphics.beginFill(0x009900); + s.graphics.drawCircle(100, 100, 100); + addChild(s); + } + + private function loadCompleteHandler(event:Event):void { + var shader:Shader = new Shader(loader.data); + shader.data.width.value = [s.width]; + + var gradientFilter:ShaderFilter = new ShaderFilter(shader); + s.filters = [gradientFilter]; + } + } +} +
flash.display.DisplayObject.filtersflash.display.DisplayObject.cacheAsBitmapflash.display.BitmapData.applyFilter()flash.display.ShaderShaderFilter + Creates a new shader filter.shaderflash.display:ShadernullThe Shader to use for this filter. For details and limitations that + the shader must conform to, see the description for the shader + property. + + + Creates a new shader filter. + + shaderbottomExtension + The growth in pixels on the bottom side of the target object.int0 + + + The growth in pixels on the bottom side of the target object. + +

The growth is the area beyond the bounds of the target object + that is passed to the shader during execution. At execution time + Flash Player or AIR computes the normal bounds of a movie clip and extends + the bounds based on the leftExtension, rightExtension, + topExtension, and bottomExtension values.

+ +
leftExtension + The growth in pixels on the left side of the target object.int0 + + + The growth in pixels on the left side of the target object. + +

The growth is the area beyond the bounds of the target object + that is passed to the shader during execution. At execution time + Flash Player or AIR computes the normal bounds of a movie clip and extends + the bounds based on the leftExtension, rightExtension, + topExtension, and bottomExtension values.

+ +
rightExtension + The growth in pixels on the right side of the target object.int0 + + + The growth in pixels on the right side of the target object. + +

The growth is the area beyond the bounds of the target object + that is passed to the shader during execution. At execution time + Flash Player or AIR computes the normal bounds of a movie clip and extends + the bounds based on the leftExtension, rightExtension, + topExtension, and bottomExtension values.

+ +
shader + The shader to use for this filter.flash.display:Shader + The shader to use for this filter. + +

The Shader assigned to the shader property must specify at least one + image4 input. The input does not need to be specified in code using the + associated ShaderInput object's input property. Instead, the object to which the + filter is applied is automatically + used as the first input (the input with index 0). A shader used as a filter + can specify more than one input, in which case any additional input must be specified + by setting its ShaderInput instance's input property.

+ +

When you assign a Shader instance to this property the shader is copied internally and the + filter operation uses that internal copy, not a reference to the original shader. Any changes + made to the shader, such as changing a parameter value, input, or bytecode, are not applied + to the copied shader that's used for the filter. To make it so that shader changes are taken + into account in the filter output, + you must reassign the Shader instance to the shader property. As with all filters, + you must also reassign the ShaderFilter instance to the display object's filters + property in order to apply filter changes.

+ +
topExtension + The growth in pixels on the top side of the target object.int0 + + + The growth in pixels on the top side of the target object. + +

The growth is the area beyond the bounds of the target object + that is passed to the shader during execution. At execution time + Flash Player or AIR computes the normal bounds of a movie clip and extends + the bounds based on the leftExtension, rightExtension, + topExtension, and bottomExtension values.

+ +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.geom.xml b/language-server/playerglobal_docs/flash.geom.xml new file mode 100644 index 0000000..b0c272c --- /dev/null +++ b/language-server/playerglobal_docs/flash.geom.xml @@ -0,0 +1,4281 @@ +flash.geomUtils3D + + The Utils3D class contains static methods that simplify the implementation of certain three-dimensional + matrix operations.A utility class with static methods that simplify the implementation of certain three-dimensional operation. + + + Object + The Utils3D class contains static methods that simplify the implementation of certain three-dimensional + matrix operations. + + + flash.geom.Matrix3Dflash.geom.Vector3Dflash.geom.Transformflash.geom.PerspectiveProjectionflash.display.Graphicsflash.display.GraphicsTrianglePathVectorpointTowards + Interpolates the orientation of an object toward a position.A modified version of the Matrix3D object specified in the second parameter. To + transform the display object using the pointTowards() method, set the Matrix3D property + of the display object to the returned Matrix3D object. + + flash.geom:Matrix3DpercentNumberA Number between 0 and 1 that incrementally turns the object toward the target. + + matflash.geom:Matrix3DThe Matrix3D property of the object that is transformed. + + posflash.geom:Vector3DThe world-relative position of the target object. World-relative defines + the transformation of the object relative to the world space and coordinates, + where all objects are positioned. + + atflash.geom:Vector3DnullThe object-relative vector that defines where the display object is pointing. + Object-relative defines the transformation of the object relative to the object space, + the object's own frame of reference and coordinate system. Default value is (0,0,-1). + + upflash.geom:Vector3DnullThe object-relative vector that defines "up" for the display object. If the object + is drawn looking down from the above, the +z axis is its "up" vector. + Object-relative defines the transformation of the object relative to the object space, the object's + own frame of reference and coordinate system. Default value is (0,-1,0). + + + Interpolates the orientation of an object toward a position. The pointTowards() + method combines the functionality of the Matrix3D.pointAt() and + Matrix3D.interpolateTo() methods. + +

The pointTowards() method allows for in-place modification to the orientation. + It decomposes the Matrix3D of the display object and replaces the rotation elements + by ones that make a percent turn toward the position of the target. The object + can make an incremental turn toward the target while still moving in its own direction. + The consecutive calls to the pointTowards() followed by a translation method + can produce the animation of an object chasing or following a moving target. + First point the object a percent point toward the target, then incrementally move the + object along an axis.

+ + +
flash.geom.Matrix3D.pointAt()flash.geom.Matrix3D.interpolateTo()flash.geom.Matrix3D.interpolate()
projectVectors + Using a projection Matrix3D object, projects a Vector of three-dimensional space coordinates (verts) + to a Vector of two-dimensional space coordinates (projectedVerts).mflash.geom:Matrix3DA projection Matrix3D object that implements the projection transformation. You can produce a + projection Matrix3D object using the Matrix3D.rawData property. + vertsA Vector of Numbers, where every three Numbers represent the x, y, + and z coordinates of a three-dimensional space, like Vector3D(x,y,z). + + projectedVertsA vector of Numbers, where every two Numbers represent a projected two-dimensional + coordinate, like Point(x,y). You should pre-allocate the Vector. The projectVectors() + method fills the values for each projected point. + + uvtsA vector of Numbers, where every three Numbers represent the u, v, and t + elements of the uvt data. The u and v are the texture coordinate for each projected + point. The t value is the projection depth value, the distance from the eye to the Vector3D object in the + view or eye space. You should pre-allocate the Vector and specify the u and v values. + The projectVectors method fills the t value for each projected point. + + Projects a Vector of three-dimensional space coordinates to a Vector of two-dimensional + space coordinates. + + + Using a projection Matrix3D object, projects a Vector of three-dimensional space coordinates (verts) + to a Vector of two-dimensional space coordinates (projectedVerts). The projected Vector + object should be pre-allocated before it is used as a parameter. + +

The projectVectors() method also sets the t value of the uvt data. + You should pre-allocate a Vector that can hold the uvts data for each projected + Vector set of coordinates. Also specify the u and v values of the + uvt data. The uvt data is a Vector of normalized coordinates used for texture + mapping. In UV coordinates, (0,0) is the upper left of the bitmap, and (1,1) is the lower right of the bitmap.

+ +

This method can be used in conjunction with the Graphics.drawTriangles() method + and the GraphicsTrianglePath class.

+ +
flash.display.Graphics.drawTriangles()flash.display.GraphicsTrianglePathflash.geom.Matrix3DprojectVector()Vector
projectVector + Using a projection Matrix3D object, projects a Vector3D object from one space coordinate to another.A new Vector3D with a transformed space coordinate. + + flash.geom:Vector3Dmflash.geom:Matrix3DA projection Matrix3D object that implements the projection transformation. If a display object + has a PerspectiveProjection object, you can use the perspectiveProjection.toMatrix() method + to produce a projection Matrix3D object that applies to the children of the display object. For more advance + projections, use the matrix3D.rawData property to create a custom projection matrix. + There is no built-in Matrix3D method for creating a projection Matrix3D object. + + vflash.geom:Vector3DThe Vector3D object that is projected to a new space coordinate. + + + Using a projection Matrix3D object, projects a Vector3D object from one space coordinate to another. + The projectVector() method is like the Matrix3D.transformVector() + method except that the projectVector() method divides the x, y, and z + elements of the original Vector3D object by the projection depth value. The depth value is the distance + from the eye to the Vector3D object in view or eye space. The default value for this distance is the + value of the z element. + + flash.geom.Matrix3D.transformVector()projectVectors()
Vector3D + The Vector3D class represents a point or a location in the three-dimensional space using the + Cartesian coordinates x, y, and z.Object + The Vector3D class represents a point or a location in the three-dimensional space using the + Cartesian coordinates x, y, and z. As in a two-dimensional space, the x property represents the + horizontal axis and the y property represents the vertical axis. In three-dimensional space, the + z property represents depth. The value of the x property increases as the object moves to the right. + The value of the y property increases as the object moves down. The z property increases as the object + moves farther from the point of view. Using perspective projection and scaling, the object is seen + to be bigger when near and smaller when farther away from the screen. As in a right-handed three-dimensional + coordinate system, the positive z-axis points away from the viewer and the value of the z property + increases as the object moves away from the viewer's eye. The origin point (0,0,0) of the global space + is the upper-left corner of the stage. + +

+ +

The Vector3D class can also represent a direction, an arrow pointing from the origin of the coordinates, such as + (0,0,0), to an endpoint; or a floating-point component of an RGB (Red, Green, Blue) color model.

+ +

Quaternion notation introduces a fourth element, the w property, which provides additional orientation + information. For example, the w property can define an angle of rotation of a Vector3D object. The + combination of the angle of rotation and the coordinates x, y, and z can determine the display object's + orientation. Here is a representation of Vector3D elements in matrix notation:

+ +

+ + +
flash.display.DisplayObjectflash.geom.Pointflash.geom.Matrix3Dflash.geom.Utils3DVectorVector3D + Creates an instance of a Vector3D object.xNumber0.The first element, such as the x coordinate. + yNumber0.The second element, such as the y coordinate. + zNumber0.The third element, such as the z coordinate. + wNumber0.An optional element for additional data such as the angle of rotation. + + + Creates an instance of a Vector3D object. If you do not specify a parameter for the constructor, + a Vector3D object is created with the elements (0,0,0,0). + + add + Adds the value of the x, y, and z elements of the current Vector3D object + to the values of the x, y, and z elements of another Vector3D object.A Vector3D object that is the result of adding the current Vector3D object + to another Vector3D object. + + flash.geom:Vector3Daflash.geom:Vector3DA Vector3D object to be added to the current Vector3D object. + + Adds the current Vector3D object to another in order to create a new Vector3D object. + + + Adds the value of the x, y, and z elements of the current Vector3D object + to the values of the x, y, and z elements of another Vector3D object. + The add() method does not change the current Vector3D object. Instead, it returns + a new Vector3D object with the new values. + +

The result of adding two vectors together is a resultant vector. One way to visualize + the result is by drawing a vector from the origin or tail of the first vector + to the end or head of the second vector. The resultant vector is the distance + between the origin point of the first vector and the end point of the second vector.

+ +

+ +
incrementBy()
angleBetween + Returns the angle in radians between two vectors.The angle between two Vector3D objects. + + Numberaflash.geom:Vector3DThe first Vector3D object. + bflash.geom:Vector3DThe second Vector3D object. + + + Returns the angle in radians between two vectors. The returned angle is the smallest radian + the first Vector3D object rotates until it aligns with the second Vector3D object. + +

The angleBetween() method is a static method. You can use it directly as + a method of the Vector3D class.

+ +

To convert a degree to a radian, you can use the following formula:

+ +

radian = Math.PI/180 ~~ degree

+ +
clone + Returns a new Vector3D object that is an exact copy of the current Vector3D object.A new Vector3D object that is a copy of the current Vector3D object. + + flash.geom:Vector3D + Returns a new Vector3D object that is an exact copy of the current Vector3D object. + + + crossProduct + Returns a new Vector3D object that is perpendicular (at a right angle) to the current + Vector3D and another Vector3D object.A new Vector3D object that is perpendicular to the current Vector3D object and the Vector3D + object specified as the parameter. + + flash.geom:Vector3Daflash.geom:Vector3DA second Vector3D object. + + + Returns a new Vector3D object that is perpendicular (at a right angle) to the current + Vector3D and another Vector3D object. If the returned Vector3D object's coordinates are + (0,0,0), then the two Vector3D objects are perpendicular to each other. + +

+ +

You can use the normalized cross product of two vertices of a polygon surface with the + normalized vector of the camera or eye viewpoint to get a dot product. The value of + the dot product can identify whether a surface of a three-dimensional object is hidden + from the viewpoint.

+ + +
dotProduct()normalize()
decrementBy + Decrements the value of the x, y, and z elements of the current Vector3D object + by the values of the x, y, and z elements of specified Vector3D object.aflash.geom:Vector3DThe Vector3D object containing the values to subtract from the current Vector3D object. + + Decrements the current Vector3D object by another Vector3D object. + + + Decrements the value of the x, y, and z elements of the current Vector3D object + by the values of the x, y, and z elements of specified Vector3D object. Unlike the + Vector3D.subtract() method, the decrementBy() method changes the current + Vector3D object and does not return a new Vector3D object. + + + subtract()distance + Returns the distance between two Vector3D objects.The distance between two Vector3D objects. + + Numberpt1flash.geom:Vector3DA Vector3D object as the first three-dimensional point. + pt2flash.geom:Vector3DA Vector3D object as the second three-dimensional point. + + + Returns the distance between two Vector3D objects. The distance() method + is a static method. You can use it directly as a method of the Vector3D class to get + the Euclidean distance between two three-dimensional points. + + dotProduct + If the current Vector3D object and the one specified as the parameter are unit vertices, this + method returns the cosine of the angle between the two vertices.A scalar which is the dot product of the current Vector3D object and the specified Vector3D object. + + Numberaflash.geom:Vector3DThe second Vector3D object. + + Returns the dot product of current and another Vector3D object. + + + If the current Vector3D object and the one specified as the parameter are unit vertices, this + method returns the cosine of the angle between the two vertices. Unit vertices are vertices that + point to the same direction but their length is one. They remove the length of the vector + as a factor in the result. You can use the normalize() method to convert a vector to a unit vector. + +

The dotProduct() method finds the angle between two vertices. It is also + used in backface culling or lighting calculations. Backface culling is a procedure for determining + which surfaces are hidden from the viewpoint. You can use the normalized vertices from the camera, + or eye, viewpoint and the cross product of the vertices of a polygon surface to get the dot product. + If the dot product is less than zero, then the surface is facing the camera or the viewer. If the + two unit vertices are perpendicular to each other, they are orthogonal and the dot product is zero. + If the two vertices are parallel to each other, the dot product is one.

+ + +
crossProduct()normalize()
equals + Determines whether two Vector3D objects are equal by comparing the x, y, and z + elements of the current Vector3D object with a specified Vector3D object.A value of true if the specified Vector3D object is equal to the current + Vector3D object; false if it is not equal. + + BooleantoCompareflash.geom:Vector3DThe Vector3D object to be compared with the current Vector3D object. + allFourBooleanfalseAn optional parameter that specifies whether the w property of + the Vector3D objects is used in the comparison. + + + Determines whether two Vector3D objects are equal by comparing the x, y, and z + elements of the current Vector3D object with a specified Vector3D object. If the values of + these elements are the same, the two Vector3D objects are equal. If the second + optional parameter is set to true, all four elements of the Vector3D objects, + including the w property, are compared. + + nearEquals()incrementBy + Increments the value of the x, y, and z elements of the current Vector3D object + by the values of the x, y, and z elements of a specified Vector3D object.aflash.geom:Vector3DThe Vector3D object to be added to the current Vector3D object. + + Increments the current Vector3D object by another Vector3D object. + + + Increments the value of the x, y, and z elements of the current Vector3D object + by the values of the x, y, and z elements of a specified Vector3D object. Unlike the + Vector3D.add() method, the incrementBy() method changes the current + Vector3D object and does not return a new Vector3D object. + + + add()nearEquals + Compares the elements of the current Vector3D object with the elements of a specified + Vector3D object to determine whether they are nearly equal.A value of true if the specified Vector3D object is nearly equal to the current + Vector3D object; false if it is not equal. + + BooleantoCompareflash.geom:Vector3DThe Vector3D object to be compared with the current Vector3D object. + toleranceNumberA number determining the tolerance factor. If the difference between the values + of the Vector3D element specified in the toCompare parameter and the current Vector3D element + is less than the tolerance number, the two values are considered nearly equal. + allFourBooleanfalseAn optional parameter that specifies whether the w property of + the Vector3D objects is used in the comparison. + + + Compares the elements of the current Vector3D object with the elements of a specified + Vector3D object to determine whether they are nearly equal. The two Vector3D objects are nearly equal + if the value of all the elements of the two vertices are equal, or the result of the comparison + is within the tolerance range. The difference between two elements must be less than the number + specified as the tolerance parameter. If the third optional parameter is set to + true, all four elements of the Vector3D objects, including the w property, + are compared. Otherwise, only the x, y, and z elements are included in the comparison. + + + equals()negate + Sets the current Vector3D object to its inverse. + Sets the current Vector3D object to its inverse. The inverse object is also considered the + opposite of the original object. The value of + the x, y, and z properties of the current Vector3D object + is changed to -x, -y, and -z. + + + normalize + Converts a Vector3D object to a unit vector by dividing the first three elements + (x, y, z) by the length of the vector.The length of the current Vector3D object. + + Number + Converts a Vector3D object to a unit vector by dividing the first three elements + (x, y, z) by the length of the vector. Unit vertices are + vertices that have a direction but their length is one. They simplify + vector calculations by removing length as a factor. + + + project + Divides the value of the x, y, and z properties of the + current Vector3D object by the value of its w property. + Divides the value of the x, y, and z properties of the + current Vector3D object by the value of its w property. + +

If the current Vector3D object is the result of multiplying a Vector3D object by a projection Matrix3D object, + the w property can hold the transform value. The project() method then can + complete the projection by dividing the elements by the w property. Use the + Matrix3D.rawData property to create a projection Matrix3D object.

+ + +
scaleBy + Scales the current Vector3D object by a scalar, a magnitude.sNumberA multiplier (scalar) used to scale a Vector3D object. + + + Scales the current Vector3D object by a scalar, a magnitude. The Vector3D object's + x, y, and z elements are multiplied by the scalar number + specified in the parameter. For example, if the vector is scaled by ten, + the result is a vector that is ten times longer. The scalar can also + change the direction of the vector. Multiplying the vector by a negative + number reverses its direction. + + subtract + Subtracts the value of the x, y, and z elements of the current Vector3D object + from the values of the x, y, and z elements of another Vector3D object.A new Vector3D object that is the difference between the current Vector3D + and the specified Vector3D object. + + flash.geom:Vector3Daflash.geom:Vector3DThe Vector3D object to be subtracted from the current Vector3D object. + + Subtracts the current Vector3D from another Vector3D object in order + to create a new Vector3D object. + + + Subtracts the value of the x, y, and z elements of the current Vector3D object + from the values of the x, y, and z elements of another Vector3D object. + The subtract() method does not change the current Vector3D object. Instead, + this method returns a new Vector3D object with the new values. + + + decrementBy()toString + Returns a string representation of the current Vector3D object.A string containing the values of the x, y, and + z properties. + + String + Returns a string representation of the current Vector3D object. The string + contains the values of the x, y, and z properties. + + + X_AXIS + The x axis defined as a Vector3D object with coordinates (1,0,0).unknownflash.geom:Vector3D + The x axis defined as a Vector3D object with coordinates (1,0,0). + + Y_AXIS + The y axis defined as a Vector3D object with coordinates (0,1,0).unknownflash.geom:Vector3D + The y axis defined as a Vector3D object with coordinates (0,1,0). + + Z_AXIS + The z axis defined as a Vector3D object with coordinates (0,0,1).unknownflash.geom:Vector3D + The z axis defined as a Vector3D object with coordinates (0,0,1). + + w + The fourth element of a Vector3D object (in addition to the x, y, + and z properties) can hold + data such as the angle of rotation.Number + The fourth element of a Vector3D object (in addition to the x, y, + and z properties) can hold + data such as the angle of rotation. The default value is 0. + +

Quaternion notation employs an angle as the fourth element in its calculation of + three-dimensional rotation. The w property can be used to define the angle of rotation + about the Vector3D object. The combination of the rotation angle and the coordinates (x,y,z) + determines the display object's orientation.

+

In addition, the w property can be used as a perspective + warp factor for a projected three-dimensional position or as a projection transform value in + representing a three-dimensional coordinate projected into the two-dimensional space. For example, + you can create a projection matrix using the Matrix3D.rawData property, that, when + applied to a Vector3D object, produces a transform value in the Vector3D object's fourth element (the + w property). Dividing the Vector3D object's other elements by the transform value + then produces a projected Vector3D object. You can use the Vector3D.project() method + to divide the first three elements of a Vector3D object by its fourth element.

+ +
project()
x + The first element of a Vector3D object, such as + the x coordinate of a point in the three-dimensional space.Number + The first element of a Vector3D object, such as + the x coordinate of a point in the three-dimensional space. The default value is 0. + + y + The second element of a Vector3D object, such as + the y coordinate of a point in the three-dimensional space.Number + The second element of a Vector3D object, such as + the y coordinate of a point in the three-dimensional space. The default value is 0. + + z + The third element of a Vector3D object, such as + the z coordinate of a point in three-dimensional space.Number + The third element of a Vector3D object, such as + the z coordinate of a point in three-dimensional space. The default value is 0. + + lengthSquared + The square of the length of the current Vector3D object, calculated using the x, + y, and z properties.NumberThe square of the length of the current Vector3D object. + + + The square of the length of the current Vector3D object, calculated using the x, + y, and z properties. The w property is ignored. + Use the lengthSquared() method whenever possible instead of the slower + Math.sqrt() method call of the Vector3D.length() method. + + lengthlength + The length, magnitude, of the current Vector3D object from the origin (0,0,0) to + the object's x, y, and z coordinates.NumberThe length of the current Vector3D object. + + + The length, magnitude, of the current Vector3D object from the origin (0,0,0) to + the object's x, y, and z coordinates. The w + property is ignored. A unit vector has a length or magnitude of one. + + lengthSquared
Matrix3D + The Matrix3D class represents a transformation matrix that determines the position and orientation of + a three-dimensional (3D) display object.Object + The Matrix3D class represents a transformation matrix that determines the position and orientation of + a three-dimensional (3D) display object. The matrix can perform transformation functions including + translation (repositioning along the x, y, and z axes), rotation, and scaling (resizing). + The Matrix3D class can also perform perspective projection, which maps points from the 3D coordinate space + to a two-dimensional (2D) view. + +

A single matrix can combine multiple transformations and apply them at once to a 3D display object. + For example, a matrix can be applied to 3D coordinates to perform a rotation followed by a translation.

+ +

When you explicitly set the z property or any of the rotation or scaling + properties of a display object, a corresponding Matrix3D object is automatically created.

+ +

You can access a 3D display object's Matrix3D object through the transform.matrix3d + property. 2D objects do not have a Matrix3D object.

+ +

The value of the z property of a 2D object is zero and the value of its + matrix3D property is null.

+ +

Note: If the same Matrix3D object is assigned to two different display objects, + a runtime error is thrown.

+ +

The Matrix3D class uses a 4x4 square matrix: a table of four rows and columns of numbers that hold + the data for the transformation. The first three rows of the matrix hold data for each 3D + axis (x,y,z). The translation information is in the last column. The orientation + and scaling data are in the first three columns. The scaling factors are the diagonal numbers in + the first three columns. Here is a representation of Matrix3D elements:

+ +

+ +

You don't need to understand matrix mathematics to use the Matrix3D class. + It offers specific methods that simplify the task of transformation and projection, such as the + appendTranslation(), appendRotation(), or interpolateTo() methods. + You also can use the decompose() and recompose() methods or the rawData + property to access the underlying matrix elements.

+ +

Display objects cache their axis rotation properties to have separate rotation for each axis + and to manage the different combinations of rotations. When a method of a Matrix3D object is called + to transform a display object, the rotation cache of the object is invalidated.

+ +
flash.display.DisplayObjectflash.geom.Transformflash.geom.PerspectiveProjectionflash.geom.Vector3Dflash.geom.Orientation3Dflash.geom.Utils3Dflash.geom.MatrixMatrix3D + Creates a Matrix3D object.vnullA Vector of 16 Numbers, where each four elements can be a row or a column + of a 4x4 matrix. + + + Creates a Matrix3D object. Matrix3D objects can be initialized with a Vector of 16 Numbers, + where every four elements can be a row or a column. Once the Matrix3D object is created, + you can access its matrix elements with the rawData property. + +

If no parameter is defined, the constructor produces an identity or unit Matrix3D object. + In matrix notation, an identity matrix has a value of one for all elements on the main diagonal + position and a value of zero for all other elements. The value of the rawData property + of an identity matrix is: 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1. The position or translation + value of the identity matrix is Vector3D(0,0,0), the rotation setting is + Vector3D(0,0,0), and the scale value is Vector3D(1,1,1).

+ +
identity()Vector
appendRotation + Appends an incremental rotation to a Matrix3D object.degreesNumberThe degree of the rotation. + axisflash.geom:Vector3DThe axis or direction of rotation. The usual axes are the X_AXIS (Vector3D(1,0,0)), + Y_AXIS (Vector3D(0,1,0)), and Z_AXIS (Vector3D(0,0,1)). + pivotPointflash.geom:Vector3DnullA point that determines the center of an object's rotation. The default pivot point + for an object is its registration point. + + + Appends an incremental rotation to a Matrix3D object. When the Matrix3D object is applied + to a display object, the matrix performs the rotation after other transformations in the Matrix3D + object. + +

The display object's rotation is defined by an axis, an incremental degree + of rotation around the axis, and an optional pivot point for the center of the object's rotation. + The axis can be any general direction. The common axes are the X_AXIS (Vector3D(1,0,0)), + Y_AXIS (Vector3D(0,1,0)), and Z_AXIS (Vector3D(0,0,1)). + In aviation terminology, the rotation about the y axis is called yaw. The rotation about the x axis is + called pitch. The rotation about the z axis is called roll.

+ +

The order of transformation matters. A rotation followed by a translation transformation + produces a different effect than a translation followed by a rotation transformation.

+ +

The rotation effect is not absolute. It is relative to the current position and orientation. + To make an absolute change to the transformation matrix, use the recompose() method. + The appendRotation() method is also different from the axis rotation property of + the display object, such as rotationX property. The rotation property is always + performed before any translation, whereas the appendRotation() method is performed + relative to what is already in the matrix. To make sure that you get a similar effect as the display + object's axis rotation property, use the prependRotation() method, which performs + the rotation before other transformations in the matrix.

+ +

When the appendRotation() method's transformation is applied to a Matrix3D object + of a display object, the cached rotation property values of the display object are invalidated.

+ +

One way to have a display object rotate around a specific point relative to its location is + to set the translation of the object to the specified point, rotate the object using the appendRotation() + method, and translate the object back to the original position. In the following example, the + myObject 3D display object makes a y-axis rotation around + the coordinate (10,10,0).

+ + + + myObject.z = 1; + myObject.transform.matrix3D.appendTranslation(10,10,0); + myObject.transform.matrix3D.appendRotation(1, Vector3D.Y_AXIS); + myObject.transform.matrix3D.appendTranslation(-10,-10,0); + + + +
prependRotation()
appendScale + Appends an incremental scale change along the x, y, and z axes + to a Matrix3D object.xScaleNumberA multiplier used to scale the object along the x axis. + yScaleNumberA multiplier used to scale the object along the y axis. + zScaleNumberA multiplier used to scale the object along the z axis. + + + Appends an incremental scale change along the x, y, and z axes + to a Matrix3D object. When the Matrix3D object is applied to a display object, the matrix performs + the scale changes after other transformations in the Matrix3D object. The default scale + factor is (1.0, 1.0, 1.0). + +

The scale is defined as a set of three incremental changes along the three axes (x,y,z). + You can multiply each axis with a different number. When the scale changes are applied to + a display object, the object's size increases or decreases. For example, setting + the x, y, and z axes to two doubles the size of the object, while + setting the axes to 0.5 halves the size. To make sure that + the scale transformation only affects a specific axis, set the other parameters to one. + A parameter of one means no scale change along the specific axis.

+ +

The appendScale() method can be used for resizing as well as + for managing distortions, such as stretch or contract of a display object, or for zooming in + and out on a location. Scale transformations are automatically performed during a display + object's rotation and translation.

+ +

The order of transformation matters. A resizing followed by a translation transformation + produces a different effect than a translation followed by a resizing transformation.

+ +
prependScale()
appendTranslation + Appends an incremental translation, a repositioning along the x, y, and z axes, + to a Matrix3D object.xNumberAn incremental translation along the x axis. + yNumberAn incremental translation along the y axis. + zNumberAn incremental translation along the z axis. + + + Appends an incremental translation, a repositioning along the x, y, and z axes, + to a Matrix3D object. When the Matrix3D object is applied to a display object, the matrix performs + the translation changes after other transformations in the Matrix3D object. + +

The translation is defined as a set of three incremental changes along the three axes (x,y,z). + When the transformation is applied to a display object, the display object moves from it current + location along the x, y, and z axes as specified by the parameters. + To make sure that the translation only affects a specific axis, set the other parameters to zero. + A zero parameter means no change along the specific axis.

+ +

The translation changes are not absolute. They are relative to the current + position and orientation of the matrix. To make an absolute change to the transformation matrix, + use the recompose() method. The order of transformation also matters. A translation + followed by a rotation transformation produces a different effect than a rotation followed + by a translation.

+ + +
prependTranslation()position
append + Appends the matrix by multiplying another Matrix3D object by the current Matrix3D object.lhsflash.geom:Matrix3DA left-hand-side matrix that is multiplied by the current Matrix3D object. + + + Appends the matrix by multiplying another Matrix3D object by the current Matrix3D object. + The result combines both matrix transformations. You can multiply a Matrix3D object + by many matrixes. The final Matrix3D object contains the result of all the + transformations. + +

Matrix multiplication is different from matrix addition. Matrix multiplication is not commutative. + In other words, A times B is not equal to B times A. With the append() method, + the multiplication happens from the left side, meaning the lhs Matrix3D object is + on the left side of the multiplication operator.

+ + thisMatrix = lhs ~~ thisMatrix; + +

The first time the append() method is called, it makes a modification relative + to the parent space. Subsequent calls are relative to the frame of reference of the appended + Matrix3D object.

+ +

The append() method replaces the current matrix with the appended matrix. + If you want to append two matrixes without altering the current matrix, copy the + current matrix by using the clone() method and then apply the append() + method to the copy.

+ +
flash.geom.Matrix3D.prepend()
clone + Returns a new Matrix3D object that is an exact copy of the current Matrix3D object.A new Matrix3D object that is an exact copy of the current Matrix3D object. + + flash.geom:Matrix3D + Returns a new Matrix3D object that is an exact copy of the current Matrix3D object. + + + decompose + Returns the transformation matrix's translation, rotation, and scale settings as + a Vector of three Vector3D objects.A Vector of three Vector3D objects, each holding the translation, rotation, and scale + settings, respectively. + + orientationStyleStringeulerAnglesAn optional parameter that determines the orientation style + used for the matrix transformation. The three types of orientation style are + eulerAngles (constant EULER_ANGLES), axisAngle + (constant AXIS_ANGLE), and quaternion (constant QUATERNION). + For additional information on the different orientation style, see the geom.Orientation3D class. + + + Returns the transformation matrix's translation, rotation, and scale settings as + a Vector of three Vector3D objects. The first Vector3D object holds the translation + elements. The second Vector3D object holds the rotation elements. The third Vector3D object + holds the scale elements. + +

Some Matrix3D methods, such as the interpolateTo() method, automatically + decompose and recompose the matrix to perform their transformation.

+ +

To modify the matrix's transformation with an absolute parent frame of reference, + retrieve the settings with the decompose() method and make the appropriate changes. + You can then set the Matrix3D object to the modified transformation using the recompose() + method.

+ +

The decompose() method's parameter specifies the orientation style that + is meant to be used for the transformation. The default orientation is eulerAngles, + which defines the orientation with three separate angles of rotation for each axis. + The rotations occur consecutively and do not change the axis of each other. The + display object's axis rotation properties perform Euler Angles orientation style transformation. + The other orientation style options are axisAngle and quaternion. + The Axis Angle orientation uses a combination of an axis and an angle to determine the orientation. + The axis around which the object is rotated is a unit vector that represents a direction. + The angle represents the magnitude of the rotation about the vector. The direction also + determines where a display object is facing and the angle determines which way is up. + The appendRotation() and prependRotation() methods use the Axis Angle orientation. + The quaternion orientation uses complex numbers and the fourth element of a vector. + The three axes of rotation (x,y,z) and an angle of rotation (w) represent the orientation. + The interpolate() method uses quaternion.

+ +
This example uses the decompose() + and recompose() methods to have an ellipse stretch horizontally + while moving toward the vanishing point. The first Vector3D object returned + by the decompose() method holds the translation coordinates. The + third Vector3D object holds the scale settings. The Vector3D object's + incrementBy() method increments the matrix's absolute translation + and scale settings. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.geom.*; + import flash.events.Event; + + public class Matrix3DdecomposeExample extends MovieClip { + private var ellipse:Shape = new Shape(); + + public function Matrix3DdecomposeExample():void { + + ellipse.x = (this.stage.stageWidth / 2); + ellipse.y = (this.stage.stageHeight - 40); + ellipse.z = 1; + ellipse.graphics.beginFill(0xFF0000); + ellipse.graphics.lineStyle(2); + ellipse.graphics.drawEllipse(0, 0, 50, 40); + ellipse.graphics.endFill(); + addChild(ellipse); + + ellipse.addEventListener(Event.ENTER_FRAME, enterFrameHandler); + } + + private function enterFrameHandler(e:Event):void { + + var v3:Vector.<Vector3D> = new Vector.<Vector3D>(3); + v3 = ellipse.transform.matrix3D.decompose(); + v3[0].incrementBy(new Vector3D(0,0,1)); + v3[2].incrementBy(new Vector3D(0.01,0,0)); + ellipse.transform.matrix3D.recompose(v3); + } + } +} +
flash.geom.Orientation3Drecompose()Vector
deltaTransformVector + Uses the transformation matrix without its translation elements + to transform a Vector3D object from one space coordinate to another.A Vector3D object with the transformed coordinates. + + flash.geom:Vector3Dvflash.geom:Vector3DA Vector3D object holding the coordinates that are going to be transformed. + + + Uses the transformation matrix without its translation elements + to transform a Vector3D object from one space coordinate to another. + The returned Vector3D object holds the new coordinates after the rotation + and scaling transformations have been applied. If the deltaTransformVector() + method applies a matrix that only contains a translation transformation, + the returned Vector3D is the same as the original Vector3D object. + +

You can use the deltaTransformVector() method to have a + display object in one coordinate space respond to the rotation transformation + of a second display object. The object does not copy the rotation; + it only changes its position to reflect the changes in the rotation. + For example, to use the display.Graphics API for drawing a rotating + 3D display object, you must map the object's rotating coordinates + to a 2D point. First, retrieve the object's 3D + coordinates after each rotation, using the deltaTransformVector() method. + Next, apply the display object's local3DToGlobal() method to translate the + 3D coordinates to 2D points. You can then use + the 2D points to draw the rotating 3D object.

+ + +
transformVectors()transformVector()
identity + Converts the current matrix to an identity or unit matrix. + Converts the current matrix to an identity or unit matrix. An identity matrix has a value + of one for the elements on the main diagonal and a value of zero for all + other elements. The result is a matrix where the rawData value is + 1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1 and the rotation setting is set to + Vector3D(0,0,0), the position or translation setting is set to + Vector3D(0,0,0), and the scale is set to Vector3D(1,1,1). + Here is a representation of an identity matrix. + +

+ +

An object transformed by applying an identity matrix performs no transformation. + In other words, if a matrix is multiplied by an identity matrix, the result is + a matrix that is the same as (identical to) the original matrix.

+ +
interpolateTo + Interpolates the display object's matrix a percent closer to a target's matrix.toMatflash.geom:Matrix3DThe target Matrix3D object. + percentNumberA value between 0 and 1 that determines the location of the display object + relative to the target. The closer the value is to 1.0, the closer the display object + is to its current position. The closer the value is to 0, the closer the display object is + to the target. + + + Interpolates the display object's matrix a percent closer to a target's matrix. All the elements for + translation, rotation, and scale of the display object are interpolated to values + between the current and target display object's matrix. + +

The interpolateTo() method avoids the unwanted results that can occur when + using methods such as the display object's axis rotation properties. The interpolateTo() + method invalidates the cached value of the rotation property of the display + object and converts the orientation elements of the display object's matrix to a quaternion + before interpolation. This method guarantees the shortest, most efficient path for the rotation. + It also produces a smooth, gimbal-lock-free rotation. A gimbal lock can occur when using Euler Angles, + where each axis is handled independently. During the rotation around two or more axes, the axes can + become aligned, leading to unexpected results. Quaternion rotation avoids the gimbal lock.

+ +

Consecutive calls to the interpolateTo() method can produce the effect of a display + object starting quickly and then slowly approaching another display object. For example, if the percent + parameter is set to 0.1, the display object moves ten percent toward the target object + specified by the toMat parameter. On subsequent calls or in subsequent + frames, the object moves ten percent of the remaining 90 percent, then ten percent of the + remaining 80 percent, until it reaches the target.

+ +
In this example, ellipse2, a three-dimensional display object, goes + toward ellipse1, another three-dimensional display object. + ellipse2 follows ellipse1 around trying to catch it. + If ellipse1 does not rotate around its y axis, ellipse2 + will reach and land on top of ellipse1. The two ellipses are + drawn in the same way but are placed in different three-dimensional world-space locations. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.display.Graphics; + import flash.geom.*; + import flash.events.Event; + + public class InterpolateToExample extends MovieClip { + private var ellipse1:Shape = new Shape(); + private var ellipse2:Shape = new Shape(); + + public function InterpolateToExample():void { + + ellipse1 = myEllipses(250, 100, 500, 0xFF0000); + addChild(ellipse1); + + ellipse2 = myEllipses(-30, 120, 1, 0x00FF00); + addChild(ellipse2); + + addEventListener(Event.ENTER_FRAME, enterFrameHandler); + } + + private function myEllipses(x:Number, y:Number, z:Number, c:Number):Shape { + var s:Shape = new Shape(); + s.x = x; + s.y = y; + s.z = z; + s.graphics.beginFill(c); + s.graphics.lineStyle(2); + s.graphics.drawEllipse(100, 50, 100, 80); + s.graphics.endFill(); + return s; + } + + private function enterFrameHandler(e:Event) { + ellipse1.rotationY += 1; + + ellipse2.transform.matrix3D.interpolateTo(ellipse1.transform.matrix3D, 0.1); + } + } +} +
interpolate()
interpolate + Simplifies the interpolation from one frame of reference to another by interpolating a display object + a percent point closer to a target display object.A Matrix3D object with elements that place the values of the matrix between the original matrix + and the target matrix. When the returned matrix is applied to the this display object, the + object moves the specified percent closer to the target object. + + flash.geom:Matrix3DthisMatflash.geom:Matrix3DThe Matrix3D object that is to be interpolated. + toMatflash.geom:Matrix3DThe target Matrix3D object. + percentNumberA value between 0 and 1 that determines the percent + the thisMat Matrix3D object is interpolated toward the target Matrix3D object. + + Interpolates a display object a percent point closer to a target display object. + + + Simplifies the interpolation from one frame of reference to another by interpolating a display object + a percent point closer to a target display object. The result is a new Matrix3D object + where all the elements for the translation, rotation, and scale are interpolated to values + between the current display object and the target display object. + +

The interpolate() method avoids some of the unwanted results that can occur when + using methods such as the display object's axis rotation properties. The interpolate() + method invalidates the cached value of the rotation property of the display + object and converts the orientation elements of the display object's matrix to a quaternion + before interpolation. This method guarantees the shortest, most efficient path for the rotation. + It also produces a smooth, gimbal-lock-free rotation. A gimbal lock can occur when using Euler Angles, + where each axis is handled independently. During the rotation around two or more axes, the axes can + become aligned, leading to unexpected results. Quaternion rotation avoids the gimbal lock.

+ +

Consecutive calls to the interpolate() method can produce the effect of a display + object starting quickly and then slowly approaching another display object. For example, if you set + the thisMat parameter to the returned Matrix3D object, the toMat parameter + to the target display object's + associated Matrix3D object, and the percent parameter to 0.1, + the display object moves ten percent toward the target object. On subsequent calls or in subsequent + frames, the object moves ten percent of the remaining 90 percent, then ten percent of the remaining + 80 percent, until it reaches the target.

+ +
interpolateTo()flash.geom.Utils3D.pointTowards()
invert + Inverts the current matrix.Returns true if the matrix was successfully inverted. + + Boolean + Inverts the current matrix. An inverted matrix is the same size as the original + but performs the opposite transformation of the original matrix. For example, + if the original matrix has an object rotate around the x axis in one direction, + the inverse of the matrix will have the object rotate around the axis in + the opposite direction. Applying an inverted matrix to an object undoes the + transformation performed by the original matrix. If a matrix is multiplied by its + inverse matrix, the result is an identity matrix. + +

An inverse of a matrix can be used to divide one matrix by another. The way to divide + matrix A by matrix B is to multiply matrix A by the inverse of matrix B. The inverse matrix can also be used + with a camera space. When the camera moves in the world space, the object in the world needs to + move in the opposite direction to transform from the world view to the camera or + view space. For example, if the camera moves closer, the objects becomes bigger. + In other words, if the camera moves down the world z axis, the object moves up + world z axis.

+ +

The invert() method replaces the current matrix with an inverted matrix. + If you want to invert a matrix without altering the current matrix, first copy the + current matrix by using the clone() method and then apply the invert() + method to the copy.

+ +

The Matrix3D object must be invertible.

+ +
determinant
pointAt + Rotates the display object so that it faces a specified position.posflash.geom:Vector3DThe world-relative position of the target object. World-relative defines + the object's transformation relative to the world space and coordinates, where all objects are positioned. + + atflash.geom:Vector3DnullThe object-relative vector that defines where the display object is pointing. + Object-relative defines the object's transformation relative to the object space, the object's own + frame of reference and coordinate system. Default value is the +y axis (0,1,0). + + upflash.geom:Vector3DnullThe object-relative vector that defines "up" for the display object. If the object + is drawn looking down from above, the +z axis is its "up" vector. + Object-relative defines the object's transformation relative to the object space, the object's own + frame of reference and coordinate system. Default value is the +z-axis (0,0,1). + + + Rotates the display object so that it faces a specified position. This method allows for an + in-place modification to the orientation. The forward direction vector of the display object + (the at Vector3D object) points at the specified world-relative position. + The display object's up direction is specified with the up + Vector3D object. + +

The pointAt() method invalidates the cached rotation property + value of the display object. The method decomposes the display object's matrix and modifies + the rotation elements to have the object turn to the specified position. It + then recomposes (updates) the display object's matrix, which performs the transformation. + If the object is pointing at a moving target, such as a moving object's position, + then with each subsequent call, the method has the object rotate toward the moving target.

+

Note: If you use the Matrix3D.pointAt() method without setting the optional parameters, + a target object does not face the specified world-relative position by default. You need to set the values + for at to the -y-axis (0,-1,0) and up to the -z axis (0,0,-1).

+ +
In this example, a triangle points and follows the path of the ellipse's + movement. The ellipse and triangle are set to different locations. + The ellipse then moves up toward the corner of the stage. The triangle + follows the ellipse's translation changes. You can change the triangle's + shape and the "at" and "up" parameters of the pointAt() + to see their impacts on the triangle's movement. + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.display.Graphics; + import flash.geom.*; + import flash.events.Event; + + public class PointAtExample extends MovieClip { + private var ellipse:Shape = new Shape(); + private var triangle:Shape = new Shape(); + + public function PointAtExample():void { + ellipse.graphics.beginFill(0xFF0000); + ellipse.graphics.lineStyle(2); + ellipse.graphics.drawEllipse(30, 40, 50, 40); + ellipse.graphics.endFill(); + ellipse.x = 100; + ellipse.y = 150; + ellipse.z = 1; + + triangle.graphics.beginFill(0x0000FF); + triangle.graphics.moveTo(0, 0); + triangle.graphics.lineTo(40, 40); + triangle.graphics.lineTo(80, 0); + triangle.graphics.lineTo(0, 0); + triangle.graphics.endFill(); + triangle.x = 200; + triangle.y = 50; + triangle.z = 1; + + addChild(ellipse); + addChild(triangle); + + ellipse.addEventListener(Event.ENTER_FRAME, ellipseEnterFrameHandler); + triangle.addEventListener(Event.ENTER_FRAME, triangleEnterFrameHandler); + } + + private function ellipseEnterFrameHandler(e:Event) { + if(e.target.y > 0) { + e.target.y -= 1; + e.target.x -= 1; + } + } + + private function triangleEnterFrameHandler(e:Event) { + e.target.transform.matrix3D.pointAt(ellipse.transform.matrix3D.position, + Vector3D.X_AXIS, Vector3D.Y_AXIS); + } + } +} +
flash.geom.Utils3D.pointTowards()
prependRotation + Prepends an incremental rotation to a Matrix3D object.degreesNumberThe degree of rotation. + axisflash.geom:Vector3DThe axis or direction of rotation. The usual axes are the X_AXIS (Vector3D(1,0,0)), + Y_AXIS (Vector3D(0,1,0)), and Z_AXIS (Vector3D(0,0,1)). + pivotPointflash.geom:Vector3DnullA point that determines the center of rotation. The default pivot point + for an object is its registration point. + + + Prepends an incremental rotation to a Matrix3D object. When the Matrix3D object is applied + to a display object, the matrix performs the rotation before other transformations in the Matrix3D + object. + +

The display object's rotation is defined by an axis, an incremental degree + of rotation around the axis, and an optional pivot point for the center of the object's rotation. + The axis can be any general direction. The common axes are the X_AXIS (Vector3D(1,0,0)), + Y_AXIS (Vector3D(0,1,0)), and Z_AXIS (Vector3D(0,0,1)). + In aviation terminology, the rotation about the y axis is called yaw. + The rotation about the x axis is called pitch. + The rotation about the z axis is called roll.

+ +

The order of transformation matters. A rotation followed by a translation transformation + produces a different effect than a translation followed by a rotation.

+ +

The rotation effect is not absolute. The effect is object-relative, relative to the frame + of reference of the original position and orientation. To make an absolute change to the transformation, + use the recompose() method.

+ +

When the prependRotation() method's transformation is applied to a Matrix3D object + of a display object, the cached rotation property values of the display object are invalidated.

+ +

One way to have a display object rotate around a specific point relative to its location is + to set the translation of the object to the specified point, rotate the object using + the prependRotation() method, and translate the object back to the original position. + In the following example, the myObject 3D display object makes a y-axis rotation around + the coordinate (10,10,0).

+ + + + myObject.z = 1; + myObject.transform.matrix3D.prependTranslation(10,10,0); + myObject.transform.matrix3D.prependRotation(1, Vector3D.Y_AXIS); + myObject.transform.matrix3D.prependTranslation(-10,-10,0); + + + +
In this example, the user can move a mouse to rotate an ellipse + around its x and y axes. The ellipse is drawn + with its registration point in its center. The ellipse rotates + around its y axis using the mouse's x coordinate. + It rotates around its x axis using the mouse's y coordinate. + + +package { + import flash.display.MovieClip; + import flash.display.Shape; + import flash.geom.*; + import flash.events.MouseEvent; + + public class Matrix3DprependRotationExample extends MovieClip { + private var ellipse:Shape = new Shape(); + + public function Matrix3DprependRotationExample():void { + + ellipse.graphics.beginFill(0xFF0000); + ellipse.graphics.lineStyle(2); + ellipse.graphics.drawEllipse(-50, -40, 100, 80); + ellipse.graphics.endFill(); + + ellipse.x = (this.stage.stageWidth / 2); + ellipse.y = (this.stage.stageHeight / 2); + ellipse.z = 1; + + addChild(ellipse); + + stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function mouseMoveHandler(e:MouseEvent):void { + var y:int; + var x:int; + + if(e.localX > ellipse.x) { + y = (Math.round(e.localX) / 100); + } else { + y = -(Math.round(e.localX) / 10); + } + + if(e.localY > ellipse.y) { + x = (Math.round(e.localY) / 100); + } else { + x = -(Math.round(e.localY) / 100); + } + + ellipse.transform.matrix3D.prependRotation(y, Vector3D.Y_AXIS); + ellipse.transform.matrix3D.prependRotation(x, Vector3D.X_AXIS); + } + + } +} +
appendRotation()
prependScale + Prepends an incremental scale change along the x, y, and z axes to a Matrix3D object.xScaleNumberA multiplier used to scale the object along the x axis. + yScaleNumberA multiplier used to scale the object along the y axis. + zScaleNumberA multiplier used to scale the object along the z axis. + + + Prepends an incremental scale change along the x, y, and z axes to a Matrix3D object. + When the Matrix3D object is applied to a display object, the matrix performs + the scale changes before other transformations in the Matrix3D object. The changes are + object-relative, relative to the frame of reference of the original position and orientation. + The default scale factor is (1.0, 1.0, 1.0). + +

The scale is defined as a set of three incremental changes along the three axes (x,y,z). + You can multiply each axis with a different number. When the scale changes are applied to + a display object, the object's size increases or decreases. For example, setting + the x, y, and z axes to two doubles the size of the object, while + setting the axes to 0.5 halves the size. To make sure that + the scale transformation only affects a specific axis, set the other parameters to one. + A parameter of one means no scale change along the specific axis.

+ +

The prependScale() method can be used for resizing as well as + for managing distortions, such as stretch or contract of a display object. It can also be + used for zooming in and out on a location. Scale transformations are automatically + performed during a display object's rotation and translation.

+ +

The order of transformation matters. A resizing followed by a translation transformation + produces a different effect than a translation followed by a resizing transformation.

+ +
appendScale()
prependTranslation + Prepends an incremental translation, a repositioning along the x, y, + and z axes, to a Matrix3D object.xNumberAn incremental translation along the x axis. + yNumberAn incremental translation along the y axis. + zNumberAn incremental translation along the z axis. + + + Prepends an incremental translation, a repositioning along the x, y, + and z axes, to a Matrix3D object. When the Matrix3D object is applied to a + display object, the matrix performs the translation changes before other transformations + in the Matrix3D object. + +

Translation specifies the distance the display object moves from its current location along + the x, y, and z axes. The prependTranslation() method + sets the translation as a set of three incremental changes along the three axes (x,y,z). + To have a translation change only a specific axis, set the other parameters to zero. + A zero parameter means no change along the specific axis.

+ +

The translation changes are not absolute. The effect is object-relative, relative to the frame + of reference of the original position and orientation. To make an absolute change to the transformation + matrix, use the recompose() method. The order of transformation also matters. A translation + followed by a rotation transformation produces a different effect than a rotation followed by a translation + transformation. When prependTranslation() is used, the display object continues to move + in the direction it is facing, regardless of the other transformations. For example, if a display object + was facing toward a positive x axis, it continues to move in the direction specified + by the prependTranslation() method, regardless of how the object has been rotated. To make + translation changes occur after other transformations, use the appendTranslation() method.

+ + +
In this example, the user can push an ellipse up the stage's y axis + using a mouse. When the user moves the mouse over the ellipse, the ellipse + jumps ten coordinates up the y axis. When the mouse moves off of + the ellipse, if the ellipse has not reached the top, the ellipse again jumps + ten coordinates up the y axis. Once the ellipse reaches the top, + it is moved back to the bottom of the stage. + +package { + import flash.display.MovieClip; + import flash.display.Sprite; + import flash.geom.*; + import flash.events.MouseEvent; + + public class Matrix3DprependTranslationExample extends MovieClip { + private var ellipse:Sprite = new Sprite(); + + public function Matrix3DprependTranslationExample():void { + ellipse.x = this.stage.stageWidth / 2; + ellipse.y = this.stage.stageHeight - 100; + ellipse.z = 1; + ellipse.graphics.beginFill(0xFF0000); + ellipse.graphics.lineStyle(2); + ellipse.graphics.drawEllipse(0, 0, 60, 50); + ellipse.graphics.endFill(); + addChild(ellipse); + + ellipse.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); + ellipse.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); + } + + private function mouseOverHandler(e:MouseEvent):void { + if(ellipse.y > 0) { + ellipse.transform.matrix3D.prependTranslation(0, -10, 0); + } + } + + private function mouseOutHandler(e:MouseEvent):void { + if(ellipse.y > 0) { + ellipse.transform.matrix3D.prependTranslation(0, -10, 0); + } else { + ellipse.transform.matrix3D.prependTranslation(0, + (this.stage.stageHeight - 100), 0); + } + } + } +} +
appendTranslation()
prepend + Prepends a matrix by multiplying the current Matrix3D object by another Matrix3D object.rhsflash.geom:Matrix3DA right-hand-side of the matrix by which the current Matrix3D is multiplied. + + + Prepends a matrix by multiplying the current Matrix3D object by another Matrix3D object. + The result combines both matrix transformations. + +

Matrix multiplication is different from matrix addition. Matrix multiplication is not commutative. + In other words, A times B is not equal to B times A. With the prepend() method, + the multiplication happens from the right side, meaning the rhs Matrix3D object is + on the right side of the multiplication operator.

+ + thisMatrix = thisMatrix ~~ rhs + +

The modifications made by prepend() method are object-space-relative. In other words, + they are always relative to the object's initial frame of reference.

+ +

The prepend() method replaces the current matrix with the prepended matrix. + If you want to prepend two matrixes without altering the current matrix, first copy the + current matrix by using the clone() method and then apply the prepend() + method to the copy.

+ +
append()
recompose + Sets the transformation matrix's translation, rotation, and scale settings.Returns false if any of the scale elements are zero. + + BooleancomponentsA Vector of three Vector3D objects that replace the Matrix3D + object's translation, rotation, and scale elements. + + orientationStyleStringeulerAnglesAn optional parameter that determines the orientation style + used for the matrix transformation. The three types of orientation styles are + eulerAngles (constant EULER_ANGLES), axisAngle + (constant AXIS_ANGLE), and quaternion (constant QUATERNION). + For additional information on the different orientation style, see the geom.Orientation3D class. + + + Sets the transformation matrix's translation, rotation, and scale settings. + Unlike the incremental changes made by the display object's rotation properties or + Matrix3D object's rotation methods, the changes made by recompose() method + are absolute changes. The recompose() method overwrites the matrix's transformation. + +

To modify the matrix's transformation with an absolute parent frame of reference, retrieve + the settings with the decompose() method and make the appropriate changes. You can then + set the Matrix3D object to the modified transformation using the recompose() method.

+ +

The recompose() method's parameter specifies the orientation style that was used + for the transformation. The default orientation is eulerAngles, + which defines the orientation with three separate angles of rotation for each axis. + The rotations occur consecutively and do not change the axis of each other. The + display object's axis rotation properties perform Euler Angles orientation style transformation. + The other orientation style options are axisAngle and quaternion. + The Axis Angle orientation uses the combination of an axis and an angle to determine the orientation. + The axis around which the object is rotated is a unit vector that represents a direction. + The angle represents the magnitude of the rotation about the vector. The direction also + determines where a display object is facing and the angle determines which way is up. + The appendRotation() and prependRotation() methods use the Axis Angle orientation. + The quaternion orientation uses complex numbers and the fourth element of a vector. + An orientation is represented by the three axes of rotation (x,y,z) and an angle of + rotation (w). The interpolate() method uses quaternion.

+ +
flash.geom.Orientation3Ddecompose()Vector
transformVector + Uses the transformation matrix to transform a Vector3D object from one space coordinate + to another.A Vector3D object with the transformed coordinates. + + flash.geom:Vector3Dvflash.geom:Vector3DA Vector3D object holding the coordinates that are going to be transformed. + + + Uses the transformation matrix to transform a Vector3D object from one space coordinate + to another. The returned Vector3D object holds the new coordinates after the transformation. + All the matrix transformations including translation are applied to the Vector3D object. + +

If the result of the transformVector() method was applied to the position + of a display object, only the display object's position changes. + The display object's rotation and scale elements remain the same.

+ +
transformVectors()deltaTransformVector()
transformVectors + Uses the transformation matrix to transform a Vector of Numbers from one + coordinate space to another.vinA Vector of Numbers, where every three Numbers are a 3D coordinate + (x,y,z) that is going to be transformed. + voutA Vector of Numbers, where every three Numbers are a 3D + transformed coordinate (x,y,z). + + + + Uses the transformation matrix to transform a Vector of Numbers from one + coordinate space to another. The tranformVectors() method reads every + three Numbers in the vin Vector object as a 3D coordinate + (x,y,z) and places a transformed 3D coordinate in the vout + Vector object. All the matrix transformations including translation are applied to the + vin Vector object. You can use the transformVectors() method + to render and transform a 3D object as a mesh. A mesh is a collection of + vertices that defines the shape of the object. + + transformVector()deltaTransformVector()Vectortranspose + Converts the current Matrix3D object to a matrix where the rows and columns + are swapped. + Converts the current Matrix3D object to a matrix where the rows and columns + are swapped. For example, if the current Matrix3D object's rawData contains + the following 16 numbers, 1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34, + the transpose() method reads every four elements as a row and turns the rows + into columns. The result is a matrix with the rawData of: + 1,11,21,31,2,12,22,32,3,13,23,33,4,14,24,34. + +

The transpose() method replaces the current matrix with a transposed matrix. + If you want to transpose a matrix without altering the current matrix, first copy the + current matrix by using the clone() method and then apply the transpose() + method to the copy.

+ +

An orthogonal matrix is a square matrix whose transpose is equal to its inverse.

+ + +
determinant + A Number that determines whether a matrix is invertible.Number + A Number that determines whether a matrix is invertible. + +

A Matrix3D object must be invertible. You can use the determinant + property to make sure that a Matrix3D object is invertible. If determinant is zero, + an inverse of the matrix does not exist. For example, if an entire row or column + of a matrix is zero or if two rows or columns are equal, the determinant is zero. + Determinant is also used to solve a series of equations.

+ +

Only a square matrix, like the Matrix3D class, has a determinant.

+ +
invert()
position + A Vector3D object that holds the position, the 3D coordinate (x,y,z) of a display object + within the transformation's frame of reference.flash.geom:Vector3D + A Vector3D object that holds the position, the 3D coordinate (x,y,z) of a display object + within the transformation's frame of reference. The position property provides immediate + access to the translation vector of the display object's matrix without needing to decompose and + recompose the matrix. + +

With the position property, you can get and set the translation elements + of the transformation matrix.

+ + +
appendTranslation()prependTranslation()
rawData + A Vector of 16 Numbers, where every four elements can be a row or + a column of a 4x4 matrix. + A Vector of 16 Numbers, where every four elements can be a row or + a column of a 4x4 matrix. + +

An exception is thrown if the rawData property is set to a matrix + that is not invertible. The Matrix3D object must be invertible. If a non-invertible matrix + is needed, create a subclass of the Matrix3D object.

+ +
Vector
Transform + The Transform class provides access to color adjustment properties and two- or three-dimensional + transformation objects that can be applied to a display object.Provides access to color as well as two and three-dimensional transformation objects + and matrices that can be applied to a display object. + + Object + The Transform class provides access to color adjustment properties and two- or three-dimensional + transformation objects that can be applied to a display object. During the transformation, + the color or the orientation and position of a display object is adjusted (offset) from + the current values or coordinates to new values or coordinates. + The Transform class also collects data about color and two-dimensional matrix transformations + that are applied to a display object and all of its parent objects. You can access + these combined transformations through the concatenatedColorTransform + and concatenatedMatrix properties. + +

To apply color transformations: create a ColorTransform object, + set the color adjustments using the object's methods and properties, and then assign the + colorTransformation property of the transform property of the + display object to the new ColorTransformation object.

+ +

To apply two-dimensional transformations: create a Matrix object, + set the matrix's two-dimensional transformation, and then assign the transform.matrix + property of the display object to the new Matrix object.

+ +

To apply three-dimensional transformations: start with a three-dimensional display object. + A three-dimensional display object has a z property value other than zero. + You do not need to create the Matrix3D object. For all three-dimensional objects, a Matrix3D object + is created automatically when you assign a z value to a display object. You can + access the display object's Matrix3D object through the display object's transform property. + Using the methods of the Matrix3D class, you can add to or modify the existing transformation settings. Also, you can + create a custom Matrix3D object, set the custom Matrix3D object's transformation elements, + and then assign the new Matrix3D object to the display object using the transform.matrix + property.

+ +

To modify a perspective projection of the stage or root object: + use the transform.matrix property of the root display object to gain access to the + PerspectiveProjection object. Or, apply different perspective projection + properties to a display object by setting the perspective projection properties of the display + object's parent. The child display object inherits the new properties. Specifically, create a + PerspectiveProjection object and set its properties, then assign the PerspectiveProjection + object to the perspectiveProjection property of the parent display object's + transform property. The specified projection transformation then applies + to all the display object's three-dimensional children.

+ +

Since both PerspectiveProjection and Matrix3D objects perform perspective transformations, + do not assign both to a display object at the same time. Use the PerspectiveProjection object + for focal length and projection center changes. For more control over the perspective transformation, + create a perspective projection Matrix3D object.

+ + +
The following example uses the TransformExample class to skew the bottom side + of a square sprite filled with a gradient pattern. Each time the user clicks the square, the + application transforms the sprite by skewing it with the following steps: + +
  1. The TransformExample() constructor creates a new sprite object target.
  2. The TransformExample() constructor calls the draw() method, + which draws a gradient square in the sprite.
  3. The TransformExample() constructor adds a click event listener for the sprite, + which is handled by the clickHandler() method.
  4. The clickHandler() method creates a new Matrix object, skewMatrix, + which is set to apply a skew effect. Another matrix, tempMatrix, is assigned to the + current transformation matrix of the sprite, and then is combined with skewMatrix + using the concat() method. This matrix is assigned to the + transform.matrix property of the square sprite. Each time the user clicks the square, + the call to the clickHandler() modifies the shape of the square by skewing it.
  5. Additionally, the clickHandler() method creates a new ColorTransform object. The + redOffset property of the new ColorTransform is set to the current value of redOffset and + increased by 25. Likewise, the blueOffset property is reduced by 25. With each click, + the colors of the sprite change.
+ +package { + import flash.display.Sprite; + import flash.display.GradientType; + import flash.geom.Matrix; + import flash.geom.ColorTransform; + import flash.events.MouseEvent; + + public class TransformExample extends Sprite { + public function TransformExample() { + var target:Sprite = new Sprite(); + draw(target); + addChild(target); + target.useHandCursor = true; + target.buttonMode = true; + target.addEventListener(MouseEvent.CLICK, clickHandler) + } + public function draw(sprite:Sprite):void { + var red:uint = 0xFF0000; + var green:uint = 0x00FF00; + var blue:uint = 0x0000FF; + var size:Number = 100; + sprite.graphics.beginGradientFill(GradientType.LINEAR, [red, blue, green], [1, 0.5, 1], [0, 200, 255]); + sprite.graphics.drawRect(0, 0, 100, 100); + } + public function clickHandler(event:MouseEvent):void { + var skewMatrix:Matrix = new Matrix(); + skewMatrix.c = 0.25; + var tempMatrix:Matrix = this.transform.matrix; + tempMatrix.concat(skewMatrix); + this.transform.matrix = tempMatrix; + + var rOffset:Number = this.transform.colorTransform.redOffset + 25; + var bOffset:Number = this.transform.colorTransform.blueOffset - 25; + this.transform.colorTransform = new ColorTransform(1, 1, 1, 1, rOffset, 0, bOffset, 0); + } + } +} +
flash.display.DisplayObject.transformflash.geom.ColorTransformflash.geom.Matrixflash.geom.Matrix3Dflash.geom.PerspectiveProjectiongetRelativeMatrix3D + Returns a Matrix3D object, which can transform the space of a specified + display object in relation to the current display object's space.A Matrix3D object that can be used to transform the space from the relativeTo + display object to the current display object space. + + flash.geom:Matrix3DrelativeToflash.display:DisplayObjectThe display object relative to which the transformation occurs. + To get a Matrix3D object relative to the stage, set the parameter to the root + or stage object. To get the world-relative matrix of the display object, + set the parameter to a display object that has a perspective transformation applied to it. + + + Returns a Matrix3D object, which can transform the space of a specified + display object in relation to the current display object's space. You can use the + getRelativeMatrix3D() method to move one three-dimensional display + object relative to another three-dimensional display object. + + flash.geom.Matrix3DcolorTransform + A ColorTransform object containing values that universally adjust the colors in + the display object.flash.geom:ColorTransformThe colorTransform is null when being set + + TypeErrorTypeError + A ColorTransform object containing values that universally adjust the colors in + the display object. + + flash.geom.ColorTransformconcatenatedColorTransform + A ColorTransform object representing the combined color transformations applied to the display object + and all of its parent objects, back to the root level.flash.geom:ColorTransform + A ColorTransform object representing the combined color transformations applied to the display object + and all of its parent objects, back to the root level. + If different color transformations have been applied at different levels, all of those transformations are + concatenated into one ColorTransform object + for this property. + + flash.geom.ColorTransformconcatenatedMatrix + A Matrix object representing the combined transformation matrixes of the + display object and all of its parent objects, back to the root level.flash.geom:Matrix + A Matrix object representing the combined transformation matrixes of the + display object and all of its parent objects, back to the root level. + If different transformation matrixes have been applied at different levels, + all of those matrixes are concatenated into one matrix + for this property. Also, for resizeable SWF content running in the browser, + this property factors in the difference between stage coordinates and window + coordinates due to window resizing. Thus, the property converts local coordinates + to window coordinates, which may not be the same coordinate space as that of + the Stage. + + matrix3D + Provides access to the Matrix3D object of a three-dimensional display object.flash.geom:Matrix3D + Provides access to the Matrix3D object of a three-dimensional display object. + The Matrix3D object represents a transformation matrix that determines the + display object's position and orientation. A Matrix3D object can also + perform perspective projection. + + +

If the matrix property is set to a value (not null), the + matrix3D property is null. And if the matrix3D property + is set to a value (not null), the matrix property is null.

+ +
flash.geom.Matrix3D
matrix + A Matrix object containing values that alter the scaling, rotation, + and translation of the display object.flash.geom:MatrixThe matrix is null when being set + + TypeErrorTypeError + A Matrix object containing values that alter the scaling, rotation, + and translation of the display object. + + +

If the matrix property is set to a value (not null), the + matrix3D property is null. And if the matrix3D property + is set to a value (not null), the matrix property is null.

+ +
flash.geom.Matrix
perspectiveProjection + Provides access to the PerspectiveProjection object of a three-dimensional display + object.flash.geom:PerspectiveProjection + Provides access to the PerspectiveProjection object of a three-dimensional display + object. The PerspectiveProjection object can be used to modify the perspective + transformation of the stage or to assign a perspective transformation to all the + three-dimensional children of a display object. + +

Based on the field of view and aspect ratio (dimensions) of the stage, a + default PerspectiveProjection object is assigned to the root object.

+ +
flash.geom.PerspectiveProjection
pixelBounds + A Rectangle object that defines the bounding rectangle of the display object on the stage.flash.geom:Rectangle + A Rectangle object that defines the bounding rectangle of the display object on the stage. + +
Matrix + The Matrix class represents a transformation matrix that determines how to map points from one + coordinate space to another.A standard two-dimensional homogeneous Matrix class. + + Object + The Matrix class represents a transformation matrix that determines how to map points from one + coordinate space to another. You can perform various graphical + transformations on a display object by setting the properties of a Matrix object, + applying that Matrix object to the matrix property of a Transform object, + and then applying that Transform object as the transform property of the display object. + These transformation functions include translation + (x and y repositioning), rotation, scaling, and skewing. + +

Together these types of transformations are known as affine transformations. + Affine transformations preserve the straightness of lines while transforming, so that + parallel lines stay parallel.

+ +

To apply a transformation matrix to a display object, you create a Transform + object, set its matrix property to the transformation matrix, and then set the transform + property of the display object to the Transform object. + Matrix objects are also used as parameters of some methods, such as the following:

+ +
  • The draw() method of a BitmapData object
  • The beginBitmapFill() method, beginGradientFill() method, + or lineGradientStyle() method of a Graphics object
+ +

A transformation matrix object is a 3 x 3 matrix with the following contents:

+ +

+ +

In traditional transformation matrixes, the u, v, and w + properties provide extra capabilities. + The Matrix class can only operate in two-dimensional space, so it always + assumes that the property values u and v are 0.0, and that the property value + w is 1.0. The effective values of the matrix are as follows:

+ +

+ +

You can get and set the values of all six of the other properties in a Matrix + object: a, b, c, + d, tx, and ty.

+ +

The Matrix class supports the four major types of transformations: + translation, scaling, rotation, and skewing. You can set three of these transformations by using + specialized methods, as described in the following table:

+ + TransformationMethodMatrix valuesDisplay resultDescriptionTranslation (displacement)translate(tx, ty) Moves the image tx pixels to the right and ty pixels + down.Scalingscale(sx, sy)Resizes the image, multiplying the location of each pixel by sx on the + x axis and sy on the y axis.Rotationrotate(q)Rotates the image by an angle q, which is measured in radians.Skewing or shearing None; must set the properties b and cProgressively slides the image in a direction parallel to the x or y axis. The b + property of the Matrix object represents the tangent of the skew angle along the y axis; + the c property of the Matrix object represents the tangent of the skew angle along the + x axis. +

Each transformation function alters the current matrix properties so that + you can effectively combine multiple transformations. To do this, you call more than one + transformation function before applying the matrix to its display object target (by using the + transform property of that display object).

+ +

Use the new Matrix() constructor to create a + Matrix object before you can call the methods of the Matrix object.

+ +
The following example uses the MatrixExample class to show + how a large gradient-filled square can be created. This is accomplished with the following + steps: +
  1. The application creates a new Matrix object myMatrix, and it uses the + trace() method to output + the default property values for the myMatrix object.
  2. The application calls the createGradientBox() with the width + and height parameters set to 200 pixels, no rotation, and the distance to translate along + the x and y axes set to 50 pixels.
  3. The application prints the myMatrix object again to show the change after calling + createGradientBox().
  4. The application sets up three variables to control how the gradient box is filled: +
    • colors: Sets the gradient colors to range between solid red and solid blue.
    • alphas: Sets the opacity to solid.
    • ratios: Sets the distribution of the colors to be equal for both red and blue.
  5. The application calls the graphics method beginGradientFill(), which operates on the myMatrix + object, and it calls the lineTo() method, resulting in the gradient-filled box.
+ +package { + import flash.geom.Matrix; + import flash.display.Sprite; + import flash.display.GradientType; + + public class MatrixExample extends Sprite { + + public function MatrixExample() { + var myMatrix:Matrix = new Matrix(); + trace(myMatrix.toString()); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + + myMatrix.createGradientBox(200, 200, 0, 50, 50); + trace(myMatrix.toString()); // (a=0.1220703125, b=0, c=0, d=0.1220703125, tx=150, ty=150) + + var colors:Array = [0xFF0000, 0x0000FF]; + var alphas:Array = [1, 1]; + var ratios:Array = [0, 0xFF]; + graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, myMatrix); + graphics.lineTo(0, 300); + graphics.lineTo(300, 300); + graphics.lineTo(300, 0); + graphics.lineTo(0, 0); + } + } +} +
flash.display.DisplayObject.transformflash.geom.Transformflash.display.BitmapData.draw()flash.display.Graphics.beginBitmapFill()flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()Matrix + Creates a new Matrix object with the specified parameters.aNumber1The value that affects the positioning of pixels + along the x axis when scaling or rotating an image. + bNumber0The value that affects the positioning of pixels + along the y axis when rotating or skewing an image. + cNumber0The value that affects the positioning of pixels + along the x axis when rotating or skewing an image. + dNumber1The value that affects the positioning of pixels + along the y axis when scaling or rotating an image.. + txNumber0The distance by which to translate each point along the x axis. + tyNumber0The distance by which to translate each point along the y axis. + + Creates a new two-dimensional Matrix object. + + + Creates a new Matrix object with the specified parameters. In matrix notation, the properties + are organized like this: + +

+ +

If you do not provide any parameters to the new Matrix() constructor, it creates an + identity matrix with the following values:

+
a = 1
b = 0
c = 0
d = 1
tx = 0
ty = 0
+

In matrix notation, the identity matrix looks like this:

+ +

+ +
The following example creates matrix_1 by sending no parameters to the + Matrix() constructor and matrix_2 by sending parameters to it. Notice that + matrix_1, which was created with no parameters, results in an identity matrix with the values + a=1, b=0, c=0, d=1, tx=0, + ty=0. + +import flash.geom.Matrix; + +var matrix_1:Matrix = new Matrix(); +trace(matrix_1); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + +var matrix_2:Matrix = new Matrix(1, 2, 3, 4, 5, 6); +trace(matrix_2); // (a=1, b=2, c=3, d=4, tx=5, ty=6) +
clone + Returns a new Matrix object that is a clone of this + matrix, with an exact copy of the contained object.A Matrix object. + + flash.geom:MatrixReturns a new Matrix object that is a copy of the current matrix. + + + Returns a new Matrix object that is a clone of this + matrix, with an exact copy of the contained object. + + concat + Concatenates a matrix with the current matrix, effectively combining the + geometric effects of the two.mflash.geom:MatrixThe matrix to be concatenated to the source matrix. + + + Concatenates a matrix with the current matrix, effectively combining the + geometric effects of the two. In mathematical terms, concatenating two matrixes + is the same as combining them using matrix multiplication. + +

For example, if matrix m1 scales an object by a factor of four, and + matrix m2 rotates an object by 1.5707963267949 radians + (Math.PI/2), then m1.concat(m2) transforms m1 + into a matrix that scales an object by a factor of four and rotates the object by + Math.PI/2 radians.

+ +

This method replaces the source matrix with the concatenated matrix. If you + want to concatenate two matrixes without altering either of the two source matrixes, + first copy the source matrix by using the clone() method, as shown in the Class Examples section.

+ +
createBox + Includes parameters for scaling, + rotation, and translation.scaleXNumberThe factor by which to scale horizontally. + + scaleYNumberThe factor by which scale vertically. + + rotationNumber0The amount to rotate, in radians. + + txNumber0The number of pixels to translate (move) to the right along the x axis. + + tyNumber0The number of pixels to translate (move) down along the y axis. + + Creates a Matrix with scaling, rotation, and translation values. + + + Includes parameters for scaling, + rotation, and translation. When applied to a matrix it sets the matrix's values + based on those parameters. + +

Using the createBox() method lets you obtain the same matrix as you would if + you applied the identity(), rotate(), scale(), and translate() methods + in succession. For example, mat1.createBox(2,2,Math.PI/4, 100, 100) has the + same effect as the following:

+ + + import flash.geom.Matrix; + + var mat1:Matrix = new Matrix(); + mat1.identity(); + mat1.rotate(Math.PI/4); + mat1.scale(2,2); + mat1.translate(10,20); + + + + +
The following example sets the x scale, y scale, rotation, x location, + and y location of myMatrix by calling its createBox() method. + + +package +{ + import flash.display.Shape; + import flash.display.Sprite; + import flash.geom.Matrix; + import flash.geom.Transform; + + public class Matrix_createBox extends Sprite + { + public function Matrix_createBox() + { + var myMatrix:Matrix = new Matrix(); + trace(myMatrix.toString()); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + + myMatrix.createBox(1, 2, Math.PI/4, 50, 100); + trace(myMatrix.toString()); + // (a=0.7071067811865476, b=1.414213562373095, c=-0.7071067811865475, + // d=1.4142135623730951, tx=100, ty=200) + + var rectangleShape:Shape = createRectangle(20, 80, 0xFF0000); + addChild(rectangleShape); + + var rectangleTrans:Transform = new Transform(rectangleShape); + rectangleTrans.matrix = myMatrix; + } + + public function createRectangle(w:Number, h:Number, color:Number):Shape + { + var rect:Shape = new Shape(); + rect.graphics.beginFill(color); + rect.graphics.drawRect(0, 0, w, h); + addChild(rect); + return rect; + } + } +} +
flash.display.Graphics.beginBitmapFill()
createGradientBox + Creates the specific style of matrix expected by the beginGradientFill() and + lineGradientStyle() methods of the Graphics class.widthNumberThe width of the gradient box. + + heightNumberThe height of the gradient box. + + rotationNumber0The amount to rotate, in radians. + + txNumber0The distance, in pixels, to translate to the right along the x axis. + This value is offset by half of the width parameter. + + tyNumber0The distance, in pixels, to translate down along the y axis. + + This value is offset by half of the height parameter. + + Creates the specific style of matrix expected by the beginGradientFill() method of the Graphics class. + + + Creates the specific style of matrix expected by the beginGradientFill() and + lineGradientStyle() methods of the Graphics class. Width and height are scaled to + a scaleX/scaleY pair and the tx/ty + values are offset by half the width and height. + +

For example, consider a gradient with the following characteristics:

+ +
  • GradientType.LINEAR
  • Two colors, green and blue, with the ratios array set to [0, 255]
  • SpreadMethod.PAD
  • InterpolationMethod.LINEAR_RGB
+ +

The following illustrations show gradients in which the matrix was defined using the + createGradientBox() method with different parameter settings:

+ + createGradientBox() settingsResulting gradient
width = 25;
+     height = 25; 
+     rotation = 0; 
+     tx = 0; 
+     ty = 0;
width = 25; 
+     height = 25; 
+     rotation = 0; 
+     tx = 25; 
+     ty = 0;
width = 50; 
+     height = 50; 
+     rotation = 0; 
+     tx = 0; 
+     ty = 0;
width = 50;
+     height = 50; 
+     rotation = Math.PI / 4; // 45 degrees
+     tx = 0; 
+     ty = 0;
+ +
The following example sets the x scale, y scale, rotation, x location, + and y location of myMatrix by calling its createBox() method. + + +package +{ + import flash.display.GradientType; + import flash.display.Sprite; + import flash.geom.Matrix; + + public class Matrix_createGradientBox extends Sprite + { + public function Matrix_createGradientBox() + { + var myMatrix:Matrix = new Matrix(); + trace(myMatrix.toString()); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + + myMatrix.createGradientBox(200, 200, 0, 50, 50); + trace(myMatrix.toString()); // (a=0.1220703125, b=0, c=0, d=0.1220703125, tx=150, ty=150) + + var colors:Array = [0xFF0000, 0x0000FF]; + var alphas:Array = [100, 100]; + var ratios:Array = [0, 0xFF]; + + this.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, myMatrix); + this.graphics.drawRect(0, 0, 300, 200); + } + } +} +
flash.display.Graphics.beginGradientFill()flash.display.Graphics.lineGradientStyle()
deltaTransformPoint + Given a point in the pretransform coordinate space, returns the coordinates of + that point after the transformation occurs.The point resulting from applying the matrix transformation. + + flash.geom:Pointpointflash.geom:PointThe point for which you want to get the result of the matrix transformation. + + + Given a point in the pretransform coordinate space, returns the coordinates of + that point after the transformation occurs. Unlike the standard transformation applied using + the transformPoint() method, the deltaTransformPoint() method's + transformation does not consider the translation parameters tx and ty. + + identity + Sets each matrix property to a value that causes a null transformation. + Sets each matrix property to a value that causes a null transformation. An object transformed + by applying an identity matrix will be identical to the original. + +

After calling the identity() method, the resulting matrix has the following properties: + a=1, b=0, c=0, d=1, tx=0, ty=0.

+ +

In matrix notation, the identity matrix looks like this:

+ +

+ +
invert + Performs the opposite transformation + of the original matrix. + Performs the opposite transformation + of the original matrix. You can apply an inverted matrix to an object to undo the transformation + performed when applying the original matrix. + + The following example creates a halfScaleMatrix by calling the + invert() method of doubleScaleMatrix. It then demonstrates that + the two are Matrix inverses of one another -- matrices that undo any + transformations performed by the other -- by creating originalAndInverseMatrix + which is equal to noScaleMatrix. + + +package +{ + import flash.display.Shape; + import flash.display.Sprite; + import flash.geom.Matrix; + import flash.geom.Transform; + + public class Matrix_invert extends Sprite + { + public function Matrix_invert() + { + var rect0:Shape = createRectangle(20, 80, 0xFF0000); + var rect1:Shape = createRectangle(20, 80, 0x00FF00); + var rect2:Shape = createRectangle(20, 80, 0x0000FF); + var rect3:Shape = createRectangle(20, 80, 0x000000); + + var trans0:Transform = new Transform(rect0); + var trans1:Transform = new Transform(rect1); + var trans2:Transform = new Transform(rect2); + var trans3:Transform = new Transform(rect3); + + var doubleScaleMatrix:Matrix = new Matrix(2, 0, 0, 2, 0, 0); + trans0.matrix = doubleScaleMatrix; + trace(doubleScaleMatrix.toString()); // (a=2, b=0, c=0, d=2, tx=0, ty=0) + + var noScaleMatrix:Matrix = new Matrix(1, 0, 0, 1, 0, 0); + trans1.matrix = noScaleMatrix; + rect1.x = 50; + trace(noScaleMatrix.toString()); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + + var halfScaleMatrix:Matrix = doubleScaleMatrix.clone(); + halfScaleMatrix.invert(); + trans2.matrix = halfScaleMatrix; + rect2.x = 100; + trace(halfScaleMatrix.toString()); // (a=0.5, b=0, c=0, d=0.5, tx=0, ty=0) + + var originalAndInverseMatrix:Matrix = doubleScaleMatrix.clone(); + originalAndInverseMatrix.concat(halfScaleMatrix); + trans3.matrix = originalAndInverseMatrix; + rect3.x = 150; + trace(originalAndInverseMatrix.toString()); // (a=1, b=0, c=0, d=1, tx=0, ty=0) + } + + public function createRectangle(w:Number, h:Number, color:Number):Shape + { + var rect:Shape = new Shape(); + rect.graphics.beginFill(color); + rect.graphics.drawRect(0, 0, w, h); + addChild(rect); + return rect; + } + } +} +rotate + Applies a rotation transformation to the Matrix object.angleNumberThe rotation angle in radians. + + + + Applies a rotation transformation to the Matrix object. + +

The rotate() method alters the a, b, c, + and d properties of the Matrix object. + In matrix notation, this is the same as concatenating the current matrix with the following:

+ +

+ +
scale + Applies a scaling transformation to the matrix.sxNumberA multiplier used to scale the object along the x axis. + syNumberA multiplier used to scale the object along the y axis. + + + Applies a scaling transformation to the matrix. The x axis is multiplied + by sx, and the y axis it is multiplied by sy. + +

The scale() method alters the a and d properties of + the Matrix object. + In matrix notation, this is the same as concatenating the current matrix with the following matrix:

+

+ +
toString + Returns a text value listing the properties of the Matrix object.A string containing the values of the properties of the Matrix object: a, b, c, + d, tx, and ty. + StringReturns a text value listing the properties of this Matrix object. + + Returns a text value listing the properties of the Matrix object. + + transformPoint + Returns the result of applying the geometric transformation represented by the Matrix object to the + specified point.The point resulting from applying the Matrix transformation. + + + flash.geom:Pointpointflash.geom:PointThe point for which you want to get the result of the Matrix transformation. + + Returns the result of a geometric transformation to a Point object. + + + Returns the result of applying the geometric transformation represented by the Matrix object to the + specified point. + + translate + Translates the matrix along the x and y axes, as specified by the dx + and dy parameters.dxNumberThe amount of movement along the x axis to the right, in pixels. + + dyNumberThe amount of movement down along the y axis, in pixels. + + + Translates the matrix along the x and y axes. + +

The translate() method alters the tx and ty properties of + the matrix object. + + In matrix notation, this is the same as concatenating the current matrix with the following:

+ +

+ +
+ Translates the matrix along the x and y axes, as specified by the dx + and dy parameters. + +
a + The value that affects the positioning of pixels + along the x axis when scaling or rotating an image.NumberThe value that affects the positioning of pixels + along the x axis when scaling or rotating an image. + + + The value that affects the positioning of pixels + along the x axis when scaling or rotating an image. + + The following example creates the Matrix object myMatrix and sets its + a value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.a); // 1 + +myMatrix.a = 2; +trace(myMatrix.a); // 2 +b + The value that affects the positioning of pixels + along the y axis when rotating or skewing an image.NumberThe value that affects the positioning of pixels + along the y axis when rotating or skewing an image. + + + The value that affects the positioning of pixels + along the y axis when rotating or skewing an image. + + The following example creates the Matrix object myMatrix and sets its + b value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.b); // 0 + +var degrees:Number = 30; +var radians:Number = (degrees/180) ~~ Math.PI; +myMatrix.b = Math.tan(radians); +trace(myMatrix.b); // 0.5773502691896257 +c + The value that affects the positioning of pixels + along the x axis when rotating or skewing an image.NumberThe value that affects the positioning of pixels + along the x axis when rotating or skewing an image. + + + The value that affects the positioning of pixels + along the x axis when rotating or skewing an image. + + The following example creates the Matrix object myMatrix and sets its + c value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.c); // 0 + +var degrees:Number = 30; +var radians:Number = (degrees/180) ~~ Math.PI; +myMatrix.c = Math.tan(radians); +trace(myMatrix.c); // 0.5773502691896257 +d + The value that affects the positioning of pixels + along the y axis when scaling or rotating an image.NumberThe value that affects the positioning of pixels + along the y axis when scaling or rotating an image. + + + The value that affects the positioning of pixels + along the y axis when scaling or rotating an image. + + The following example creates the Matrix object myMatrix and sets its + d value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.d); // 1 + +myMatrix.d = 2; +trace(myMatrix.d); // 2 +tx + The distance by which to translate each point along the x axis.NumberThe distance by which to translate each point along the x axis. + + + The distance by which to translate each point along the x axis. + + The following example creates the Matrix object myMatrix and sets its + tx value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.tx); // 0 + +myMatrix.tx = 50; // 50 +trace(myMatrix.tx); +ty + The distance by which to translate each point along the y axis.NumberThe distance by which to translate each point along the y axis. + + + The distance by which to translate each point along the y axis. + + The following example creates the Matrix object myMatrix and sets its + ty value. + +import flash.geom.Matrix; + +var myMatrix:Matrix = new Matrix(); +trace(myMatrix.ty); // 0 + +myMatrix.ty = 50; +trace(myMatrix.ty); // 50 +
Rectangle + A Rectangle object is an area defined by its position, as + indicated by its top-left corner point (x, y) and by its width + and its height.A Rectangle object is an area defined by its position, as + indicated by its top-left corner point (x, y), and by its width + and its height. + + Object + A Rectangle object is an area defined by its position, as + indicated by its top-left corner point (x, y) and by its width + and its height. + +

The x, y, width, and + height properties of the Rectangle class are + independent of each other; changing the value of one property has + no effect on the others. However, the right and bottom + properties are integrally related to those four properties. For example, if you change + the value of the right property, the value of the width property + changes; if you change the bottom property, the value of the height + property changes.

+ +

The following methods and properties use Rectangle objects:

+ +
  • The applyFilter(), colorTransform(), + copyChannel(), copyPixels(), draw(), fillRect(), + generateFilterRect(), getColorBoundsRect(), getPixels(), + merge(), paletteMap(), pixelDisolve(), setPixels(), and + threshold() methods, and the rect property of the BitmapData class
  • The getBounds() and getRect() methods, and the scrollRect + and scale9Grid properties of the DisplayObject class
  • The getCharBoundaries() method of the TextField class
  • The pixelBounds property of the Transform class
  • The bounds parameter for the startDrag() method of the Sprite class
  • The printArea parameter of the addPage() method of the PrintJob class
+ +

You can use the new Rectangle() constructor to create a + Rectangle object.

+ +

Note: The Rectangle class does not define a rectangular Shape display object. To draw + a rectangular Shape object onscreen, use the drawRect() method of the Graphics + class.

+ +
The following example uses the RectangleExample class to create three new Rectangle + objects at various x,y coordinates and with various heights and widths and then uses the + trace() method to confirm that the Rectangle instances were successfully created. Then a Boolean + variable isContained is assigned to the result of the call to + the containsRect() method, + which determines that the second rectangle does not fully enclose the third rectangle. + +package { + import flash.display.Sprite; + import flash.geom.Rectangle; + + public class RectangleExample extends Sprite { + + public function RectangleExample() { + var firstRect:Rectangle = new Rectangle(); + trace(firstRect); // (x=0, y=0, w=0, h=0) + var secondRect:Rectangle = new Rectangle(1, 3, 11, 13); + trace(secondRect); // (x=1, y=3, w=11, h=13) + var thirdRect:Rectangle = new Rectangle(5, 8, 17, 19); + trace(thirdRect); // (x=5, y=8, w=17, h=19) + var isContained:Boolean = secondRect.containsRect(thirdRect); + trace(isContained); // false + } + } +} +
flash.display.DisplayObject.scrollRectflash.display.BitmapDataflash.display.DisplayObjectflash.display.NativeWindowflash.text.TextField.getCharBoundaries()flash.geom.Transform.pixelBoundsflash.display.Sprite.startDrag()flash.printing.PrintJob.addPage()Rectangle + Creates a new Rectangle object with the top-left corner specified by the x + and y parameters and with the specified width and height + parameters.xNumber0The x coordinate of the top-left corner of the rectangle. + yNumber0The y coordinate of the top-left corner of the rectangle. + widthNumber0The width of the rectangle, in pixels. + heightNumber0The height of the rectangle, in pixels. + + Creates a new Rectangle object with the top-left corner specified by the + x and y parameters and with the specified width and height. + + + Creates a new Rectangle object with the top-left corner specified by the x + and y parameters and with the specified width and height + parameters. If you call this function without parameters, + a rectangle with x, y, width, and height + properties set to 0 is created. + + + xywidthheightclone + Returns a new Rectangle object with the same values for the x, y, + width, and height properties as the original Rectangle object.A new Rectangle object with the same values for the x, y, + width, and height properties as the original Rectangle object. + + flash.geom:RectangleReturns a copy of this Rectangle object. + + + Returns a new Rectangle object with the same values for the x, y, + width, and height properties as the original Rectangle object. + + xywidthheightcontainsPoint + Determines whether the specified point is contained within the rectangular region defined + by this Rectangle object.A value of true if the Rectangle object contains the specified point; + otherwise false. + + Booleanpointflash.geom:PointThe point, as represented by its x and y coordinates. + Determines if the specified point is contained within the rectangular region defined + by this Rectangle object using a Point object as a parameter. + + + Determines whether the specified point is contained within the rectangular region defined + by this Rectangle object. This method is similar to the Rectangle.contains() method, + except that it takes a Point object as a parameter. + + contains()flash.geom.PointcontainsRect + Determines whether the Rectangle object specified by the rect parameter is contained + within this Rectangle object.A value of true if the Rectangle object that you specify is + contained by this Rectangle object; otherwise false. + + Booleanrectflash.geom:RectangleThe Rectangle object being checked. + + Determines if the Rectangle object specified by the rect parameter is contained + within this Rectangle object. + + + Determines whether the Rectangle object specified by the rect parameter is contained + within this Rectangle object. A Rectangle object is said to contain another if the second + Rectangle object falls entirely within the boundaries of the first. + + contains + Determines whether the specified point is contained within the rectangular region defined + by this Rectangle object.A value of true if the Rectangle object contains the specified point; + otherwise false. + + BooleanxNumberThe x coordinate (horizontal position) of the point. + yNumberThe y coordinate (vertical position) of the point. + Determines if the specified point is contained within the rectangular region. + + + Determines whether the specified point is contained within the rectangular region defined + by this Rectangle object. + + flash.geom.Pointequals + Determines whether the object specified in the toCompare parameter is + equal to this Rectangle object.A value of true if the object has exactly the same values for the + x, y, width, and height properties + as this Rectangle object; otherwise false. + + BooleantoCompareflash.geom:RectangleThe rectangle to compare to this Rectangle object. + + Determines if the object specified in the toCompare parameter is equal to this + Rectangle object. + + + Determines whether the object specified in the toCompare parameter is + equal to this Rectangle object. This method compares the x, y, + width, and height properties of an object against the same properties + of this Rectangle object. + + xywidthheightinflatePoint + Increases the size of the Rectangle object.pointflash.geom:PointThe x property of this Point object is used to increase the + horizontal dimension of the Rectangle object. The y property + is used to increase the vertical dimension of the Rectangle object. + + Increases the size of the Rectangle object using a Point object as a parameter. + + + Increases the size of the Rectangle object. + This method is similar to the Rectangle.inflate() method + except it takes a Point object as a parameter. + +

The following two code examples give the same result:

+ + + var rect1:Rectangle = new Rectangle(0,0,2,5); + rect1.inflate(2,2) + + + + var rect1:Rectangle = new Rectangle(0,0,2,5); + var pt1:Point = new Point(2,2); + rect1.inflatePoint(pt1) + + + + + + +
flash.geom.Point
inflate + Increases the size of the Rectangle object by the specified amounts, in pixels.dxNumberThe value to be added to the left and the right of the Rectangle object. The following + equation is used to calculate the new width and position of the rectangle: + + + x -= dx; + width += 2 ~~ dx; + + + dyNumberThe value to be added to the top and the bottom of the Rectangle. The + following equation is used to calculate the new height and position of the rectangle: + + + y -= dy; + height += 2 ~~ dy; + + + + Increases the size of the Rectangle object by the specified amounts, in pixels. The center point of the + Rectangle object stays the same, and its size increases to the left and right by the + dx value, and to the top and the bottom by the dy value. + + xyintersection + If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle + object, returns the area of intersection as a Rectangle object.A Rectangle object that equals the area of intersection. If the rectangles do not + intersect, this method returns an empty Rectangle object; that is, a rectangle with its x, + y, width, and height properties set to 0. + + flash.geom:RectangletoIntersectflash.geom:RectangleThe Rectangle object to compare against to see if it intersects with + this Rectangle object. + + Returns the area of intersection. + + + If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle + object, returns the area of intersection as a Rectangle object. + If the rectangles do not intersect, this method returns an empty Rectangle object with its properties + set to 0. + +

+ +
intersects + Determines whether the object specified in the toIntersect parameter intersects + with this Rectangle object.A value of true if the specified object intersects with this Rectangle object; + otherwise false. + + BooleantoIntersectflash.geom:RectangleThe Rectangle object to compare against this Rectangle object. + + Determines if the object specified in the toIntersect parameter intersects + with this Rectangle object. + + + Determines whether the object specified in the toIntersect parameter intersects + with this Rectangle object. This method checks the x, y, + width, and height properties of the specified Rectangle object to see + if it intersects with this Rectangle object. + + xywidthheightisEmpty + Determines whether or not this Rectangle object is empty.A value of true if the Rectangle object's width or height is less than + or equal to 0; otherwise false. + + Boolean + Determines whether or not this Rectangle object is empty. + + offsetPoint + Adjusts the location of the Rectangle object using a Point object as a parameter.pointflash.geom:PointA Point object to use to offset this Rectangle object. + + Adjusts the location of the Rectangle object using a Point object as a parameter. + + + Adjusts the location of the Rectangle object using a Point object as a parameter. + This method is similar to the Rectangle.offset() method, except that it takes a Point + object as a parameter. + + flash.geom.Pointoffset + Adjusts the location of the Rectangle object, as determined by its top-left corner, + by the specified amounts.dxNumberMoves the x value of the Rectangle object by this amount. + dyNumberMoves the y value of the Rectangle object by this amount. + + Adjusts the location of the Rectangle object. + + + Adjusts the location of the Rectangle object, as determined by its top-left corner, + by the specified amounts. + + setEmpty + Sets all of the Rectangle object's properties to 0.Sets all properties to 0. + + + Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or + height is less than or equal to 0. + +

This method sets the values of the x, y, + width, and height properties to 0.

+ +
xywidthheight
toString + Builds and returns a string that lists the horizontal and vertical positions + and the width and height of the Rectangle object.A string listing the value of each of the following properties of the Rectangle object: + x, y, width, and height. + + String + Builds and returns a string that lists the horizontal and vertical positions + and the width and height of the Rectangle object. + + xywidthheightunion + Adds two rectangles together to create a new Rectangle object, by + filling in the horizontal and vertical space between the two rectangles.A new Rectangle object that is the union of the two rectangles. + + flash.geom:RectangletoUnionflash.geom:RectangleA Rectangle object to add to this Rectangle object. + + Adds two rectangles together to create a new Rectangle object. + + + Adds two rectangles together to create a new Rectangle object, by + filling in the horizontal and vertical space between the two rectangles. + +

+

Note: The union() method ignores rectangles with 0 + as the height or width value, such as: var rect2:Rectangle = new Rectangle(300,300,50,0);

+ +
height + The height of the rectangle, in pixels.NumberThe height of the rectangle in pixels. + + + The height of the rectangle, in pixels. Changing the height value of a Rectangle + object has no effect on the x, y, and + width properties. + +

+ +
xyheight
width + The width of the rectangle, in pixels.NumberThe width of the rectangle. + + + The width of the rectangle, in pixels. Changing the width value of a Rectangle object + has no effect on the x, y, and height + properties. + +

+ +
xyheight
x + The x coordinate of the top-left corner of the rectangle.NumberThe x coordinate of the top-left corner of the rectangle. + + + The x coordinate of the top-left corner of the rectangle. Changing + the value of the x property of a Rectangle object has no effect on the + y, + width, and height properties. + +

The value of the x property is equal to the value of the + left property.

+ + +
left
y + The y coordinate of the top-left corner of the rectangle.NumberThe y coordinate of the top-left corner. + + + The y coordinate of the top-left corner of the rectangle. Changing + the value of the y property of a Rectangle object has no effect on the + x, width, and height properties. + +

The value of the y property is equal to the value of + the top property.

+ +
xwidthheighttop
bottomRight + The location of the Rectangle object's bottom-right corner, determined by the values of the right and + bottom properties.flash.geom:PointThe location of the Rectangle object's bottom-right corner determined by the right + and bottom properties. + + + The location of the Rectangle object's bottom-right corner, determined by the values of the right and + bottom properties. + +

+ +
flash.geom.Point
bottom + The sum of the y and + height properties.NumberThe sum of the y and height properties. + + + The sum of the y and + height properties. + +

+ +
yheight
left + The x coordinate of the top-left corner of the rectangle.NumberThe x coordinate of the top-left corner of the rectangle. + + + The x coordinate of the top-left corner of the rectangle. Changing + the left property of a Rectangle object has no effect on the y + and height properties. However it does affect the width + property, whereas changing the x value does not affect the + width property. + +

The value of the left property is equal to the value of the + x property.

+ + +

+ +
xywidthheight
right + The sum of the x and + width properties.NumberThe sum of the x and width properties. + + + The sum of the x and + width properties. + +

+ +
xwidth
size + The size of the Rectangle object, expressed as a Point object with the values + of the width and height properties.flash.geom:PointThe size of the Rectangle object, expressed as a Point object with values + width, height. + + + The size of the Rectangle object, expressed as a Point object with the values + of the width and height properties. + + flash.geom.PointtopLeft + The location of the Rectangle object's top-left corner, determined by the x and + y coordinates of the point.flash.geom:PointThe location of the Rectangle object's top-left corner determined by the x and + y values of the point. + + + The location of the Rectangle object's top-left corner, determined by the x and + y coordinates of the point. + +

+ +
flash.geom.Pointxy
top + The y coordinate of the top-left corner of the rectangle.NumberThe y coordinate of the top-left corner of the rectangle. + + + The y coordinate of the top-left corner of the rectangle. Changing + the top property of a Rectangle object has no effect on the x + and width properties. However it does affect the height + property, whereas changing the y value does not affect the + height property. + +

The value of the top property is equal to the value of the y property.

+ +

+ +
xywidthheight
ColorTransform + The ColorTransform class lets you adjust the color values in a display object.Object + The ColorTransform class lets you adjust the color values in a display object. + The color adjustment or color transformation can be applied to all four channels: + red, green, blue, and alpha transparency. + +

When a ColorTransform object is applied to a display object, a new value for each color + channel is calculated like this:

+ +
  • New red value = (old red value * redMultiplier) + redOffset
  • New green value = (old green value * greenMultiplier) + + greenOffset
  • New blue value = (old blue value * blueMultiplier) + blueOffset
  • New alpha value = (old alpha value * alphaMultiplier) + + alphaOffset
+ +

If any of the color channel values is greater than 255 after the calculation, it is set to 255. + If it is less than 0, it is set to 0.

+ +

You can use ColorTransform objects in the following ways:

+ +
  • In the colorTransform parameter of the colorTransform() method + of the BitmapData class
  • As the colorTransform property of a Transform object (which can be + used as the transform property of a display object)
+ +

You must use the new ColorTransform() constructor to create a + ColorTransform object before you can call the methods of the + ColorTransform object.

+ +

Color transformations do not apply to the background color of a movie clip (such as a loaded SWF + object). They apply only to graphics and symbols that are attached to the movie clip.

+ +
The following example uses the TransformExample class to create a simple sprite + in the shape of a square filled with a gradient pattern. Each time the user clicks the square, the + application transforms the colors of the square sprite, adding to the red color channel and + lightening the blue color channel. This is accomplished with the following steps: + +
  1. The constructor creates a new sprite object target.
  2. The CustomButton() constructor calls the draw() method, which draws a gradient + square in the sprite.
  3. The CustomButton() constructor adds a click event listener for the sprite, which is handled by the + clickHandler() method.
  4. In the clickHandler() method, two properties are set to the + redOffset and blueOffset properties of the current + color transformation. Each is adjusted by 25. Then the transform.colorTransform + property of the square sprite is modified to use the new offset values. + Each time the user clicks the square, the call to the clickHandler() method modifies + the color of the square, by augmenting its red color value and diminishing its blue color value.
+ +package { + import flash.display.Sprite; + import flash.display.GradientType; + import flash.geom.ColorTransform; + import flash.events.MouseEvent; + + public class ColorTransformExample extends Sprite { + public function ColorTransformExample() { + var target:Sprite = new Sprite(); + draw(target); + addChild(target); + target.useHandCursor = true; + target.buttonMode = true; + target.addEventListener(MouseEvent.CLICK, clickHandler) + } + public function draw(sprite:Sprite):void { + var red:uint = 0xFF0000; + var green:uint = 0x00FF00; + var blue:uint = 0x0000FF; + var size:Number = 100; + sprite.graphics.beginGradientFill(GradientType.LINEAR, [red, blue, green], [1, 0.5, 1], [0, 200, 255]); + sprite.graphics.drawRect(0, 0, 100, 100); + } + public function clickHandler(event:MouseEvent):void { + var rOffset:Number = transform.colorTransform.redOffset + 25; + var bOffset:Number = transform.colorTransform.redOffset - 25; + this.transform.colorTransform = new ColorTransform(1, 1, 1, 1, rOffset, 0, bOffset, 0); + } + } +} +
flash.geom.Transformflash.display.DisplayObject.transformflash.display.BitmapData.colorTransform()ColorTransform + Creates a ColorTransform object for a display object with the specified + color channel values and alpha values.redMultiplierNumber1.0The value for the red multiplier, in the range from 0 to 1. + greenMultiplierNumber1.0The value for the green multiplier, in the range from 0 to 1. + blueMultiplierNumber1.0The value for the blue multiplier, in the range from 0 to 1. + alphaMultiplierNumber1.0The value for the alpha transparency multiplier, in the range from 0 to 1. + redOffsetNumber0The offset value for the red color channel, in the range from -255 to 255. + greenOffsetNumber0The offset value for the green color channel, in the range from -255 to 255. + blueOffsetNumber0The offset for the blue color channel value, in the range from -255 to 255. + alphaOffsetNumber0The offset for alpha transparency channel value, in the range from -255 to 255. + + Creates a ColorTransform object for a display object. + + + Creates a ColorTransform object for a display object with the specified + color channel values and alpha values. + + concat + Concatenates the ColorTranform object specified by the second parameter + with the current ColorTransform object and sets the + current object as the result, which is an additive combination of the two color transformations.secondflash.geom:ColorTransformThe ColorTransform object to be combined with the current ColorTransform object. + + + Concatenates the ColorTranform object specified by the second parameter + with the current ColorTransform object and sets the + current object as the result, which is an additive combination of the two color transformations. + When you apply the concatenated ColorTransform object, the effect is the same as applying the + second color transformation after the original color transformation. + + toString + Formats and returns a string that describes all of the properties of the + ColorTransform object.A string that lists all of the properties of the ColorTransform object. + + String + Formats and returns a string that describes all of the properties of the + ColorTransform object. + + alphaMultiplier + A decimal value that is multiplied with the alpha transparency channel value.Number + A decimal value that is multiplied with the alpha transparency channel value. + +

If you set the alpha transparency value of a display object directly by using the + alpha property of the DisplayObject instance, it affects the value of the + alphaMultiplier property of that display object's transform.colorTransform + property.

+ +
flash.display.DisplayObject.alpha
alphaOffset + A number from -255 to 255 that is added to the alpha transparency channel value after it has + been multiplied by the alphaMultiplier value.NumberA number from -255 to 255 that is added to the alpha transparency channel value after it has been + multiplied by the alphaMultiplier value. + + + A number from -255 to 255 that is added to the alpha transparency channel value after it has + been multiplied by the alphaMultiplier value. + + blueMultiplier + A decimal value that is multiplied with the blue channel value.Number + A decimal value that is multiplied with the blue channel value. + + blueOffset + A number from -255 to 255 that is added to the blue channel value after it has + been multiplied by the blueMultiplier value.NumberA number from -255 to 255 that is added to the blue channel value after it has + been multiplied by the blueMultiplier value. + + + A number from -255 to 255 that is added to the blue channel value after it has + been multiplied by the blueMultiplier value. + + greenMultiplier + A decimal value that is multiplied with the green channel value.Number + A decimal value that is multiplied with the green channel value. + + greenOffset + A number from -255 to 255 that is added to the green channel value after it has + been multiplied by the greenMultiplier value.NumberA number from -255 to 255 that is added to the green channel value after it has + been multiplied by the greenMultiplier value. + + + A number from -255 to 255 that is added to the green channel value after it has + been multiplied by the greenMultiplier value. + + redMultiplier + A decimal value that is multiplied with the red channel value.Number + A decimal value that is multiplied with the red channel value. + + redOffset + A number from -255 to 255 that is added to the red channel value after it has been + multiplied by the redMultiplier value.NumberA number from -255 to 255 that is added to the red channel value after it + has been multiplied by the redMultiplier value. + + + A number from -255 to 255 that is added to the red channel value after it has been + multiplied by the redMultiplier value. + + color + The RGB color value for a ColorTransform object.uint + The RGB color value for a ColorTransform object. + +

When you set this property, it changes the three color offset values (redOffset, + greenOffset, and blueOffset) + accordingly, and it sets the three color multiplier values (redMultiplier, + greenMultiplier, and blueMultiplier) to 0. + The alpha transparency multiplier and offset values do not change.

+ +

When you pass a value for this property, use the format 0xRRGGBB. + RR, GG, and BB each consist + of two hexadecimal digits that specify the offset of each color component. The 0x + tells the ActionScript compiler that the number is a hexadecimal value.

+ +
Point + The Point object represents a location in a two-dimensional coordinate system, where x + represents the horizontal axis and y represents the vertical axis.The Point class represents a location in a two-dimensional coordinate system. + + Object + The Point object represents a location in a two-dimensional coordinate system, where x + represents the horizontal axis and y represents the vertical axis. + +

The following code creates a point at (0,0):

+ + var myPoint:Point = new Point(); + + + +

Methods and properties of the following classes use Point objects:

+ +
  • BitmapData
  • DisplayObject
  • DisplayObjectContainer
  • DisplacementMapFilter
  • NativeWindow
  • Matrix
  • Rectangle
+ +

You can use the new Point() constructor to create a + Point object.

+ +
The following example uses the PointExample class to create a number of new Point + objects at various x,y coordinates and then uses the trace() method to output the + results of various class methods. + +package { + import flash.display.Sprite; + import flash.geom.Point; + + public class PointExample extends Sprite { + + public function PointExample() { + var point1:Point = new Point(); + trace(point1); // (x=0, y=0) + + var point2:Point = new Point(6, 8); + trace(point2); // (x=6, y=8) + + trace(Point.interpolate(point1, point2, 0.5)); // (x=3, y=4) + + trace(Point.distance(point1, point2)); // 10 + + trace(point1.add(point2)); // (x=6, y=8) + + var point3:Point = point2.clone(); + trace(point2.equals(point3)); // true + + point3.normalize(2.5); + trace(point3); // (x=1.5, y=2) + + trace(point2.subtract(point3)); // (x=4.5, y=6) + + trace(point1.offset(2, 3)); // + + var angle:Number = Math.PI * 2 * (30 / 360); // 30 degrees + trace(Point.polar(4, angle)) // (x=3.464101615137755, y=1.9999999999999998) + } + } +} +
flash.display.BitmapDataflash.display.DisplayObjectflash.display.DisplayObjectContainerflash.filters.DisplacementMapFilterflash.geom.Matrixflash.display.NativeWindowflash.geom.RectanglePoint + Creates a new point.xNumber0The horizontal coordinate. + yNumber0The vertical coordinate. + + + Creates a new point. If you pass no parameters to this method, a point is created at (0,0). + add + Adds the coordinates of another point to the coordinates of this point to create a new point.The new point. + + flash.geom:Pointvflash.geom:PointThe point to be added. + + + Adds the coordinates of another point to the coordinates of this point to create a new point. + + clone + Creates a copy of this Point object.The new Point object. + + flash.geom:PointCreates a copy of the Point object. + + + Creates a copy of this Point object. + distance + Returns the distance between pt1 and pt2.The distance between the first and second points. + Numberpt1flash.geom:PointThe first point. + pt2flash.geom:PointThe second point. + + Returns the distance between pt1 and pt2. + equals + Determines whether two points are equal.A value of true if the object is equal to this Point object; false if it is not equal. + BooleantoCompareflash.geom:PointThe point to be compared. + + Determines whether two points are equal. Two points are equal if they have the same x and + y values. + interpolate + Determines a point between two specified points.The new, interpolated point. + + flash.geom:Pointpt1flash.geom:PointThe first point. + pt2flash.geom:PointThe second point. + fNumberThe level of interpolation between the two points. Indicates where the new point will be, along the line + between pt1 and pt2. If f=1, pt1 is returned; if + f=0, pt2 is returned. + + + Determines a point between two specified points. The parameter f + determines where the new interpolated point is located relative to the two end points + specified by parameters pt1 and pt2. The closer the value of the parameter + f is to 1.0, the closer the interpolated point is to the + first point (parameter pt1). The closer the value of the parameter f is + to 0, the closer the interpolated point is to the second point (parameter pt2). + + normalize + Scales the line segment between (0,0) and the current point to a set length.The normalized point. + + thicknessNumberThe scaling value. For example, if the current point is (0,5), + and you normalize it to 1, the point returned is at (0,1). + + + Scales the line segment between (0,0) and the current point to a set length. + + lengthoffset + Offsets the Point object by the specified amount.dxNumberThe amount by which to offset the horizontal coordinate, x. + dyNumberThe amount by which to offset the vertical coordinate, y. + + Offsets the Point object by the specified amount. The value of dx is added + to the original value of x to create the new x value. The value + of dy is added to the original value of y to create the new y value. + polar + Converts a pair of polar coordinates to a Cartesian point coordinate.The Cartesian point. + + flash.geom:PointlenNumberThe length coordinate of the polar pair. + angleNumberThe angle, in radians, of the polar pair. + + + Converts a pair of polar coordinates to a Cartesian point coordinate. + + lengthMath.round()subtract + Subtracts the coordinates of another point from the coordinates of this point to create a new + point.The new point. + + flash.geom:Pointvflash.geom:PointThe point to be subtracted. + + + Subtracts the coordinates of another point from the coordinates of this point to create a new + point. + + toString + Returns a string that contains the values of the x and y coordinates.The string representation of the coordinates. + StringReturns a string that contains the values of the x and y coordinates. + + + Returns a string that contains the values of the x and y coordinates. + + The string has the form "(x=x, y=y)", so calling the toString() + method for a point at 23,17 would return "(x=23, y=17)". + + x + The horizontal coordinate of the point.Number + The horizontal coordinate of the point. The default value is 0. + + y + The vertical coordinate of the point.Number + The vertical coordinate of the point. The default value is 0. + + length + The length of the line segment from (0,0) to this point.Number + The length of the line segment from (0,0) to this point. + + Point.polar()
Orientation3D +The Orientation3D class is an enumeration of constant values for representing the orientation style +of a Matrix3D object.Object +The Orientation3D class is an enumeration of constant values for representing the orientation style +of a Matrix3D object. The three types of orientation are Euler angles, axis angle, and quaternion. +The decompose and recompose methods of the Matrix3D object take one of these +enumerated types to identify the rotational components of the Matrix. + +flash.geom.Matrix3Dflash.geom.Transformflash.geom.PerspectiveProjectionAXIS_ANGLE + The axis angle orientation uses a combination of an axis and an angle to determine the orientation.axisAngleString + The axis angle orientation uses a combination of an axis and an angle to determine the orientation. + A line or vector from the center of a three-dimensional globe to the surface is an example of an axis. + The axis around which the object is rotated is a unit vector that represents any possible direction + in the three-dimensional space. The angle represents the magnitude of the rotation + about the vector. The direction determines where a display object is facing and the roll angle determines + which way is up. You can use Vector3D and the Matrix3D objects to determine + the various matrix transformations as well as to determine important three-dimensional programming + values such as the distance to the intersection of two objects that can be used to detect simple + collision between three-dimensional objects. + +

The Matrix3D.appendRotation() and Matrix3D.prependRotation() methods + use the axis angle orientation.

+ +
flash.geom.Matrix3D.decompose()flash.geom.Matrix3D.recompose()
EULER_ANGLES + Euler angles, the default orientation for decompose() and recompose() methods, + defines the orientation with three separate angles of rotation for each axis.eulerAnglesStringDefines the orientation with three separate angles of rotation for each axis. + + + Euler angles, the default orientation for decompose() and recompose() methods, + defines the orientation with three separate angles of rotation for each axis. Usually, + a rotation around the x axis is followed by a rotation around the y axis, which is followed by a + rotation around the z axis. + +

Euler angles can sometimes lead to animation errors because of problems such as singularities when + rotating around the x axis or gimbal lock. For example, since with Euler angles each axis is handled + independently, gimbal lock can occur during the rotation around two or more axes. The axes + can become aligned, leading to unexpected results.

+ +

The axis rotation properties of the display object perform Euler angles rotation.

+ +
flash.geom.Matrix3D.decompose()flash.geom.Matrix3D.recompose()
QUATERNION + The quaternion orientation uses complex numbers.quaternionStringAn orientation in quaternion uses the three axes (x,y,z) and an angle of rotation (w). + + + The quaternion orientation uses complex numbers. An orientation in quaternion is by the three axes of + rotation (x,y,z) and an angle of rotation (w). Quaternion guarantees the shortest, most efficient + path for the rotation. It also produces a smooth, gimbal-lock-free rotation. A gimbal lock can occur + when during the rotation around two or more axes the axes are aligned, leading to unexpected results. + +

The Matrix3D.interpolate() method uses quaternion.

+ +
flash.geom.Matrix3D.decompose()flash.geom.Matrix3D.recompose()
PerspectiveProjection + The PerspectiveProjection class provides an easy way to assign or modify the perspective + transformations of a display object and all of its children.Object + The PerspectiveProjection class provides an easy way to assign or modify the perspective + transformations of a display object and all of its children. For more complex or + custom perspective transformations, use the Matrix3D class. While the PerspectiveProjection + class provides basic three-dimensional presentation properties, the Matrix3D class + provides more detailed control over the three-dimensional presentation of display objects. + +

Projection is a way of representing a three-dimensional object in a + two-dimensional space, like a cube projected onto a computer screen. Perspective projection uses a viewing + frustum (a rectangular pyramid) to model and project a three-dimensional world and its objects + on the screen. The viewing frustum becomes increasingly wider as it moves further from the origin + of the viewpoint. The origin of the viewpoint could be a camera or the eyes of an observer facing the screen. + The projected perspective produces the illusion of three dimensions with depth and distance, + where the objects closer to the screen appear larger than the objects farther from the screen.

+ +

+ +

A default PerspectiveProjection object is a framework defined for perspective transformation + of the root object, based on the field of view and aspect ratio (dimensions) of the stage. + The projection center, the vanishing point, is set to the center of the stage, which means the + three-dimensional display objects disappear toward the center of the stage as they move + back in the z axis. The default viewpoint is at point (0,0) looking down the positive + z axis. The y-axis points down toward the bottom of the screen. You can + gain access to the root display object's perspective projection settings + and change the field of view and projection center properties of the perspectiveProjection + property through the root object's DisplayObject.transform property.

+ +

You can also set a different perspective projection setting for a display object through + the parent's perspective projection. First, create a PerspectiveProjection object and set + its fieldOfView and projectionCenter properties. Next, assign the + PerspectiveProjection object to the parent display object using + the DisplayObject.transform property. The specified projection matrix and transformation + will then apply to all the display object's three-dimensional children.

+ + +
flash.display.DisplayObject.transformflash.geom.Transformflash.geom.Matrix3Dflash.geom.Utils3DPerspectiveProjection + Creates an instance of a PerspectiveProjection object. + Creates an instance of a PerspectiveProjection object. + + toMatrix3D + Returns the underlying Matrix3D object of the display object.The underlying Matrix3D object. + + flash.geom:Matrix3D + Returns the underlying Matrix3D object of the display object. + +

A display object, like the root object, can have a PerspectiveProjection object without + needing a Matrix3D property defined for its transformations. In fact, use either + a PerspectiveProjection or a Matrix3D object to specify the perspective transformation. + If when using the PerspectiveProjection object, a Matrix3D object was needed, the toMatrix3D() + method can retrieve the underlying Matrix3D object of the display object. For example, the + toMatrix3D() method can be used with the Utils3D.projectVectors() + method.

+ +
flash.geom.Matrix3D
fieldOfView + Specifies an angle, as a degree between 0 and 180, for the field of view in three + dimensions.NumberSpecifies an angle, as a degree between 0 and 180, for the field of view in three dimensions. + + + Specifies an angle, as a degree between 0 and 180, for the field of view in three + dimensions. This value determines how strong the perspective transformation and distortion apply to + a three-dimensional display object with a non-zero z-coordinate. + +

A degree close to 0 means that the screen's two-dimensional x- and y-coordinates are + roughly the same as the three-dimensional x-, y-, and z-coordinates with little or + no distortion. In other words, for a small angle, a display object moving down the z axis appears + to stay near the same size and moves little.

+ +

A value close to 180 degrees results in a fisheye lens effect: positions + with a z value smaller than 0 are magnified, while positions with a + z value larger than 0 are minimized. With a large angle, a display object + moving down the z axis appears to change size quickly and moves a great distance. If the field of view + is set to 0 or 180, nothing is seen on the screen.

+ +
focalLength + The distance between the eye or the viewpoint's origin (0,0,0) and the display object located + in the z axis.Number + The distance between the eye or the viewpoint's origin (0,0,0) and the display object located + in the z axis. During the perspective transformation, the focalLength is calculated dynamically + using the angle of the field of view and the stage's aspect ratio (stage width divided by + stage height). + + fieldOfViewprojectionCenter + A two-dimensional point representing the center of the projection, the vanishing point for the display object.flash.geom:Point + A two-dimensional point representing the center of the projection, the vanishing point for the display object. + +

The projectionCenter property is an offset to the default registration point that is the + upper left of the stage, point (0,0). The default projection transformation center is in the middle of + the stage, which means the three-dimensional display objects disappear toward the center of the stage + as they move backwards in the z axis.

+ +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.globalization.xml b/language-server/playerglobal_docs/flash.globalization.xml new file mode 100644 index 0000000..265a0c4 --- /dev/null +++ b/language-server/playerglobal_docs/flash.globalization.xml @@ -0,0 +1,3166 @@ +flash.globalizationDateTimeFormatter + + The DateTimeFormatter class provides locale-sensitive formatting for Date objects and access to localized + date field names.Object + The DateTimeFormatter class provides locale-sensitive formatting for Date objects and access to localized + date field names. The methods of this class use functions and settings provided by the operating system. + +

There are two ways to select a date time format: using a predefined pattern + or a custom pattern. For most applications the predefined styles specified by the + DateTimeStyle constants (LONG, MEDIUM, NONE, or SHORT + should be used. These constants + specify the default patterns for the requested locale or the default patterns based on the + user's operating system settings. +

+

+ For example the following code creates a date string using the default short date format: +

+ + var df:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE); + var currentDate:Date = new Date(); + var shortDate:String = df.format(currentDate); + + +

When an instance of this class is created, if the requested locale is supported by the + operating system then the properties of the instance are set according to the conventions and + defaults of the requested locale and the constructor's dateStyle and timeStyle parameters. + If the requested locale is not available, then the properties are set according to a fallback or + default system locale, which can be retrieved using the actualLocaleIDName property. +

+

+ This class contains additional methods to get localized strings for month names and + weekday names, and to retrieve the first day of the week that can be used in a calendar picker + or other similar application. +

+

+ Due to the use of the user's settings, the use of formatting patterns + provided by the operating system, and the use of a fallback locale when a requested locale is not supported, + different users can see different formatting results even when using the same locale ID. +

+ +
The following examples shows how strings that represent date and time values can be formatted + differently based on the locale. + + The output from this example will differ based on the operating system and user preferences. +

+ This example uses the following locales: English (US), French (France), Spanish (Spain). +

+

+ The example does the following for each locale in the list: +

+
  1. Creates a DateTimeFormatter object using the default style (long dateStyle, long timeStyle)
  2. Formats the current date and time using the default long date style.
  3. Change to a time-only short date style using the DateTimeStyle.NONE and DateTimeStyle.SHORT + constants.
  4. Formats the current date and time using the time-only short date style.
+ + +package { + import flash.display.Sprite; + import flash.globalization.DateTimeFormatter; + import flash.globalization.DateTimeStyle; + + public class DateTimeFormatterExample extends Sprite + { + private var localeList:Array = new Array("en-US", "fr-FR", "es-ES"); + + public function DateTimeFormatterExample() + { + var date:Date = new Date(); + + for each (var locale:String in localeList) { + var dtf:DateTimeFormatter = new DateTimeFormatter(locale); + trace('\n' + "LocaleID requested=" + dtf.requestedLocaleIDName + + "; actual=" + dtf.actualLocaleIDName); + + var longDate:String = dtf.format(date); + trace(longDate + " (" + dtf.getDateTimePattern() + ")"); + + dtf.setDateTimeStyles(DateTimeStyle.NONE, DateTimeStyle.SHORT); + var shortDate:String = dtf.format(date); + trace(shortDate + " (" + dtf.getDateTimePattern() + ")"); + } + } + } +} +
The following example shows how an application can format a date based on a pattern selected by the user. + + The output from this example will differ based on the operating system and user preferences. +

+ The example does the following for each locale in the list: +

+
  1. Creates three input and output text fields.
  2. Creates a DateTimeFormatter object using the American English locale.
  3. Calls the configureTextField() function which sets the position and size of the text fields + and adds an event listener to the patternField object.
  4. When the user enters pattern in the patternField text field, the textInputHandler function + formats the current date and time using the pattern, and displays the result and the lastOperationStatus + value the in output text fields.
+ + +package { + import flash.display.Sprite; + import flash.events.Event; + import flash.globalization.DateTimeFormatter; + import flash.text.*; + + public class DateTimePatternExample extends Sprite + { + private var patternField:TextField = new TextField(); + private var resultField:TextField = new TextField(); + private var statusField:TextField = new TextField(); + private var date:Date = new Date(); + private var dtf:DateTimeFormatter = new DateTimeFormatter("en-US"); + + private function configureTextField():void + { + patternField.type = TextFieldType.INPUT; + patternField.width = 300; + patternField.height = 20; + patternField.background = true; + patternField.border = true; + + resultField.y = 40; + resultField.width = 300; + resultField.height = 20; + + statusField.y = 80; + statusField.width = 300; + statusField.height = 20; + + addChild(patternField); + addChild(resultField); + addChild(statusField); + patternField.addEventListener(Event.CHANGE,textInputHandler); + } + + private function textInputHandler(event:Event):void + { + dtf.setDateTimePattern(patternField.text); + statusField.text = dtf.lastOperationStatus; + resultField.text = dtf.format(date); + } + + public function DateTimePatternExample() + { + configureTextField(); + } + } +} +
actualLocaleIDNameDateTimeStyleDateTimeFormatter + Constructs a new DateTimeFormatter object to format dates and times according to the conventions of the + specified locale and the provided date and time formatting styles.if the dateStyle or timeStyle parameter is not a valid DateTimeStyle constant. + ArgumentErrorArgumentErrorif the dateStyle or timeStyle parameter is null. + + TypeErrorTypeErrorrequestedLocaleIDNameStringThe preferred locale ID name to use when determining date or time formats. + dateStyleStringlongSpecifies the style to use when formatting dates. + The value corresponds to one of the values enumerated by the DateTimeStyle class: +
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
+
timeStyleStringlongSpecifies the style to use when formatting times. + The value corresponds to one of the values enumerated by the DateTimeStyle class: +
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
+ +
+ Constructs a new DateTimeFormatter object to format dates and times according to the conventions of the + specified locale and the provided date and time formatting styles. Date and time styles are used to set + date and time formatting patterns to predefined, locale dependent patterns from the operating system. + +

This constructor determines if the current operating system supports the requested locale ID name. + If it is not supported then a fallback locale is used instead. + The name of the fallback locale ID can be determined from the actualLocaleIDName property. +

+ If a fallback is used for any of the requestedLocaleIDName, dateStyle or + timeStyle parameters then the lastOperationStatus property is set + to indicate the type of fallback. +

+

To format based on the user's current operating system preferences, pass the value LocaleID.DEFAULT + in the requestedLocaleIDName parameter to the constructor. +

+ +

When the constructor is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

When the requested locale ID name is not available then the lastOperationStatus + is set to one of the following:

+
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+

Otherwise the lastOperationStatus property is set to one of the constants defined in + the LastOperationStatus class.

+ +

For details on the warnings listed above and other possible values of the + lastOperationStatus property see the descriptions in the LastOperationStatus class.

+ +
lastOperationStatusrequestedLocaleIDNameactualLocaleIDNameDateTimeStyleLastOperationStatusLocaleID
formatUTC + Formats a display string for a Date object that is interpreted as being in UTC time + (using the UTC components of the Date object such as: dateUTC, dayUTC, fullYearUTC, hoursUTC, minutesUTC, monthUTC, + and secondsUTC), according to the dateStyle, timeStyle or date time pattern.A formatted string representing the date or time value. + + StringdateTimeDateA Date value to be formatted. + + Formats a display string for a Date object that is interpreted as being in UTC time + (using the UTC components of the Date object such as: dateUTC, dayUTC, fullYearUTC, hoursUTC, minutesUTC, monthUTC, + and secondsUTC), according to the dateStyle, timeStyle or date time pattern. + The formatting is done using the conventions of the locale ID + and the date style and time style, or customized date pattern and time pattern, + specified for this DateTimeFormatter instance. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
setDateTimeStyles()setDateTimePattern()getDateStyle()getTimeStyle()lastOperationStatusLastOperationStatus
format + Formats a display string for a Date object that is interpreted as being in the user's local time + (using the local time components of the Date object such as: date, day, fullYear, hours, minutes, month, and seconds).A formatted string representing the date or time value. + + StringdateTimeDateA Date value to be formatted. + + Formats a display string for a Date object that is interpreted as being in the user's local time + (using the local time components of the Date object such as: date, day, fullYear, hours, minutes, month, and seconds). + The formatting is done using the conventions of the locale ID + and the date style and time style, or customized date pattern and time pattern, + specified for this DateTimeFormatter instance. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
setDateTimeStyles()setDateTimePattern()getDateStyle()getTimeStyle()lastOperationStatusLastOperationStatus
getAvailableLocaleIDNames + Lists all of the locale ID names supported by this class.A vector of strings containing all of the locale ID names supported by this class. + + + Lists all of the locale ID names supported by this class. + +

If this class is not supported on the current operating system, this method returns a null value.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatusLocaleID
getDateStyle + Gets the date style for this instance of the DateTimeFormatter.The date style string for this formatter. +

Possible values:

+
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
  • DateTimeStyle.CUSTOM
+ +
String
+ Gets the date style for this instance of the DateTimeFormatter. The date style is used to retrieve a + predefined date formatting pattern from the operating system. + + The date style value can be set by the DateTimeFormatter() constructor, the setDateTimeStyles() + method or the setDateTimePattern() method. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
setDateTimeStyles()setDateTimePattern()lastOperationStatusDateTimeStyleDateTimeFormatterLastOperationStatus
getDateTimePattern + Returns the pattern string used by this DateTimeFormatter object to format dates and times.A string containing the pattern used by this DateTimeFormatter object to format dates and times. + + String + Returns the pattern string used by this DateTimeFormatter object to format dates and times. + +

This pattern can be set in one of three ways:

+
  1. By the dateStyle and timeStyle parameters used in the constructor
  2. By the setDateTimeStyles() method
  3. By the setDateTimePattern() method.
+

For a description of the pattern syntax, see the + setDateTimePattern() method. +

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
DateTimeFormattersetDateTimeStyles()setDateTimePattern()lastOperationStatusLastOperationStatus
getFirstWeekday + Returns an integer corresponding to the first day of the week for this locale and calendar system.An integer corresponding to the first day of the week for this locale and calendar system. + + int + Returns an integer corresponding to the first day of the week for this locale and calendar system. + A value of 0 corresponds to Sunday, 1 corresponds to Monday, and so on, with 6 corresponding to Saturday. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getMonthNames + Retrieves a list of localized strings containing the month names for the current calendar system.if the nameStyle or context parameter is null. + + TypeErrorTypeErrorA vector of localized strings containing the month names for the specified locale, name style, and context. + The first element in the vector, at index 0, is the name for the first month of the year; the next element is + the name for the second month of the year; and so on. + nameStyleStringfullIndicates the style of name string to be used. Valid values are: +
  • DateTimeNameStyle.FULL
  • DateTimeNameStyle.LONG_ABBREVIATION
  • DateTimeNameStyle.SHORT_ABBREVIATION
+
contextStringstandaloneA code indicating the context in which the formatted string is used. + This context makes a difference only for certain locales. Valid values are: +
  • DateTimeNameContext.FORMAT
  • DateTimeNameContext.STANDALONE
+ +
+ Retrieves a list of localized strings containing the month names for the current calendar system. + The first element in the list is the name for the first month of the year. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusDateTimeNameContextDateTimeNameStyleLastOperationStatus
getTimeStyle + Gets the time style for this instance of the DateTimeFormatter.The time style string for this formatter. +

Possible values:

+
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
  • DateTimeStyle.CUSTOM
+ +
String
+ Gets the time style for this instance of the DateTimeFormatter. The time style is used to retrieve a + predefined time formatting pattern from the operating system. + + The time style value can be set by the DateTimeFormatter() constructor, the setDateTimeStyles() + method or the setDateTimePattern() method. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
setDateTimeStyles()setDateTimePattern()lastOperationStatusDateTimeStyleDateTimeFormatterLastOperationStatus
getWeekdayNames + Retrieves a list of localized strings containing the names of weekdays for the current calendar system.if the nameStyle or context parameter is null. + + TypeErrorTypeErrorA vector of localized strings containing the month names for the specified locale, name style, and context. + The first element in the vector, at index 0, is the name for Sunday; the next element is the name + for Monday; and so on. + nameStyleStringfullIndicates the style of name string to be used. Valid values are: +
  • DateTimeNameStyle.FULL
  • DateTimeNameStyle.LONG_ABBREVIATION
  • DateTimeNameStyle.SHORT_ABBREVIATION
+
contextStringstandaloneA code indicating the context in which the formatted string is used. + This context only applies for certain locales where the name of a month changes depending on the context. + For example, in Greek the month names are different if they are displayed alone versus displayed along with a day. + Valid values are: +
  • DateTimeNameContext.FORMAT
  • DateTimeNameContext.STANDALONE
+ +
+ Retrieves a list of localized strings containing the names of weekdays for the current calendar system. + The first element in the list represents the name for Sunday. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusDateTimeNameContextDateTimeNameStyleLastOperationStatus
setDateTimePattern + Sets the pattern string used by this DateTimeFormatter object to format dates and times.if the pattern parameter is null. + TypeErrorTypeErrorpatternString + Sets the pattern string used by this DateTimeFormatter object to format dates and times. + +

The pattern used to format dates can be set in one of three ways:

+
  1. By the dateStyle and timeStyle parameters used in the constructor
  2. By the setDateTimeStyles() method
  3. By this setDateTimePattern() method.
+

+ As a side effect this method overrides the current time and date styles for this DateTimeFormatter object and set them + to the value DateTimeStyle.CUSTOM. +

+

A pattern string defines how date and times are formatted. The pattern contains sequences of letters that are replaced + with date and time values in the formatted string. + For example, in the pattern "yyyy/MM" the characters "yyyy" are replaced with a four-digit year, followed by a + "/" character, and the characters "MM" are replaced with a two-digit month. +

+

Many of the letters used in patterns can be repeated more than once to produce different outputs, + as described in the table below. +

+ If a sequence exceeds the maximum number of letters supported by a pattern, + it is mapped back to the longest supported sequence for that pattern letter. + For example: +

+
  • MMMMMM is replaced with MMMM
  • dddd is replaced with dd
  • EEEEEEE is replaced with EEEE
  • aa is replaced with a
  • hhh is replaced with hh
  • mmmm is replaced with mm
+

In theory a pattern can contain up to 255 characters, but some platforms have stricter limit. + If the pattern exceeds the pattern character limit, the lastOperationStatus property is set to the value + LastOperationStatus.PATTERN_SYNTAX_ERROR. +

+

Not all possible patterns are supported on each operating system. If a pattern is not supported on the platform + then a fallback pattern is used + and the lastOperationStatus property is set to indicate the use of a fallback. + If no reasonable fallback pattern can be provided, an empty string is used + and the lastOperationStatus property is set to indicate that the pattern was unsupported. +

+

The following table describes the valid pattern letters and their meaning. +

+ + Pattern letterDescriptionGEra. Replaced by the Era string for the current date and calendar. This pattern is not supported on all + operating systems. On operating systems that do not support the era, the letters of the input pattern + are replaced by an empty string. +

There can be one to five letters in era patterns that are interpreted as follows:

+
  • If the number of pattern letters is one to three, the abbreviated form is used.
  • If the number of pattern letters is four, the format is interpreted as the full form.
  • If the number of pattern letters is five, the format is interpreted as the short abbreviation.
+

Examples with the Gregorian Calendar(for operating systems that support this pattern):

+
  • G, GG, GGG = AD
  • GGGG = Anno Domini
  • GGGGG = A
yYear. If the number of pattern letters is two, the last two digits of the year are displayed; otherwise the number of letters determines + the number of digits. If the year value requires more digits than provided by the number of letters, then the full + year value is provided. If there are more letters than required by the value, then the year values are padded with zeros. + The following list shows the results for the years 1 and 2005. +

Examples:

+
  • y = 1
  • y = 2005
  • yy = 01
  • yy = 05
  • yyyy = 0001 or 01, Depending on the operating system.
  • yyyy = 2005
  • yyyyy = 01 or 0001, Depending on the operating system. More than four y's fall back to the maximum number of digits supported on the operating system.
  • yyyyy = 2005
M Month in year. There can be one to five letters in month patterns that are interpreted as follows: +
  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
  • If the number of pattern letters is three, the format is interpreted as the long abbreviation.
  • If the number of pattern letters is four, the format is interpreted as the full name.
  • If the number of pattern letters is five, the format is interpreted as the short abbreviation. This format is not supported + on all operating systems and falls back to the long abbreviation.
+

Examples:

+
  • M = 7
  • MM = 07
  • MMM = Jul, 7月
  • MMMM = July, 7月
  • MMMMM = J or Jul, 7 or 7月 depending on the operating system.
d Day of the month. There can be one or two letters in day of the month patterns that are interpreted as follows: +
  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
+

Examples:

+
  • d = 4
  • dd = 04
  • dd = 14
EDay in week. There can be one to five letters in day of the week patterns that are interpreted as follows: +
  • If the number of pattern letters is one to three, the format is interpreted as the long abbreviation.
  • If the number of pattern letters is four, the format is interpreted as the full name.
  • If the number of pattern letters is five, the format is interpreted as the short abbreviation. This format is not supported + on all operating systems and falls back to the long abbreviation.
+

Examples:

+
  • E, EE, EEE = Tues
  • EEEE = Tuesday
  • EEEEE = T or Tues depending on the operating system.
QQuarter. Some platforms do not support this pattern. There can be one to four letters in quarter patterns that are interpreted as follows: +
  • If the number of pattern letters is one, the format is interpreted as numeric in one digit.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
  • If the number of pattern letters is three, the format is interpreted as the abbreviation.
  • If the number of pattern letters is four, the format is interpreted as the full name.
+

Examples (for operating systems that support this pattern):

+
  • Q = 2
  • QQ = 02
  • QQQ = Q2
  • QQQQ = second quarter
wWeek of the year. Some platforms do not support this pattern. There can be one to two letters in this pattern that are interpreted as follows. +
  • If the number of pattern letters is one, the format is interpreted as numeric in one or two digits.
  • If the number of pattern letters is two, the format is interpreted as numeric in two digits.
+

Examples for the second week of the year (for operating systems that support this pattern):

+
  • w = 2
  • ww = 02
WWeek of the month. Some platforms do not support this pattern. This pattern allows one letter only. +

Examples for the second week of July (for operating systems that support this pattern):

+
  • W = 2
DDay of the year. Some platforms do not support this pattern. There can be one to three letters in this pattern. +

Examples for the second day of the year (for operating systems that support this pattern):

+
  • D = 2
  • DD = 02
  • DDD = 002
FOccurrence of a day of the week within a calendar month. For example, this element displays "3" + if used to format the date for the third Monday in October. This pattern allows one letter only. +

Examples for the second Wednesday in July (for operating systems that support this pattern):

+
  • F = 2
aAM/PM indicator. This pattern allows one letter only, a or p. +

Examples:

+
  • a = AM, 午前
  • p = PM, 午後
hHour of the day in a 12-hour format [1 - 12]. This pattern must be one or two letters. +

Examples:

+
  • h = 1
  • h = 12
  • hh = 01
HHour of the day in a 24-hour format [0 - 23]. This pattern must be one or two letters. +

Examples:

+
  • H = 0
  • H = 23
  • HH = 00
KHour in the day in a 12-hour format [0 - 11]. This pattern must be one or two letters. + This pattern is not supported on all operating systems. +

Examples (for operating systems that support this pattern):

+
  • K = 0
  • K = 11
  • KK = 00
kHour of the day in a 24-hour format [1 - 24]. This pattern must be one or two letters. + This pattern is not supported on all operating systems. +

Examples (for operating systems that support this pattern):

+
  • k = 1
  • k = 24
  • kk = 01
mMinute of the hour [0 - 59]. This pattern must be one or two letters. +

Examples:

+
  • m = 2
  • m = 59
  • mm = 02
sSeconds in the minute [0 - 59]. This pattern must be one or two letters. +

Examples:

+
  • s = 2
  • s = 59
  • ss = 02
SMilliseconds. This pattern must be one to five letters. The value is rounded according to the + number of letters used. When five characters are used (SSSSS) it denotes fractional milliseconds. +

Examples:

+
  • S = 2
  • SS = 24
  • SSS = 235
  • SSSS = 2350
  • SSSSS = 23500
zTime Zone. Represents the time zone as a string that respects standard or daylight time, without referring to a specific + location. This pattern is not supported on all operating systems. On operating systems that do not support + time zone patterns, the letters of the input pattern are replaced by an empty string. On operating + systems that do support this pattern, not all locales have a defined string. Those locales fall back + to a localized GMT format such as GMT-08:00 or GW-08:00 +

There must be one to four letters in this time zone pattern, interpreted as follows:

+
  • If the number of pattern letters is one to three, the format is interpreted as abbreviated form.
  • If the number of pattern letters is four, the format is interpreted as the full name.
+

Examples for operating systems that support this format:

+
  • z, zz, zzz = PDT
  • z, zz, zzz = PST
  • z, zz, zzz = GMT-0800
  • zzzz = Pacific Daylight Time
  • zzzz = Pacific Standard Time
ZTime Zone. Represents the time zone as an offset from GMT. This pattern is not supported on all operating systems. On operating systems that do not support + time zone patterns, the letters of the input pattern are replaced by an empty string. +

There must be one to four letters in this time zone pattern, interpreted as follows:

+
  • If the number of pattern letters is one to three, the format uses the RFC 822 format.
  • If the number of pattern letters is four, the format uses the localized GMT format. This + falls back to the non-localized GMT format for locales that do not have a localized GMT format.
+

Examples for operating systems that support this format:

+
  • Z, ZZ, ZZZ = -0800
  • ZZZZ = GMT-08:00, GW-08:00
vTime Zone. A string reflecting the generic time zone that does not refer to a specific + location or distinguish between daylight savings time or standard time. This pattern is not supported on all operating systems. On operating systems that do not support + time zone patterns the letters of the input pattern are replaced by an empty string. On operating + systems that support this pattern, fallback strings are provided if a localized name is not + available. +

There must be one or four letters in this time zone pattern, interpreted as follows:

+
  • If the number of pattern letters is one, the format uses the abbreviated form.
  • If the number of pattern letters is four, the format uses the full form.
+

Examples for operating systems that support this format:

+
  • v = PT
  • vvvv = Pacific Time
'Other text'Text and punctuation may be included in the pattern string. However the characters from a to z and A to Z, are reserved as + syntax characters and must be enclosed in single quotes to be included in + the formatted string. To include a single quote in the result string, two single quotes must be used in the + pattern string. The two single quotes may appear inside or outside a quoted portion of the pattern string. + An unmatched pair of single quotes is terminated at the end of the string. +

Examples:

+
  • EEEE, MMM. d, yyyy 'at' h 'o''clock' a= Tuesday, Sept. 8, 2005 at 1 o'clock PM
  • yyyy年M月d日 = 2005年9月8日
  • mm''ss'' = 43'01'
+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
DateTimeFormattersetDateTimeStyles()setDateTimePattern()lastOperationStatusLastOperationStatus
setDateTimeStyles + Sets the date and time styles for this instance of the DateTimeFormatter.if the dateStyle or timeStyle parameter is not a valid DateTimeStyle constant. + ArgumentErrorArgumentErrorif the dateStyle or timeStyle parameter is null. + + TypeErrorTypeErrordateStyleStringSpecifies the style to use when formatting dates. + The value corresponds to one of the values enumerated by the DateTimeStyle class: +
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
+
timeStyleStringSpecifies the style to use when formatting times. + The value corresponds to one of the values enumerated by the DateTimeStyle class: +
  • DateTimeStyle.LONG
  • DateTimeStyle.MEDIUM
  • DateTimeStyle.SHORT
  • DateTimeStyle.NONE
+ +
+ Sets the date and time styles for this instance of the DateTimeFormatter. Date and time styles are used to set + date and time formatting patterns to predefined, locale-dependent patterns from the operating system. + + This method replaces the styles that were set using the DateTimeFormatter() constructor or + using the setDateTimePattern() method. The date and time pattern is + also updated based on the styles that are set. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
DateTimeFormatter()setDateTimeStyles()setDateTimePattern()lastOperationStatusDateTimeStyleLastOperationStatus
actualLocaleIDName + The name of the actual locale ID used by this DateTimeFormatter object.String + The name of the actual locale ID used by this DateTimeFormatter object. + +

There are three possibilities for the value of the name, depending on operating system and the + value of the requestedLocaleIDName parameter passed to the Collator() constructor.

+
  1. If the requested locale was not LocaleID.DEFAULT and + the operating system provides support for the requested locale, + then the name returned is the same as the requestedLocaleIDName property. +
  2. If LocaleID.DEFAULT was used as the value for the requestedLocaleIDName + parameter to the constructor, then the name of the current locale specified by the user's operating system is + used. The LocaleID.DEFAULT value preserves user's customized setting in the OS. + Passing an explicit value as the requestedLocaleIDName parameter does not necessarily give the + same result as using the LocaleID.DEFAULT even if the two locale ID names are the same. + The user might have customized the locale settings on their machine, and by requesting an + explicit locale ID name rather than using LocaleID.DEFAULT your application would not + retrieve those customized settings. +
    +

    For example:

    + + var fmt:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT); + var aliName:String = fmt.actualLocaleIDName; + +

    In the above example, aliName is the name of the locale corresponding to + the user's current operating systems settings (e.g. "it-IT" if the user's locale is set to Italian-Italy), + and not "i-default" (the name of the LocaleID.DEFAULT locale).

    +
  3. If the system does not support the requestedLocaleIDName specified in the constructor + then a fallback locale ID name is provided. +
    +

    For Example:

    + + var fmt:DateTimeFormatter = new DateTimeFormatter("fr-CA"); + var aliName:String = fmt.actualLocaleIDName; + +

    Assuming that the operating system in the example above does not support the "fr-CA" (French-Canada) locale ID, + a fallback is used. In this case the fallback locale ID is "fr-FR" (French-France).

    +
+ +
LocaleIDrequestedLocaleIDNameDateTimeFormatter()
lastOperationStatus + The status of previous operation that this DateTimeFormatter object performed.String + The status of previous operation that this DateTimeFormatter object performed. + The lastOperationStatus property is set whenever the constructor or a method of + this class is called, or another property is set. For the possible values see the description for each method. + + LastOperationStatusrequestedLocaleIDName + The name of the requested locale ID that was passed to the constructor of this DateTimeFormatter object.String + The name of the requested locale ID that was passed to the constructor of this DateTimeFormatter object. + +

If the LocaleID.DEFAULT value was used then the name returned is "i-default". + The actual locale used can differ from the requested locale when a fallback locale is applied. + The name of the actual locale can be retrieved using the actualLocaleIDName property. +

+ +
LocaleIDactualLocaleIDNameDateTimeFormatter()
LastOperationStatus + The LastOperationStatus class enumerates constant values that represent the status of the most recent globalization service operation.Object + The LastOperationStatus class enumerates constant values that represent the status of the most recent globalization service operation. + These values can be retrieved through the read-only property lastOperationStatus available in most globalization + classes. + + BUFFER_OVERFLOW_ERROR + Indicates that given buffer is not enough to hold the result.bufferOverflowErrorString + Indicates that given buffer is not enough to hold the result. + + ERROR_CODE_UNKNOWN + Indicates that the return error code is not known.errorCodeUnknownString + Indicates that the return error code is not known. + + Any non-static method or read/write properties can return this error when the operation is not successful + and the return error code is not known. + + ILLEGAL_ARGUMENT_ERROR + Indicates that an argument passed to a method was illegal.illegalArgumentErrorString + Indicates that an argument passed to a method was illegal. + +

For example, the following code shows that an invalid argument error status is set + when CurrencyFormatter.grouping property is set to the invalid value "3;".

+ + + var cf:CurrencyFormatter = new CurrencyFormatter("en-US"); + cf.groupingPattern = "3;"; + trace(cf.lastOperationStatus); // "illegalArgumentError" + + +
INDEX_OUT_OF_BOUNDS_ERROR + Indicates that an iterator went out of range or an invalid parameter was specified for month, day, or time.indexOutOfBoundsErrorString + Indicates that an iterator went out of range or an invalid parameter was specified for month, day, or time. + + INVALID_ATTR_VALUE + Indicates that a given attribute value is out of the expected range.invalidAttrValueString + Indicates that a given attribute value is out of the expected range. + +

The following example shows that setting the NumberFormatter.negativeNumberFormat + property to an out-of-range value results in an invalid attribute value status. +

+ + var nf:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT); + nf.negativeNumberFormat = 9; + nf.lastOperationStatus; // "invalidAttrValue" + + +
INVALID_CHAR_FOUND + Indicates that invalid Unicode value was found.invalidCharFoundString + Indicates that invalid Unicode value was found. + + MEMORY_ALLOCATION_ERROR + Indicates that memory allocation has failed.memoryAllocationErrorString + Indicates that memory allocation has failed. + + NO_ERROR + Indicates that the last operation succeeded without any errors.noErrorString + Indicates that the last operation succeeded without any errors. This status can be returned + by all constructors, non-static methods, static methods and read/write properties. + + NUMBER_OVERFLOW_ERROR + Indicates that an operation resulted a value that exceeds a specified numeric type.numberOverflowErrorString + Indicates that an operation resulted a value that exceeds a specified numeric type. + + PARSE_ERROR + Indicates that the parsing of a number failed.parseErrorString + Indicates that the parsing of a number failed. + This status can be returned by parsing methods of the formatter classes, such as + CurrencyFormatter.parse() and NumberFormatter.parseNumber(). For example, if the value "12abc34" is passed + as the parameter to the CurrencyFormatter.parse() method, the method returns "NaN" and sets the + lastOperationStatus value to LastOperationStatus.PARSE_ERROR. + + PATTERN_SYNTAX_ERROR + Indicates that the pattern for formatting a number, date, or time is invalid.patternSyntaxErrorString + Indicates that the pattern for formatting a number, date, or time is invalid. + + This status is set when the user's operating system does not support the given pattern. + +

For example, the following code shows the value of the lastOperationStatus property after + an invalid "xx" pattern is used for date formatting:

+ + var df:DateTimeFormatter = new DateTimeFormatter("en-US"); + df.setDateTimePattern("xx"); + trace(df.lastOperationStatus); // "patternSyntaxError" + + +
PLATFORM_API_FAILED + Indicates that an underlying platform API failed for an operation.platformAPIFailedString + Indicates that an underlying platform API failed for an operation. + + TRUNCATED_CHAR_FOUND + Indicates that a truncated Unicode character value was found.truncatedCharFoundString + Indicates that a truncated Unicode character value was found. + + UNEXPECTED_TOKEN + Indicates that an unexpected token was detected in a Locale ID string.unexpectedTokenString + Indicates that an unexpected token was detected in a Locale ID string. + +

For example, the following code shows the value of the lastOperationStatus property after + an incomplete string is used when requesting a locale ID. As a result the lastOperationStatus + property is set to the value UNEXPECTED_TOKEN after a call to the + LocaleID.getKeysAndValues() method. +

+ + var locale:LocaleID = new LocaleID("en-US@Collation"); + var kav:Object = locale.getKeysAndValues(); + trace(locale.lastOperationStatus); // "unexpectedToken" + + +
UNSUPPORTED_ERROR + Indicates that the requested operation or option is not supported.unsupportedErrorString + Indicates that the requested operation or option is not supported. This status can be returned by methods like + DateTimeFormatter.setDateTimePattern() and when retrieving properties like + Collator.ignoreCase. + + USING_DEFAULT_WARNING + Indicates that an operating system default value was used during the most recent operation.usingDefaultWarningString + Indicates that an operating system default value was used during the most recent operation. + Class constructors can return this status. + + USING_FALLBACK_WARNING + Indicates that a fallback value was set during the most recent operation.usingFallbackWarningString + Indicates that a fallback value was set during the most recent operation. + This status can be returned by constructors and methods like DateTimeFormatter.setDateTimeStyles(), + and when retrieving properties like CurrencyFormatter.groupingPattern. + +
NationalDigitsType + The NationalDigitsType class enumerates constants that indicate digit sets used by the NumberFormatter class.Object + The NationalDigitsType class enumerates constants that indicate digit sets used by the NumberFormatter class. + The value of each constant represents the Unicode value for the zero digit in the specified decimal digit set. + + ARABIC_INDIC + Represents the Unicode value for the zero digit of the Arabic-Indic digit set.0x0660uint + Represents the Unicode value for the zero digit of the Arabic-Indic digit set. + + BALINESE + Represents the Unicode value for the zero digit of the Balinese digit set.0x1B50uint + Represents the Unicode value for the zero digit of the Balinese digit set. + + BENGALI + Represents the Unicode value for the zero digit of the Bengali digit set.0x09E6uint + Represents the Unicode value for the zero digit of the Bengali digit set. + + CHAM + Represents the Unicode value for the zero digit of the Cham digit set.0xAA50uint + Represents the Unicode value for the zero digit of the Cham digit set. + + DEVANAGARI + Represents the Unicode value for the zero digit of the Devanagari digit set.0x0966uint + Represents the Unicode value for the zero digit of the Devanagari digit set. + + EUROPEAN + Represents the Unicode value for the zero digit of the Latin-1 (European) digit set.0x0030uint + Represents the Unicode value for the zero digit of the Latin-1 (European) digit set. + + EXTENDED_ARABIC_INDIC + Represents the Unicode value for the zero digit of the Extended Arabic-Indic digit set.0x06F0uint + Represents the Unicode value for the zero digit of the Extended Arabic-Indic digit set. + + FULL_WIDTH + Represents the Unicode value for the zero digit of the Fullwidth digit set.0xFF10uint + Represents the Unicode value for the zero digit of the Fullwidth digit set. + + GUJARATI + Represents the Unicode value for the zero digit of the Gujarati digit set.0x0AE6uint + Represents the Unicode value for the zero digit of the Gujarati digit set. + + GURMUKHI + Represents the Unicode value for the zero digit of the Gurmukhi digit set.0x0A66uint + Represents the Unicode value for the zero digit of the Gurmukhi digit set. + + KANNADA + Represents the Unicode value for the zero digit of the Kannada digit set.0x0CE6uint + Represents the Unicode value for the zero digit of the Kannada digit set. + + KAYAH_LI + Represents the Unicode value for the zero digit of the Kayah Li digit set.0xA900uint + Represents the Unicode value for the zero digit of the Kayah Li digit set. + + KHMER + Represents the Unicode value for the zero digit of the Khmer digit set.0x17E0uint + Represents the Unicode value for the zero digit of the Khmer digit set. + + LAO + Represents the Unicode value for the zero digit of the Lao digit set.0x0ED0uint + Represents the Unicode value for the zero digit of the Lao digit set. + + LEPCHA + Represents the Unicode value for the zero digit of the Lepcha digit set.0x1C40uint + Represents the Unicode value for the zero digit of the Lepcha digit set. + + LIMBU + Represents the Unicode value for the zero digit of the Limbu digit set.0x1946uint + Represents the Unicode value for the zero digit of the Limbu digit set. + + MALAYALAM + Represents the Unicode value for the zero digit of the Malayalam digit set.0x0D66uint + Represents the Unicode value for the zero digit of the Malayalam digit set. + + MONGOLIAN + Represents the Unicode value for the zero digit of the Mongolian digit set.0x1810uint + Represents the Unicode value for the zero digit of the Mongolian digit set. + + MYANMAR_SHAN + Represents the Unicode value for the zero digit of the Myanmar Shan digit set.0x1090uint + Represents the Unicode value for the zero digit of the Myanmar Shan digit set. + + MYANMAR + Represents the Unicode value for the zero digit of the Myanmar digit set.0x1040uint + Represents the Unicode value for the zero digit of the Myanmar digit set. + + NEW_TAI_LUE + Represents the Unicode value for the zero digit of the New Tai Lue digit set.0x19D0uint + Represents the Unicode value for the zero digit of the New Tai Lue digit set. + + NKO + Represents the Unicode value for the zero digit of the Nko digit set.0x07C0uint + Represents the Unicode value for the zero digit of the Nko digit set. + + OL_CHIKI + Represents the Unicode value for the zero digit of the Ol Chiki digit set.0x1C50uint + Represents the Unicode value for the zero digit of the Ol Chiki digit set. + + ORIYA + Represents the Unicode value for the zero digit of the Oriya digit set.0x0B66uint + Represents the Unicode value for the zero digit of the Oriya digit set. + + OSMANYA + Represents the Unicode value for the zero digit of the Osmanya digit set.0x104A0uint + Represents the Unicode value for the zero digit of the Osmanya digit set. + + SAURASHTRA + Represents the Unicode value for the zero digit of the Saurashtra digit set.0xA8D0uint + Represents the Unicode value for the zero digit of the Saurashtra digit set. + + SUNDANESE + Represents the Unicode value for the zero digit of the Sundanese digit set.0x1BB0uint + Represents the Unicode value for the zero digit of the Sundanese digit set. + + TAMIL + Represents the Unicode value for the zero digit of the Tamil digit set.0x0BE6uint + Represents the Unicode value for the zero digit of the Tamil digit set. + + TELUGU + Represents the Unicode value for the zero digit of the Telugu digit set.0x0C66uint + Represents the Unicode value for the zero digit of the Telugu digit set. + + THAI + Represents the Unicode value for the zero digit of the Thai digit set.0x0E50uint + Represents the Unicode value for the zero digit of the Thai digit set. + + TIBETAN + Represents the Unicode value for the zero digit of the Tibetan digit set.0x0F20uint + Represents the Unicode value for the zero digit of the Tibetan digit set. + + VAI + Represents the Unicode value for the zero digit of the Vai digit set.0xA620uint + Represents the Unicode value for the zero digit of the Vai digit set. + + CurrencyParseResult + A data structure that represents a currency amount and currency symbol or string that were extracted by parsing a currency value.Object + A data structure that represents a currency amount and currency symbol or string that were extracted by parsing a currency value. + + CurrencyFormatter.parse()CurrencyParseResult + Constructs a currency parse result object.valueNumberunknownA number representing the currency amount value. + symbolStringA string representing the currency symbol. + + + Constructs a currency parse result object. + + currencyString + The portion of the input string that corresponds to the currency symbol or currency string.String + The portion of the input string that corresponds to the currency symbol or currency string. + + value + The currency amount value that was extracted from the input string.Number + The currency amount value that was extracted from the input string. + + NumberParseResult + A data structure that holds information about a number that was extracted by parsing a string.Object + A data structure that holds information about a number that was extracted by parsing a string. + +

The number string can contain a prefix and suffix surrounding a number. In such + cases the startIndex property is set to the first character of the number. + Also, the endIndex property + is set to the index of the character that follows the last character of the number. +

+ +
NumberFormatter.parse()NumberFormatter.parseNumber()NumberParseResult + Constructs a number parse result object.valueNumberunknownThe value of the numeric portion of the input string. + startIndexint0x7fffffffThe index of the first character of the number in the input string. + endIndexint0x7fffffffThe index of the character after the last character of the number in the input string. + + + Constructs a number parse result object. NumberParseResult objects are usually created by the + NumberFormatter.parse() and NumberFormatter.parseNumber() methods, rather + than by calling this constructor directly. + + NumberFormatter.parse()NumberFormatter.parseNumber()endIndex + The index of the character after the last character of the numeric portion of the input string.int + The index of the character after the last character of the numeric portion of the input string. + + startIndex + The index of the first character of the numeric portion of the input string.int + The index of the first character of the numeric portion of the input string. + + value + The value of the numeric portion of the input string.Number + The value of the numeric portion of the input string. + +
LocaleID + The LocaleID class provides methods for parsing and using locale ID names.Object + The LocaleID class provides methods for parsing and using locale ID names. This class supports locale ID names + that use the syntax defined by the Unicode Technical Standard #35 + (http://unicode.org/reports/tr35/). + + The following example shows how to retrieve and display information about LocaleID strings + for different locales. +

+ This example uses the following locales: Arabic (Saudi Arabia), English (US), English (US, POSIX variant), Chinese (PRC), + Chinese (Taiwan), Chinese (Simplified Han Script), Chinese (PRC with several keys and values) +

+

+ The example does the following for each locale in the list: +

+
  1. Creates a new LocaleID object.
  2. Displays various properties of the LocaleID. The values shown will differ based on your operating system and user preferences.
  3. Displays the full set of keys and values for the LocaleID.
+ +package +{ + import flash.display.Sprite; + import flash.globalization.LocaleID; + + public class LocaleIDExample extends Sprite + { + public function LocaleIDExample() + { + var localeNames:Array = ["ar-SA", "EN_us", "en-US-POSIX", "zh-CH", "zh-TW", "zh-Hans", "zh-CH@collation=pinyin;calendar=chinese;currency=RMB"]; + + for ( var i:int = 0; i < localeNames.length; i++ ) + { + var locID:LocaleID = new LocaleID( localeNames[i] as String ); + + trace('\n\n' + "LocaleID requested: " + locID.requestedLocaleIDName + + "; actual: " + locID.actualLocaleIDName); + trace( "Last Operation Status after new LocaleID: " + locID.lastOperationStatus); + + trace("name: " + locID.name); + trace("language: " + locID.getLanguage() + "; status: " + locID.lastOperationStatus); + trace("script: " + locID.getScript() + "; status: " + locID.lastOperationStatus); + trace("region: " + locID.getRegion() + "; status: " + locID.lastOperationStatus); + trace("variant: " + locID.getVariant() + "; status: " + locID.lastOperationStatus); + trace("isRightToLeft: ", locID.isRightToLeft(), "; status: " + locID.lastOperationStatus); + + var keysAndValues:Object = locID.getKeysAndValues(); + var key:String; + for (key in keysAndValues) + { + trace("key: ", key + " value: " + keysAndValues[ key ]); + } + trace( "Last Operation Status after getKeysAndValues(): " + locID.lastOperationStatus); + } + } + } +} +
Unicode Technical Standard #35LocaleID + Constructs a new LocaleID object, given a locale name.if the name is null. + + ArgumentErrorArgumentErrornameStringA locale ID name, which can also include an optional collation string. + For example: "en-US" or "de-DE@collation=phonebook" + + + Constructs a new LocaleID object, given a locale name. The locale name + must conform to the syntax defined by the Unicode Technical Standard #35 + (http://unicode.org/reports/tr35/). + +

When the constructor completes successfully the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

When the requested locale ID name is not available then the lastOperationStatus + is set to one of the following:

+
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+

Otherwise the lastOperationStatus property is set to one of the constants defined in + the LastOperationStatus class.

+ +

For details on the warnings listed above and other possible values of the lastOperationStatus property + see the descriptions in the LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
determinePreferredLocales + Returns a list of acceptable locales based on a list of desired locales and a list of the locales that are currently available.A subset of the available locales, sorted according to the user's preferences. + + wantA list of the user's preferred locales sorted in order of preference. + haveA list of locales available to the application. The order of this list is not important. + keywordStringuserinterfaceA keyword to use to help determine the best fit. + + + Returns a list of acceptable locales based on a list of desired locales and a list of the locales that are currently available. + +

The resulting list is sorted according in order of preference.

+ +

Here is a typical use case for this method:

+
  • A user specifies a list of languages that she understands + (stored in a user profile, a browser setting, or a cookie). + The user lists the languages that she understands best first, so the order of the languages in the list is relevant. + This list is the "want" list.
  • The application is localized into a number of different languages. + This list is the "have" list.
  • The determinePreferredLocales() method returns an intersection of the two lists, sorted so that the + user's preferred languages come first.
+ +

If this feature is not supported on the current operating system, this method returns a null value.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getKeysAndValues + Returns an object containing all of the key and value pairs from the LocaleID object.An Object containing all the keys and values in the LocaleID object, structured as an associative array or hashtable. + + Object + Returns an object containing all of the key and value pairs from the LocaleID object. + +

The returned object is structured as a hash table or associative array, where each property name represents a key + and the value of the property is value for that key. For example, the following code lists all of the keys and values + obtained from the LocaleID object using the getKeysAndValues() method:

+ + + var myLocale:LocaleID = new LocaleID("fr-CA"); + var localeData:Object = myLocale.getKeysAndValues(); + for (var propertyName:String in localeData) + { + trace(propertyName + " = " + localeData[propertyName]); + } + + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getLanguage + Returns the language code specified by the locale ID name.A two-character language code obtained by parsing the locale ID name. + + String + Returns the language code specified by the locale ID name. + +

If the locale name cannot be properly parsed then the language code is the same as the full locale name.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getRegion + Returns the region code specified by the locale ID name.A two-character region code, or an empty string if the region code cannot be parsed or otherwise + determined from the locale name. + + String + Returns the region code specified by the locale ID name. + +

This method returns an empty string if the region code cannot be parsed or guessed + This could occur if an unknown or incomplete locale ID name like "xy" is used. + The region code is not validated against a fixed list. For example, the region code returned for a locale ID name of + "xx-YY" is "YY".

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+ +

If the region is not part of the specified locale name, the most likely region code for the locale is "guessed" and + lastOperationStatus property is set to LastOperationStatus.USING_FALLBACK_WARNING

+ +

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getScript + Returns the script code specified by the locale ID name.A four-character script code, or an empty string if the script code cannot be parsed or otherwise + determined from the locale name. + + String + Returns the script code specified by the locale ID name. + +

This method returns an empty string if the script code cannot be parsed or guessed + This could occur if an unknown or incomplete locale ID name like "xy" is used. + The script code is not validated against a fixed list. For example, the script code returned for a locale ID name of + "xx-Abcd-YY" is "Abcd".

+ +

The region, as well as the language, can also affect the return value. For example, the script code for "mn-MN" + (Mongolian-Mongolia) is "Cyrl" (Cyrillic), while the script code for "mn-CN" (Mongolian-China) is + "Mong" (Mongolian).

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+ +

If the script code is not part of the specified locale name, the most likely script code is "guessed" and + lastOperationStatus property is set to LastOperationStatus.USING_FALLBACK_WARNING.

+ +

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getVariant + Returns the language variant code specified by the locale ID name.A language variant code, or an empty string if the locale ID name does not contain a language variant code. + + String + Returns the language variant code specified by the locale ID name. + +

This method returns an empty string if there is no language variant code in the given locale ID name. + (No guessing is necessary because few locales have or need a language variant.)

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
isRightToLeft + Specifies whtehr the text direction for the specified locale is right to left.true if the general text flows in a line of text should go from right to left; otherwise false; + + Boolean + Specifies whtehr the text direction for the specified locale is right to left. + +

The result can be used to determine the direction of the text in the Flash text engine, + and to decide whether to mirror the user interface to support the current text direction.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
flashx.textLayout.formats.DirectionlastOperationStatusLastOperationStatus
DEFAULT + Indicates that the user's default linguistic preferences should be used, as specified in the user's operating system settings.i-defaultString + Indicates that the user's default linguistic preferences should be used, as specified in the user's operating system settings. + For example, such preferences are typically set using the "Control Panel" for Windows, or the "System Preferences" in Mac OS X. + +

Using the LocaleID.DEFAULT setting can result in the use of a different locale ID name for different + kinds of operations. For example, one locale could be used for sorting and a different one for formatting. + This flexibility respects the user preferences, and the class behaves this way by design.

+ +

This locale identifier is not always the most appropriate one to use. + For applications running in the browser, the browser's preferred locale could be a better choice. + It is often a good idea to let the user alter the preferred locale ID name setting and preserve that preference + in a user profile, cookie, or shared object.

+ +
lastOperationStatus + The status of the most recent operation that this LocaleID object performed.String + The status of the most recent operation that this LocaleID object performed. + The lastOperationStatus property is set whenever the constructor or a method of + this class is called or another property is set. For the possible values see the description for each method. + + LastOperationStatusname + Returns a slightly more "canonical" locale identifier.String + Returns a slightly more "canonical" locale identifier. + +

This method performs the following conversion to the locale ID name to give it a more canonical form.

+
  • Proper casing is applied to all of the components.
  • Underscores are converted to dashes.
+ +

No additional processing is performed. For example, aliases are not replaced, and no elements are added or removed.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
DateTimeStyle + Enumerates constants that determine a locale-specific date and time formatting pattern.Object + Enumerates constants that determine a locale-specific date and time formatting pattern. These constants are used when + constructing a DateTimeFormatter object or when calling the DateTimeFormatter.setDateTimeStyles() method. + +

The CUSTOM constant cannot be used in the DateTimeFormatter constructor or the + DateFormatter.setDateTimeStyles() method. + This constant is instead set as the timeStyle and dateStyle property as a side effect of + calling the DateTimeFormatter.setDateTimePattern() method. +

+ +
DateTimeFormatterCUSTOM + Specifies that a custom pattern string is used to specify the date or time style.customString + Specifies that a custom pattern string is used to specify the date or time style. + + LONG + Specifies the long style of a date or time.longString + Specifies the long style of a date or time. + + MEDIUM + Specifies the medium style of a date or time.mediumString + Specifies the medium style of a date or time. + + NONE + Specifies that the date or time should not be included in the formatted string.noneString + Specifies that the date or time should not be included in the formatted string. + + SHORT + Specifies the short style of a date or time.shortString + Specifies the short style of a date or time. + +
StringTools + The StringTools class provides locale-sensitive case conversion methods.Object + The StringTools class provides locale-sensitive case conversion methods. + +

In some situations the + conversion between uppercase and lowercase letters is not a simple mapping from one character + to another and instead requires language- or context-specific processing. For example:

+
  • In Turkish and Azeri, + the uppercase of the dotted lowercase i is an uppercase dotted İ (U+0130). + Similarly the lowercase of a + dotless uppercase I, is a lowercase dotless ı (U+0131).
  • The lowercase sharp S, ß (U+00DF), used in German + is converted to uppercase double SS.
  • In Greek there are two representations of the + lowercase sigma, σ (U+03C3) and ς (U+03C2), which both convert to the single + uppercase sigma Σ (U+03A3).
+

+ The toLowerCase() and toUpperCase() methods of this + class provide this special case conversion logic. +

+

+ Due to the use of the user's settings, the use of case conversion rules + provided by the operating system, and the use of a fallback locale when a requested locale is not supported, + different users can see different case conversion results even when using the same locale ID. +

+ +
This example shows how different strings + are converted to lower case and upper case in a lingustically correct manner. + +

+ This example takes the following steps: +

+
  1. Creates a StringTools object.
  2. Defines three strings with characters unique to the Turkish, Greek, and German languages.
  3. Converts each string to upper case and lower case and displays the results. This example demonstrates interesting + locale-specific behavior for characters like the Turkish "ı" and "İ", the German "ß" and the Greek "Σςσ".
+ +package { + import flash.display.Sprite; + import flash.globalization.LocaleID; + import flash.globalization.StringTools; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class StringToolsExample extends Sprite + { + public function StringToolsExample() + { + var localeName:String= LocaleID.DEFAULT; + var strTool:StringTools = new StringTools(localeName); + + trace('\n\n' + "LocaleID requested: " + nf.requestedLocaleIDName + + "; actual: " + nf.actualLocaleIDName); + trace( "Last Operation Status:" + nf.lastOperationStatus ); + + var turkishStr:String = "iI ıİ"; + var greekStr:String = "Σςσβΰ�Σ"; + var germanStr:String= "ß"; + + var tfTurInp:TextField = createTextField(10, 10); + tfTurInp.text="Turkish Input: \t " + turkishStr; + + var tfdash:TextField = createTextField(10, 20); + tfdash.text="-------------------"; + + var tf1:TextField = createTextField(10, 30); + tf1.text="\t Upper case: \t " + strTool.toUpperCase(turkishStr); + + var tf2:TextField = createTextField(10, 40); + tf2.text="\t Lower case: \t " + strTool.toLowerCase(turkishStr); + + var tfgreekInp:TextField = createTextField(10, 60); + tfgreekInp.text="Greek Input: \t " + greekStr; + + var tfdash1:TextField = createTextField(10, 70); + tfdash1.text="-------------------"; + + var tf3:TextField = createTextField(10, 80); + tf3.text="\t Upper case: \t " + strTool.toUpperCase(greekStr); + + var tf4:TextField = createTextField(10, 90); + tf4.text="\t Lower case: \t " + strTool.toLowerCase(greekStr); + + var tfgermanInp:TextField = createTextField(10, 110); + tfgermanInp.text="German Input: \t " + germanStr; + + var tfdash2:TextField = createTextField(10, 120); + tfdash2.text="-------------------"; + + var tf5:TextField = createTextField(10, 130); + tf5.text="\t Upper case: \t " + strTool.toUpperCase(germanStr); + + var tf6:TextField = createTextField(10, 140); + tf6.text="\t Lower case: \t " + strTool.toLowerCase(germanStr); + } + + private function createTextField(x:Number, y:Number):TextField + { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.autoSize=TextFieldAutoSize.LEFT; + addChild(result); + return result; + } + } +} + + +
StringTools + Constructs a new StringTools object that provides case conversion and other utilities according to + the conventions of a given locale.when the requestedLocaleIDName parameter is null + + ArgumentErrorArgumentErrorrequestedLocaleIDNameStringThe preferred locale ID name to use when determining date or time formats. + + + Constructs a new StringTools object that provides case conversion and other utilities according to + the conventions of a given locale. + +

This constructor determines if the current operating system supports the requested locale ID name. + If it is not supported then a fallback locale is used instead. + If a fallback locale is used then the lastOperationStatus property + indicates the type of fallback, and the actualLocaleIDName property contains + the name of the fallback locale ID.

+ +

When this constructor completes successfully the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

When the requested locale ID name is not available then the lastOperationStatus + is set to one of the following:

+
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+

Otherwise the lastOperationStatus property is set to one of the constants defined in + the LastOperationStatus class.

+ +
LocaleIDlastOperationStatusrequestedLocaleIDNameactualLocaleIDName
getAvailableLocaleIDNames + Lists all of the locale ID names supported by this class.A vector of strings containing all of the locale ID names supported by this class. + + + Lists all of the locale ID names supported by this class. + +

If this class is not supported on the current operating system, this method returns a null value.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
toLowerCase + Converts a string to lowercase according to language conventions.when the s parameter is null. + + ArgumentErrorArgumentErrorThe converted lowercase string. + StringsStringA string to convert to lowercase. + + Converts a string to lowercase according to language conventions. + Depending on the locale, the output string length can differ from the input string length. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
toUpperCase + Converts a string to uppercase according to language conventions.when the s parameter is null. + + ArgumentErrorArgumentErrorThe converted uppercase string. + + StringsStringA string to convert to uppercase. + + Converts a string to uppercase according to language conventions. + Depending on the locale, the output string length can differ from the input string length. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
actualLocaleIDName + The name of the actual locale ID used by this StringTools object.String + The name of the actual locale ID used by this StringTools object. + +

There are three possibilities for the value of the name, depending on operating system and the + value of the requestedLocaleIDName parameter passed to the StringTools() constructor.

+ +
  1. If the requested locale was not LocaleID.DEFAULT and + the operating system provides support for the requested locale, + then the name returned is the same as the requestedLocaleIDName property. +
  2. If LocaleID.DEFAULT was used as the value for the requestedLocaleIDName + parameter to the constructor, then the name of the current locale specified by the user's operating system is + used. The LocaleID.DEFAULT value preserves user's customized setting in the OS. + Passing an explicit value as the requestedLocaleIDName parameter does not necessarily give the + same result as using the LocaleID.DEFAULT even if the two locale ID names are the same. + The user could have customized the locale settings on the machine, and by requesting an + explicit locale ID name rather than using LocaleID.DEFAULT your application would not + retrieve those customized settings. +
    +

    For example:

    + + + var tools:StringTools = new StringTools(LocaleID.DEFAULT); + var aliName:String = tools.actualLocaleIDName; + + +

    In the above example, aliName is the name of the locale corresponding to + the user's current operating systems settings (e.g. "it-IT" if the user's locale is set to Italian-Italy), + and not "i-default" (the name of the LocaleID.DEFAULT locale).

    +
  3. If the system does not support the requestedLocaleIDName specified in the constructor + then a fallback locale ID name is provided. +
    +

    For Example:

    + + + var tools:StringTools = new StringTools("fr-CA"); + var aliName:String = tools.actualLocaleIDName; + + +

    Assuming that the operating system in the example above does not support the "fr-CA" (French-Canada) locale ID, + a fallback is used. In this case the fallback locale ID is "fr-FR" (French-France).

    +
+ +
LocaleIDrequestedLocaleIDNameStringTools
lastOperationStatus + The status of the most recent operation that this StringTools object performed.String + The status of the most recent operation that this StringTools object performed. + The lastOperationStatus property is set whenever the constructor or a method of + this class is called or another property is set. For the possible values see the description for each method. + + LastOperationStatusrequestedLocaleIDName + The name of the requested locale ID that was passed to the constructor of this StringTools object.String + The name of the requested locale ID that was passed to the constructor of this StringTools object. + +

If the LocaleID.DEFAULT value was used then the name returned is "i-default". + The actual locale used can differ from the requested locale when a fallback locale is applied. + The name of the actual locale can be retrieved using the actualLocaleIDName property. +

+ +
LocaleIDactualLocaleIDNameStringTools()
CollatorMode + The CollatorMode class enumerates constant values that govern the behavior of string comparisons + performed by a Collator object.Object + The CollatorMode class enumerates constant values that govern the behavior of string comparisons + performed by a Collator object. + These constants represent the values that can be passed in the initialMode parameter + of the Collator() constructor. + + CollatorMATCHING + Initializes a Collator object so that the compare method is optimized for + determining whether two strings are equivalent.matchingString + Initializes a Collator object so that the compare method is optimized for + determining whether two strings are equivalent. + In this mode, string comparisons ignore differences in uppercase and lower + case letters, accented characters, etc. + + Collator() constructorSORTING + Initializes a Collator object so that the compare method is optimized for + sorting a list of text strings to be displayed to an end user.sortingString + Initializes a Collator object so that the compare method is optimized for + sorting a list of text strings to be displayed to an end user. + In this mode, string comparisons consider + differences in uppercase and lowercase letters, accented characters, and so on, + according to the language and sorting rules required by the locale. + + Collator() constructorNumberFormatter + The NumberFormatter class provides locale-sensitive formatting and parsing of numeric values.Object + The NumberFormatter class provides locale-sensitive formatting and parsing of numeric values. It can format int, + uint, and Number objects. + +

The NumberFormatter class uses the data and functionality provided by the operating system + and is designed to format numbers according to the conventions + of a specific locale, based on the user's preferences and features supported by the user's operating system. + The position of the negative symbol, the decimal separator, + the grouping separator, the grouping pattern, and other elements within the number format can vary depending on the locale.

+ +

If the operating system supports the requested locale, the number formatting properties + are set according to the conventions and defaults of the requested locale. + If the requested locale is not available, then the properties are set according to + a fallback or default system locale, which can be retrieved using the actualLocaleIDName property. +

+

+ Due to the use of the user's settings, the use of formatting patterns + provided by the operating system, and the use of a fallback locale when a requested locale is not supported, + different users can see different formatting results, even when using the same locale ID. +

+ +
This example shows how numbers can be formatted differently across different locales. + +

This example uses the following locales: default operating system locale for number formatting, Japanese (Japan), English (US), and + French (France). The example uses the static member LocaleID.DEFAULT to request the default operating system locale.

+

+ The results from this example might differ based on your operating system and user preferences. +

+

+ This example does the following for each locale in the list: +

+
  1. Creates a NumberFormatter object.
  2. Formats the same value as a Number, an integer, and an unsigned integer, and displays the results.
+ + +package { + import flash.globalization.NumberFormatter; + import flash.globalization.LocaleID; + + public class NumberFormatterExample extends Sprite + { + public function NumberFormatterExample():void + { + var localeNames:Array = [LocaleID.DEFAULT,"ja_JP","en_US","fr_FR"]; + + for ( var i:int = 0; i < localeNames.length; i++ ) + { + var nf:NumberFormatter = new NumberFormatter( localeNames[i] as String ); + trace('\n\n' + "LocaleID requested: " + nf.requestedLocaleIDName + + "; actual: " + nf.actualLocaleIDName); + trace( "Last Operation Status:" + nf.lastOperationStatus ); + + var numberString:String = nf.formatNumber(123456789.19); + trace( "Formatted Number:" + numberString); + numberString = nf.formatInt(-123456789); + trace( "Formatted Int:" + numberString); + numberString = nf.formatUint(123456789); + trace( "Formatted UInt:" + numberString); + } + } + } +} +
This example shows two different ways to parse an input string and extract a numeric value. +

+ The results from this example might differ based on your operating system and user preferences. +

+

+ This example does the following: +

+
  1. Creates a NumberFormatter object.
  2. Calls the NumberFormatter.parse() method to parse the string and return a NumberParseResult object.
  3. Calls the NumberFormatter.parseNumber() method to parse the string and return a Number value.
+ + +package { + import flash.globalization.NumberFormatter; + import flash.globalization.NumberParseResult; + import flash.globalization.LastOperationStatus; + import flash.globalization.LocaleID; + + public class NumberFormatterParseExample + { + public function NumberFormatterParseExample():void + { + var nf:NumberFormatter = new NumberFormatter( "en_US" ); + trace("LocaleID requested: " + nf.requestedLocaleIDName + + "; actual: " + nf.actualLocaleIDName); + trace( "Last Operation Status:" + nf.lastOperationStatus ); + + var inputNumberString:String = "123,567,89,0.254"; + var parseResult:NumberParseResult = nf.parse(inputNumberString); + if ( nf.lastOperationStatus == LastOperationStatus.NO_ERROR ) { + trace("Parsed value:" + parseResult.value); + } + inputNumberString = "-123,567,89,0.254"; + var parsedNumber:Number = nf.parseNumber(inputNumberString); + if ( nf.lastOperationStatus == LastOperationStatus.NO_ERROR ) { + trace("Parsed value:" + parsedNumber); + } + } + } +} +
NumberFormatter + Constructs a new NumberFormatter object to format numbers according to + the conventions of a given locale.if the requestedLocaleIDName is null + + TypeErrorTypeErrorrequestedLocaleIDNameStringThe preferred locale ID name to use when determining number formats. + + + Constructs a new NumberFormatter object to format numbers according to + the conventions of a given locale. + +

This constructor determines if the current operating system supports the requested locale ID name. + If it is not supported then a fallback locale is used instead. + If a fallback locale is used then the the lastOperationStatus property + indicates the type of fallback, and the actualLocaleIDName property contains + the name of the fallback locale ID.

+ +

To format based on the user's current operating system preferences, pass the value LocaleID.DEFAULT + in the requestedLocaleIDName parameter to the constructor. +

+ +

When the constructor completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+ +

When the requested locale ID name is not available then the lastOperationStatus + is set to one of the following:

+ +
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+ +

If this class is not supported on the current operating system, then the lastOperationStatus property is set to:

+
  • LastOperationStatus.UNSUPPORTED_ERROR
+ +

Otherwise the lastOperationStatus property is set to one of the constants defined in + the LastOperationStatus class.

+ +

For details on the warnings listed above and other possible values of the + lastOperationStatus property see the descriptions in the LastOperationStatus class.

+ +
LocaleIDrequestedLocaleIDNameactualLocaleIDNamelastOperationStatusLastOperationStatus
formatInt + Formats an int value.for any internal memory allocation problems. + + MemoryErrorflash.errors:MemoryErrorA formatted number string. + + StringvalueintAn int value to format. + + Formats an int value. + + This function is equivalent to the formatNumber() method except that it takes an int value. + If the value passed in is too large or small, such as a value greater than 1.72e308 or less than 1.72e-308, then this function returns 0. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusflash.globalization.LastOperationStatus
formatNumber + Formats a Number value.if there are any internal memory allocation problems. + + MemoryErrorflash.errors:MemoryErrorA formatted number string. + + StringvalueNumberA Number value to format. + + Formats a Number value. + +

This function formats the number based on the property values of the formatter. If the properties are + not modified after the the numberFormatter object is created, the numbers are formatted + according to the locale specific conventions provided by the operating system for the locale identified + by actualLocaleIDName. To customize the format, the properties can be altered to control specific + aspects of formatting a number. +

+ +

Very large numbers and very small magnitude numbers can be formatted with this function. However, the + number of significant digits is limited to the precision provided by the Number object. Scientific notation + is not supported. +

+ + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
formatUint + Formats a uint value.if there are any internal memory allocation problems. + + MemoryErrorflash.errors:MemoryErrorA formatted number string. + + StringvalueuintA uint value. + + Formats a uint value. + + This function is equivalent to the formatNumber() method except that it takes a uint. + If the value passed in is too large, such as a value greater than 1.72e308, then this function returns 0. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatus
getAvailableLocaleIDNames + Lists all of the locale ID names supported by this class.A vector of strings containing all of the locale ID names supported by this class. + + + Lists all of the locale ID names supported by this class. + +

If this class is not supported on the current operating system, this method returns a null value.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
parseNumber + Parses a string that contains only digits and optional whitespace characters and returns a Number.if the parseString is null + + TypeErrorTypeErrorNumberparseStringString + Parses a string that contains only digits and optional whitespace characters and returns a Number. + If the string does not begin + with a number or contains characters other than whitespace that are not part of the number, then + this method returns NaN. White space before or after the numeric digits is ignored. A white space + character is a character that has a Space Separator (Zs) property in the Unicode Character Database (see http://www.unicode.org/ucd/). + +

If the numeric digit is preceded or followed by a plus sign '+' it is treated as a non-whitespace character. + The return value is NaN. +

+ +

See the description of the parse function for more information about number parsing and what constitutes + a valid number. +

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatusparse()parseFloat()NationalDigitsType
parse + Parses a string and returns a NumberParseResult object containing the parsed elements.if the parseString is null + + TypeErrorTypeErrorflash.globalization:NumberParseResultparseStringString + Parses a string and returns a NumberParseResult object containing the parsed elements. + +

The NumberParseResult object contains + the value of the first number found in the input string, the starting index for the number within the string, and the index + of the first character after the number in the string.

+ +

If the string does not contain a number, the value property of the NumberParseResult is set to NaN and the + startIndex and endIndex properties are set to the hexadecimal value 0x7fffffff. +

+ +

This function uses the value of the decimalSeparator property to determine the portion of the number + that contains fractional + digits, and the groupingSeparator property to determine which characters are allowed within the digits of a number, + and the negativeNumberFormat property to control how negative values are represented.

+ +

The following table identifies the result of strings parsed for the various NegativeNumberFormat values:

+ NegativeNumberFormatInput StringResult(n)"(123)" or "( 123 )""-123"-n"-123" or "- 123""-123"- n"-123" or "- 123""-123"n-"123-" or "123 -""-123"n -"123-" or "123 -""-123" + +

A single white space is allowed between the number and the minus sign or parenthesis.

+ +

Other properties are ignored when determining a valid number. Specifically the value of the + digitsType property is ignored and the digits can be from any of + the digit sets that are enumerated in the NationalDigitsType class. The values of the groupingPattern + and useGrouping properties do not influence the parsing of the number. +

+ +

If numbers are preceded or followed in the string by a plus sign '+', the plus sign is treated as + a character that is not part of the number. +

+ +

This function does not parse strings containing numbers in scientific notation (e.g. 1.23e40).

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
The following code parses a number from a string and retrieves the prefix and suffix: + + var nf:NumberFormatter = new NumberFormatter("fr-FR"); + var str:String = "1,56 mètre" + var result:NumberParseResult = nf.parse(str); + trace(result.value) // 1.56 + trace(str.substr(0,result.startIndex)); // "" + trace(str.substr(result.startIndex, result.endIndex)); // "1,56" + trace(str.substr(result.endIndex)); // " mètre" + + +
lastOperationStatusLastOperationStatusNumberParseResultparseNumber()parseFloat()NationalDigitsType
actualLocaleIDName + The name of the actual locale ID used by this NumberFormatter object.String + The name of the actual locale ID used by this NumberFormatter object. + +

There are three possibilities for the value of the name, depending on operating system and the + value of the requestedLocaleIDName parameter passed to the Collator() constructor.

+
  1. If the requested locale was not LocaleID.DEFAULT and + the operating system provides support for the requested locale, + then the name returned is the same as the requestedLocaleIDName property. +
  2. If LocaleID.DEFAULT was used as the value for the requestedLocaleIDName + parameter to the constructor, then the name of the current locale specified by the user's operating system is + used. The LocaleID.DEFAULT value preserves user's customized setting in the OS. + Passing an explicit value as the requestedLocaleIDName parameter does not necessarily give the + same result as using the LocaleID.DEFAULT even if the two locale ID names are the same. + The user could have customized the locale settings on their machine, and by requesting an + explicit locale ID name rather than using LocaleID.DEFAULT your application would not + retrieve those customized settings. +
    +

    For example:

    + + + var fmt:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT); + var aliName:String = fmt.actualLocaleIDName; + + +

    In the above example, aliName is the name of the locale corresponding to + the user's current operating systems settings (e.g. "it-IT" if the user's locale is set to Italian-Italy), + and not "i-default" (the name of the LocaleID.DEFAULT locale).

    +
  3. If the system does not support the requestedLocaleIDName specified in the constructor + then a fallback locale ID name is provided. +
    +

    For Example:

    + + + var fmt:NumberFormatter = new NumberFormatter("fr-CA"); + var aliName:String = fmt.actualLocaleIDName; + + +

    Assuming that the operating system in the example above does not support the "fr-CA" (French-Canada) locale ID, + a fallback is used. In this case the fallback locale ID is "fr-FR" (French-France).

    +
+ +
LocaleIDrequestedLocaleIDNameNumberFormatter()
decimalSeparator + The decimal separator character used for formatting or parsing numbers that have a decimal part.Stringif this property is assigned a null value. + + TypeErrorTypeErrordependent on the locale and operating system. + + + The decimal separator character used for formatting or parsing numbers that have a decimal part. + +

This property is initially set based on the locale that is selected when the formatter object + is constructed.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
formatInt()formatNumber()formatUInt()lastOperationStatusLastOperationStatus
digitsType + Defines the set of digit characters to be used when formatting numbers.uintif this property is assigned a null value. + + TypeErrorTypeErrordependent on the locale and operating system. + + + Defines the set of digit characters to be used when formatting numbers. + +

Different languages and regions use different sets of characters to represent the + digits 0 through 9. This property defines the set of digits to be used.

+ +

The value of this property represents the Unicode value for the zero digit of a decimal digit set. + The valid values for this property are defined in the NationalDigitsType class.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatusNationalDigitsType
fractionalDigits + The maximum number of digits that can appear after the decimal separator.int0 + + + The maximum number of digits that can appear after the decimal separator. + +

Numbers are rounded to the number of digits specified by this property. The rounding scheme + varies depending on the user's operating system.

+ +

When the trailingZeros property is set to true, the fractional portion of the + number (after the decimal point) is padded with trailing zeros until its length matches the value of this + fractionalDigits property.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
trailingZeroslastOperationStatusflash.globalization.LastOperationStatus
groupingPattern + Describes the placement of grouping separators within the formatted number string.Stringif this property is assigned a null value. + + TypeErrorTypeError + Describes the placement of grouping separators within the formatted number string. + +

When the useGrouping property is set to true, the groupingPattern property is used + to define the placement and pattern used for the grouping separator.

+ +

The grouping pattern is defined as a string containing numbers separated by semicolons and optionally may end + with an asterisk. For example: "3;2;*". Each number in the string represents the number of digits + in a group. The grouping separator is placed before each group of digits. An asterisk at the end of the string + indicates that groups with that number of digits should be repeated for the rest of the formatted string. + If there is no asterisk then there are no additional groups or separators for the rest of the formatted string.

+ +

The first number in the string corresponds to the first group of digits to the left of the decimal separator. + Subsequent numbers define the number of digits in subsequent groups to the left. Thus the string "3;2;*" + indicates that a grouping separator is placed after the first group of 3 digits, followed by groups of 2 digits. + For example: 98,76,54,321

+ +

The following table shows examples of formatting the number 123456789.12 with various grouping patterns. + The grouping separator is a comma and the decimal separator is a period. +

+ Grouping PatternSample Format3;*123,456,789.123;2;*12,34,56,789.123123456,789.12 + +

Only a limited number of grouping sizes can be defined. On some operating systems, grouping patterns can only contain + two numbers plus an asterisk. Other operating systems can support up to four numbers and an asterisk. + For patterns without an asterisk, some operating systems only support one number while others support up to three numbers. + If the maximum number of grouping pattern elements is exceeded, then additional elements + are ignored and the lastOperationStatus property is set as described below. +

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
groupingSeparatoruseGroupinglastOperationStatusLastOperationStatus
groupingSeparator + The character or string used for the grouping separator.Stringif this property is assigned a null value. + + TypeErrorTypeErrordependent on the locale and operating system. + + + The character or string used for the grouping separator. + +

The value of this property is used as the grouping separator when formatting numbers with the + useGrouping property set to true. This + property is initially set based on the locale that is selected when the formatter object + is constructed.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
formatInt()formatNumber()formatUInt()useGroupinglastOperationStatusLastOperationStatus
lastOperationStatus + The status of previous operation that this NumberFormatter object performed.String + The status of previous operation that this NumberFormatter object performed. + The lastOperationStatus property is set whenever the constructor or a method of + this class is called, or another property is set. For the possible values see the description for each method. + + LastOperationStatusleadingZero + Specifies whether a leading zero is included in a formatted number when there are no integer digits + to the left of the decimal separator.Booleanif this property is assigned a null value. + + TypeErrorTypeErrordependent on the locale and operating system. + + + Specifies whether a leading zero is included in a formatted number when there are no integer digits + to the left of the decimal separator. + +

When this property is set to true a leading zero is included to the left of the decimal separator + when formatting numeric values between -1.0 and 1.0. + When this property is set to false a leading zero is not included.

+ +

For example if the number is 0.321 and this property is set true, then the leading + zero is included in the formatted string. If the property is set to false, the leading zero + is not included. In that case the string would just include the decimal separator followed by the decimal digits, + like .321.

+ +

The following table shows examples of how numbers are formatted based on the values of this property and + the related fractionalDigits and trailingZeros properties. +

+ + trailingZerosleadingZerofractionalDigits0.120truetrue30.1200.000falsetrue30.120truefalse3.120.000falsefalse3.120 + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
formatInt()formatNumber()formatUInt()trailingZeroslastOperationStatusLastOperationStatus
negativeNumberFormat + A numeric value that indicates a formatting pattern for negative numbers.uintif the assigned value is not a number between 0 and 4. + + ArgumentErrorArgumentErrordependent on the locale and operating system. + + + A numeric value that indicates a formatting pattern for negative numbers. + This pattern defines the location of the negative symbol + or parentheses in relation to the numeric portion of the formatted number. + +

The following table summarizes the possible formats for negative numbers. When a negative number is formatted, + the minus sign in the format is replaced with the value of + the negativeSymbol property and the 'n' character is replaced with the formatted numeric value.

+ + Negative number format typeFormat0(n)1-n2- n3n-4n - + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
negativeSymbolformatInt()formatNumber()formatUInt()lastOperationStatusLastOperationStatus
negativeSymbol + The negative symbol to be used when formatting negative values.Stringif the system cannot allocate enough internal memory. + + MemoryErrorflash.errors:MemoryError + The negative symbol to be used when formatting negative values. + +

This symbol is used with the negative number + format when formatting a number that is less than zero. It is not used in negative number formats that do not include + a negative sign (e.g. when negative numbers are enclosed in parentheses).

+ +

This property is set to a default value for the actual locale selected when this + formatter is constructed. It can be set with a value to override the default setting.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
negativeNumberFormatformatInt()formatNumber()formatUInt()lastOperationStatusLastOperationStatus
requestedLocaleIDName + The name of the requested locale ID that was passed to the constructor of this NumberFormatter object.String + The name of the requested locale ID that was passed to the constructor of this NumberFormatter object. + +

If the LocaleID.DEFAULT value was used then the name returned is "i-default". + The actual locale used can differ from the requested locale when a fallback locale is applied. + The name of the actual locale can be retrieved using the actualLocaleIDName property. +

+ +
LocaleIDactualLocaleIDNameNumberFormatter()
trailingZeros + Specifies whether trailing zeros are included in a formatted number.Booleanif this property is assigned a null value. + + TypeErrorTypeErrordependent on the locale and operating system. + + + Specifies whether trailing zeros are included in a formatted number. + +

When this property is set to true, trailing zeros are included in the fractional part + of the formatted number up to the limit specified by the fractionalDigits property. + When this property is set to false then no trailing zeros are shown.

+ +

For example if the numeric value is 123.4, and this property is set true, and the fractionalDigits property + is set to 3, the formatted string would show trailing zeros, like 123.400 . + If this property is false, trailing zeros are not included, and the string shows just the decimal + separator followed by the non-zero decimal digits, like 123.4 .

+ +

The following table shows examples of how numeric values are formatted based on the values of this property and + the related fractionalDigits and leadingZero properties. +

+ + trailingZerosleadingZerofractionalDigits0.120truetrue30.1200.000falsetrue30.120truefalse3.120.000falsefalse3.120 + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
leadingZerolastOperationStatusLastOperationStatus
useGrouping + Enables the use of the grouping separator when formatting numbers.Boolean + Enables the use of the grouping separator when formatting numbers. + +

When the useGrouping property is set to true, digits are grouped and + delimited by the grouping separator character. + For example: 123,456,789.22

+ +

When the useGrouping property is set to false, digits are not grouped or separated. + For example: 123456789.22

+ +

The symbol to be used as a grouping separator is defined by the groupingSeparator property. The number of digits + between grouping separators is defined by the groupingPattern property.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
groupingPatterngroupingSeparatorlastOperationStatusLastOperationStatus
DateTimeNameContext + The DateTimeNameContext class enumerates constant values representing the formatting context in which a month name + or weekday name is used.Object + The DateTimeNameContext class enumerates constant values representing the formatting context in which a month name + or weekday name is used. These constants are used for the context parameters for the DateTimeFormatter's + getMonthNames() and getWeekDayNames() methods. + +

The context parameter only changes the results of those methods for certain locales and operating systems. + For most locales the lists of month names and weekday names do not differ by context.

+ +
DateTimeFormatter.getMonthNames()DateTimeFormatter.getWeekDayNames()FORMAT + Indicates that the date element name is used within a date format.formatString + Indicates that the date element name is used within a date format. + + STANDALONE + Indicates that the date element name is used in a "stand alone" context, independent of other formats.standaloneString + Indicates that the date element name is used in a "stand alone" context, independent of other formats. + For example, the name can be used to show only the month name in a calendar or the weekday name in a date chooser. + +
DateTimeNameStyle + The DateTimeNameStyle class enumerates constants that control the length of the month names and weekday names + that are used when formatting dates.Object + The DateTimeNameStyle class enumerates constants that control the length of the month names and weekday names + that are used when formatting dates. Use these constants for the nameStyle parameter + of the DateTimeFormatter getMonthNames() and getWeekDayNames() methods. + +

The LONG_ABBREVIATION and SHORT_ABBREVIATION may be the same or + different depending on the operating system settings.

+ +
DateTimeFormatterFULL + Specifies the full form or full name style for month names and weekday names.fullString + Specifies the full form or full name style for month names and weekday names. + + Examples: Tuesday, November. + + LONG_ABBREVIATION + Specifies the long abbreviation style for month names and weekday names.longAbbreviationString + Specifies the long abbreviation style for month names and weekday names. + + Examples: Tues for Tuesday, Nov for November. + + SHORT_ABBREVIATION + Specifies the short abbreviation style for month names and weekday names.shortAbbreviationString + Specifies the short abbreviation style for month names and weekday names. + + Examples: T for Tuesday, N for November. + +
CurrencyFormatter + The CurrencyFormatter class provides locale-sensitive formatting and parsing of currency values.Object + The CurrencyFormatter class provides locale-sensitive formatting and parsing of currency values. + +

The CurrencyFormatter class uses the data and functionality provided by the operating system + and is designed to format currency values according to the conventions + of a specific locale and type of currency. The position of the currency symbol, + the negative symbol, the decimal separator, the grouping separator, the grouping pattern + decimal separator, and other elements can vary depending on the locale.

+ +

If the operating system supports the requested locale, the properties and + currency type are set according to the conventions and defaults of the requested locale. + If the requested locale is not available, then the properties are set according to + a fallback or default system locale, which can be retrieved using the actualLocaleIDName property. +

+

+ Due to the use of the user's settings, the use of formatting patterns + provided by the operating system, and the use of a fallback locale when a requested locale is not supported, + different users can see different formatting results, even when using the same locale ID. +

+ +
The following shows how a currency amount is formatted + differently based on different locales and currencies. + + The results from this example will differ based on your operating system and user preferences. +

+ This example uses the following locales: +

+
  • The default operating system locale for currency formatting (LocaleID.DEFAULT)
  • Japanese (Japan)
  • English (US)
  • French (France)
+ +

The example does the following for each locale in the list:

+
  1. Creates a CurrencyFormatter object
  2. Uses the formattingWithCurrencySymbolIsSafe() method to check whether the default currency for the locale is Euros ("EUR") + and if so it formats the string using the currency symbol. Otherwise it formats the string using the ISO code. +
+ + +package { + import flash.display.Sprite; + import flash.globalization.CurrencyFormatter; + import flash.globalization.LocaleID; + + public class CurrencyFormatterExample1 extends Sprite + { + public function CurrencyFormatterExample1():void + { + var cf:CurrencyFormatter; + var amountWithSymbol:String; + var amountWithISOCode:String + + var localeNames:Array = [LocaleID.DEFAULT, "ja-JP", "en-US", "fr-FR"]; + + for each (var localeName:String in localeNames) + { + cf = new CurrencyFormatter(localeName); + + trace('\n' + "LocaleID requested=" + cf.requestedLocaleIDName + + "; actual=" + cf.actualLocaleIDName); + + trace("Last Operation Status: " + cf.lastOperationStatus ); + + trace("Currency ISO Code: " + cf.currencyISOCode); + + if (cf.formattingWithCurrencySymbolIsSafe("EUR")) + { + amountWithSymbol = cf.format(123456789.19, true); + trace("Format using Symbol: "+ amountWithSymbol); + } + else + { + amountWithISOCode = cf.format(123456789.19); + trace("Format using ISO Code: " + amountWithISOCode); + } + } + } + } +} +
The following example parses a currency amount using the rules for a given locale. + The results from this example may differ based on your operating system and user preferences. +

This example takes the following steps:

+
  1. Creates a CurrencyFormatter object for the English (US) locale.
  2. Uses the parse() method to parse the input string.
  3. Displays the amount and currency string values from the resulting CurrencyParseResult object.
+ + +package { + import flash.display.Sprite; + import flash.globalization.CurrencyFormatter; + import flash.globalization.CurrencyParseResult; + import flash.globalization.LastOperationStatus; + import flash.globalization.LocaleID; + + public class CurrencyFormatterParseExample extends Sprite + { + public function CurrencyFormatterParseExample() + { + var cf:CurrencyFormatter = new CurrencyFormatter( "en_US" ); + + trace("LocaleID requested=" + cf.requestedLocaleIDName + + "; actual=" + cf.actualLocaleIDName); + trace("Last Operation Status: " + cf.lastOperationStatus ); + + var inputString:String = "Dollar 123,567,89,0.254"; + + var result:CurrencyParseResult = cf.parse(inputString); + + if (cf.lastOperationStatus == LastOperationStatus.NO_ERROR ) { + trace("Amount value: " + result.value); + trace("Currency string: " + result.currencyString); + } + } + } +} +
CurrencyFormatter + Constructs a new CurrencyFormatter object to format numbers representing currency amounts according to + the conventions of a given locale.if the requestedLocaleIDName parameter is null. + + TypeErrorTypeErrorrequestedLocaleIDNameStringThe preferred locale ID name to use when determining date or time formats. + + + Constructs a new CurrencyFormatter object to format numbers representing currency amounts according to + the conventions of a given locale. + +

This constructor determines if the current operating system supports the requested locale ID name. + If it is not supported then a fallback locale is used instead. + If a fallback locale is used then the lastOperationStatus property + indicates the type of fallback, and the actualLocaleIDName property contains + the name of the fallback locale ID.

+ +

Certain properties such as the currencySymbol and currencyISOCode properties are set + automatically based on the locale.

+ +

NOTE: When a fallback locale is used the currency properties are set to default values, + and therefore the currencySymbol or + currencyISOCode properties might be given unexpected values. It is a good idea to examine the + currencySymbol and currencyISOCode property values before formatting a currency amount. +

+ +

To format based on the user's current operating system preferences, pass the value LocaleID.DEFAULT + in the requestedLocaleIDName parameter to the constructor. +

+ +

When the constructor is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

When the requested locale ID name is not available then the lastOperationStatus + is set to one of the following:

+
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+

Otherwise the lastOperationStatus property is set to one of the constants defined in + the LastOperationStatus class.

+ +

For details on the warnings listed above and other possible values of the + lastOperationStatus property, see the descriptions in the LastOperationStatus class.

+ +
lastOperationStatusrequestedLocaleIDNameactualLocaleIDNameLastOperationStatusLocaleID
format + Creates a string representing a currency amount formatted according to the current properties of this CurrencyFormatter object, + including the locale, currency symbol, and currency ISO code.A string containing the formatted currency value. + + StringvalueNumberThe numeric value to be formatted into a currency string. + withCurrencySymbolBooleanfalseWhen set to false the currencyISOCode property determines which + currency string or symbol to use in the output string. When set to true, the current value of the + currencySymbol property is used in the output string. + + + + Creates a string representing a currency amount formatted according to the current properties of this CurrencyFormatter object, + including the locale, currency symbol, and currency ISO code. + +

By default this method uses the currencyISOCode property to determine the currency symbol and other + settings used when formatting.

+ +

Many countries and regions use the same currency symbols for different currencies. + For example the United States, Australia, New Zealand, Canada, + and Mexico all use the same dollar sign symbol ($) for local currency values. When the formatting currency differs + from the user's local currency it is best to use the ISO code as the currency string. + You can use the formattingWithCurrencySymbolIsSafe() method to test whether the ISO code of the + currency to be formatted matches the currencyISOCode property of the formatter. +

+ +

This method can format numbers of very large and very small magnitudes. However the + number of significant digits is limited to the precision provided by the Number data type. +

+ +
In this example the requested locale is fr-CA French (Canada). The example + assumes that this locale is supported in the user's operating system and therefore no fallback locale is used. + For fr-CA the default currency is Canadian dollars with an ISO code of CAD. Therefore when + formatting a currency with the default values, CAD is used as the currency symbol. When + the withCurrencySymbol parameter is set to true the currencySymbol + property is used to format the currency amount. + + + var cf:CurrencyFormatter = new CurrencyFormatter("fr-CA"); + + trace(cf.actualLocaleIDName); // "fr-CA" + trace(cf.currencyISOCode); // "CAD" + trace(cf.currencySymbol); // "$" + + trace(cf.format(1254.56)); // "1 254,56 CAD" + trace(cf.format(1254.56, true)); // "1 254,56 $" + + +

The second example shows a method of formatting a currency amount in Canadian dollars using the default user's locale. + The formattingWithCurrencySymbolIsSafe() method is used to test to see if the user's default currency is + Canadian dollars and if so then the format method is used with the withCurrencySymbol parameter set to true. Otherwise + the currency is set to Canadian dollars with a more descriptive currency symbol. + The example shows how the currency would be formatted if the default locale was either + French (Canada) or English (USA).

+ + + var cf:CurrencyFormatter = new CurrencyFormatter(LocaleID.DEFAULT); + + if (cf.formattingWithCurrencySymbolIsSafe("CAD")) { + trace(cf.actualLocaleIDName); // "fr-CA French (Canada)" + trace(cf.format(1254.56, false)); // "1 254,56 $" + } + else { + trace(cf.actualLocaleIDName); // "en-US English (USA)" + cf.setCurrency("CAD", "C$") + trace(cf.format(1254.56, true)); // "C$ 1,254.56" + } + + +
currencySymbolcurrencyISOCodeformattingWithCurrencySymbolIsSafe()lastOperationStatusLastOperationStatus
formattingWithCurrencySymbolIsSafe + Determines whether the currently specified currency symbol can be used when formatting currency amounts.if the requestedISOCode parameter is null. + + TypeErrorTypeErrortrue if the currencyISOCode property matches the requestedISOCode parameter; + otherwise false. + + BooleanrequestedISOCodeStringA three letter ISO 4217 currency code (for example, USD for US dollars, EUR for Euros). + Must contain three uppercase letters from A to Z. + + + Determines whether the currently specified currency symbol can be used when formatting currency amounts. + +

Many regions and countries use the same currency symbols. This method can be used to + safeguard against the use of an ambiguous currency symbol, or a currency symbol or ISO code that + is different than expected due to the use of a fallback locale.

+ +

A common use case for this method is to determine whether to show a local currency symbol (if the amount is formatted in + the user's default currency), or a more specific ISO code string (if the amount is formatted in a currency + different from the user's default).

+ +

This method compares the requestedISOCode parameter against the current currencyISOCode property, + returning true if the strings are equal and false if they are not. + When the strings are equal, using the format() method with the + withCurrencySymbol parameter set to true results in a formatted currency value string + with a unique currency symbol for the locale. + If this method returns false, then using the format() method with the withCurrencySymbol + parameter set to true could result in the use of an ambiguous or incorrect currency symbol. +

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
currencySymbolcurrencyISOCodelastOperationStatusLastOperationStatus
getAvailableLocaleIDNames + Lists all of the locale ID names supported by this class.A vector of strings containing all of the locale ID names supported by this class. + + + Lists all of the locale ID names supported by this class. + +

If this class is not supported on the current operating system, this method returns a null value.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
parse + Parses a string into a currency amount and a currency symbol.if the inputString parameter is null. + + TypeErrorTypeErrorA CurrencyParseResult object containing the numeric value and the currency symbol or string. + + flash.globalization:CurrencyParseResultinputStringStringThe input string to parse. + + + Parses a string into a currency amount and a currency symbol. + +

The parsing algorithm uses the value of the decimalSeparator property to determine the integral and fractional + portion of the number. It uses the values of the negativeCurrencyFormat and positiveCurrencyFormat + properties to determine the location of the currency symbol or string relative to the currency amount. + For negative amounts the value of the negativeCurrencyFormat property determines the location of the + negative symbol and whether parentheses are used.

+ +

If the order of the currency symbol, minus sign, and number in the input string does not match the pattern identified by the + negativeCurrencyFormat and positiveCurrencyFormat properties, then:

+ +
  1. The value property of the returned CurrencyParseResult object is set to NaN.
  2. The currencyString property of the returned CurrencyParseResult object is set to null.
  3. The lastOperationStatus property is set to indicate that parsing failed.
+ +

The input string may include space characters, which are ignored during the parsing.

+ +

Parsing can succeed even if there is no currency symbol. No validation is done of the portion of the string + corresponding to the currency symbol. If there is no currency symbol or string, the currencyString property in the + returned CurrencyParseResult object is set to an empty string.

+ +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
decimalSeparatornegativeCurrencyFormatpositiveCurrencyFormatCurrencyParseResultlastOperationStatusLastOperationStatus
setCurrency + Sets the currencyISOCode and currencySymbol properties of the CurrencyFormatter object.if the currencyISOCode or currencySymbol parameter is null. + + TypeErrorTypeErrordependent on the actual locale and operating system + + currencyISOCodeStringThe three letter ISO 4217 currency code (for example, USD for US dollars, EUR for Euros). + Must contain three uppercase letters from A to Z. + currencySymbolString The currency symbol or string to be used when formatting currency values. This can be an empty string. + + + Sets the currencyISOCode and currencySymbol properties of the CurrencyFormatter object. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the the currencyISOCode and the currencySymbol properties are not modified and the + lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
currencyISOCodecurrencySymbollastOperationStatusLastOperationStatus
actualLocaleIDName + The name of the actual locale ID used by this CurrencyFormatter object.String + The name of the actual locale ID used by this CurrencyFormatter object. + +

There are three possibilities for the value of the name, depending on operating system and the + value of the requestedLocaleIDName parameter passed to the CurrencyFormatter() constructor.

+
  1. If the requested locale was not LocaleID.DEFAULT and + the operating system provides support for the requested locale, + then the name returned is the same as the requestedLocaleIDName property. +
  2. If LocaleID.DEFAULT was used as the value for the requestedLocaleIDName + parameter to the constructor, then the name of the current locale specified by the user's operating system + is used. The LocaleID.DEFAULT value preserves user's customized setting in the OS. + Passing an explicit value as the requestedLocaleIDName parameter does not necessarily give the + same result as using the LocaleID.DEFAULT even if the two locale ID names are the same. + The user might have customized the locale settings on their machine, and by requesting an + explicit locale ID name rather than using LocaleID.DEFAULT your application would not + retrieve those customized settings. +
    +

    For example:

    + + + var fmt:CurrencyFormatter = new CurrencyFormatter(LocaleID.DEFAULT); + var aliName:String = fmt.actualLocaleIDName; + + +

    In the above example, aliName is the name of the locale corresponding to + the user's current operating systems settings (for example, "it-IT" if the user's locale is set to Italian-Italy), + and not "i-default" (the name of the LocaleID.DEFAULT locale).

    +
  3. If the system does not support the requestedLocaleIDName specified in the constructor + then a fallback locale ID name is provided. +
    +

    For Example:

    + + + var fmt:CurrencyFormatter = new CurrencyFormatter("fr-CA"); + var aliName:String = fmt.actualLocaleIDName; + + +

    Assuming that the operating system in the example above does not support the "fr-CA" (French-Canada) locale ID, + a fallback is used. In this case the fallback locale ID is "fr-FR" (French-France).

    +
+ +
LocaleIDrequestedLocaleIDNameCurrencyFormatter()
currencyISOCode + The three letter ISO 4217 currency code for the actual locale being used.Stringdependent on the actual locale and operating system + + + The three letter ISO 4217 currency code for the actual locale being used. + +

This code is used to determine the currency symbol or string when formatting currency amounts + using the format() method with the withCurrencySymbol parameter set to false.

+ +

This property is initialized by the constructor based on the actual locale that is used. When a fallback + locale is used this property reflects the preferred, default currency code for the fallback locale.

+ +
format()setCurrency()currencySymbol
currencySymbol + The currency symbol or string for the actual locale being used.Stringdependent on the actual locale and operating system + + + The currency symbol or string for the actual locale being used. + +

This property is used as the currency symbol when formatting currency amounts + using the format() method with the withCurrencySymbol parameter set to true.

+ +

This property is initialized by the constructor based on the actual locale that is used. When a fallback + locale is used this property reflects the preferred, default currency symbol for the fallback locale.

+ +
format()setCurrency()formattingWithCurrencySymbolIsSafe()currencyISOCode
decimalSeparator + The decimal separator character used for formatting or parsing currency amounts that have a decimal part.Stringif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + The decimal separator character used for formatting or parsing currency amounts that have a decimal part. + +

This property is initially set based on the locale that is selected when the formatter object + is constructed.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
format()lastOperationStatusLastOperationStatus
digitsType + Defines the set of digit characters used when formatting currency amounts.uintif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + Defines the set of digit characters used when formatting currency amounts. + +

Different languages and regions use different sets of characters to represent the + digits 0 through 9. This property defines the set of digits to be used.

+ +

The value of this property represents the Unicode value for the zero digit of a decimal digit set. + The valid values for this property are defined in the NationalDigitsType class.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
lastOperationStatusLastOperationStatusNationalDigitsType
fractionalDigits + The maximum number of digits that can appear after the decimal separator.int0 + + + The maximum number of digits that can appear after the decimal separator. + +

Numbers are rounded to the number of digits specified by this property. The rounding scheme + varies depending on the user's operating system.

+ +

When the trailingZeros property is set to true, the fractional portion of the + number (after the decimal point) is padded with trailing zeros until its length matches the value of this + fractionalDigits property.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
trailingZeroslastOperationStatusLastOperationStatus
groupingPattern + Describes the placement of grouping separators within the formatted currency amount string.Stringif this property is assigned a null value. + + TypeErrorTypeError + Describes the placement of grouping separators within the formatted currency amount string. + +

When the useGrouping property is set to true, the groupingPattern property is used + to define the placement and pattern used for the grouping separator.

+ +

The grouping pattern is defined as a string containing numbers separated by semicolons and optionally may end + with an asterisk. For example: "3;2;*". Each number in the string represents the number of digits + in a group. The grouping separator is placed before each group of digits. An asterisk at the end of the string + indicates that groups with that number of digits should be repeated for the rest of the formatted string. + If there is no asterisk then there are no additional groups or separators for the rest of the formatted string.

+ +

The first number in the string corresponds to the first group of digits to the left of the decimal separator. + Subsequent numbers define the number of digits in subsequent groups to the left. Thus the string "3;2;*" + indicates that a grouping separator is placed after the first group of 3 digits, followed by groups of 2 digits. + For example: 98,76,54,321

+ +

The following table shows examples of formatting the currency amount 123456789.12 with various grouping patterns. + The grouping separator is a comma, the decimal separator is a period, and a dollar sign ($) is the currency symbol. +

+ Grouping PatternSample Format3;* $123,456,789.123;2;*$12,34,56,789.123$123456,789.12 + +

Only a limited number of grouping sizes can be defined. On some operating systems, grouping patterns can only contain + two numbers plus an asterisk. Other operating systems can support up to four numbers and an asterisk. + For patterns without an asterisk, some operating systems only support one number while others support up to three numbers. + If the maximum number of grouping pattern elements is exceeded, then additional elements + are ignored, and the lastOperationStatus property is set as described below. +

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
groupingSeparatoruseGroupinglastOperationStatusLastOperationStatus
groupingSeparator + The character or string used for the grouping separator.Stringif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + The character or string used for the grouping separator. + +

The value of this property is used as the grouping separator when formatting currency amounts when the + useGrouping property is set to true. This + property is initially set based on the locale that is selected when the formatter object + is constructed.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
format()useGroupinglastOperationStatusLastOperationStatus
lastOperationStatus + The status of the most recent operation that this CurrencyFormatter object performed.String + The status of the most recent operation that this CurrencyFormatter object performed. + The lastOperationStatus property is set whenever the constructor or a method of + this class is called or another property is set. For the possible values see the description for each method. + + LastOperationStatusleadingZero + Specifies whether a leading zero is included in a formatted currency amount when there are no integer digits + to the left of the decimal separator.Booleanif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + Specifies whether a leading zero is included in a formatted currency amount when there are no integer digits + to the left of the decimal separator. + +

When this property is set to true a leading zero is included to the left of the decimal separator + when formatting numeric values between -1.0 and 1.0. + When this property is set to false a leading zero is not included.

+ +

For example if the currency amount is 0.321 and this property is set true, then the leading + zero is included in the formatted string. If the property is set to false, the leading zero + is not included. In that case the string would just include the decimal separator followed by the decimal digits, + like $.321.

+ +

The following table shows examples of how currency amounts are formatted based on the values of this property and + the related fractionalDigits and trailingZeros properties. +

+ trailingZerosleadingZerofractionalDigits0.120truetrue3$0.120$0.000falsetrue3$0.12$0truefalse3$.120$.000falsefalse3$.12$0 + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
format()lastOperationStatusLastOperationStatustrailingZeros
negativeCurrencyFormat + A numeric value that indicates a formatting pattern for negative currency amounts.uintif the assigned value is not between 0 and 15. + + ArgumentErrorArgumentErrordependent on the actual locale and operating system + + + A numeric value that indicates a formatting pattern for negative currency amounts. + This pattern defines the location of the currency symbol and the negative symbol + or parentheses in relation to the numeric portion of the currency amount. + +

The value of this property must be one of the constants defined in the table below. +

+ +

The table below summarizes the possible formatting patterns for negative currency amounts. + When a currency amount is formatted with the format() method:

+ +
  • The '¤' symbol is replaced with the value of the currencyISOCode or + the currencySymbol property, depending on the value of the withCurrencySymbol parameter + passed to the format() method;
  • The '-' character is replaced with the value of the negativeNumberSymbol property;
  • The 'n' character is replaced with the currency amount value that is passed to the format() method.
+ + Negative currency format typeFormatting pattern0(¤n)1-¤n2¤-n3¤n-4(n¤)5-n¤6n-¤7n¤-8-n ¤9-¤ n10n ¤-11¤ n-12¤ -n13n- ¤14(¤ n)15(n ¤) + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
format()currencySymbolnegativeSymbollastOperationStatusLastOperationStatus
negativeSymbol + The negative symbol used when formatting negative currency amounts.Stringif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + The negative symbol used when formatting negative currency amounts. + +

This symbol is used with the negative currency + format when formatting a currency amount that is less than zero. It is not used in negative currency formats that do not include + a negative sign (for example, when negative currency amounts are enclosed in parentheses).

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
format()negativeCurrencyFormatlastOperationStatusLastOperationStatus
positiveCurrencyFormat + A numeric value that indicates a formatting pattern for positive currency amounts.uintif the assigned value is not between 0 and 3. + + ArgumentErrorArgumentErrordependent on the actual locale and operating system + + + A numeric value that indicates a formatting pattern for positive currency amounts. + This format defines the location of currency symbol + relative to the numeric portion of the currency amount. + +

The value of this property must be one of the constants defined in the table below. +

+ +

The table below summarizes the possible formatting patterns for positive currency amounts. + When a currency amount is formatted with the format() method:

+ +
  • The '¤' symbol is replaced with the value of the currencyISOCode or + the currencySymbol property, depending on the value of the withCurrencySymbol parameter + passed to the format() method;
  • The 'n' character is replaced with the currency amount value that is passed to the format() method.
+ + Positive currency format typeFormatting pattern0¤n12¤ n3n ¤ + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
currencySymbolformat()lastOperationStatusLastOperationStatus
requestedLocaleIDName + The name of the requested locale ID that was passed to the constructor of this CurrencyFormatter object.String + The name of the requested locale ID that was passed to the constructor of this CurrencyFormatter object. + +

If the LocaleID.DEFAULT value was used then the name returned is "i-default". + The actual locale used can differ from the requested locale when a fallback locale is applied. + The name of the actual locale can be retrieved using the actualLocaleIDName property. +

+ +
LocaleIDactualLocaleIDNameCurrencyFormatter()
trailingZeros + Specifies whether trailing zeros are included in the formatted currency amount.Booleanif this property is assigned a null value. + + TypeErrorTypeErrordependent on the actual locale and operating system + + + Specifies whether trailing zeros are included in the formatted currency amount. + +

When this property is set to true, trailing zeros are included in the fractional part + of the formatted number up the limit specified by the fractionalDigits property. + When this property is set to false then no trailing zeros are shown.

+ +

For example if the currency amount is 123.4, and this property is set true, and the fractionalDigits property + is set to 3, the formatted string would show trailing zeros, like $123.400 . + If this property is false, trailing zeros are not included, and the string shows just the decimal + separator followed by the non-zero decimal digits, like $123.4 .

+ +

The following table shows examples of how currency amounts are formatted based on the values of this property and + the related fractionalDigits and leadingZero properties. +

+ trailingZerosleadingZerofractionalDigits0.120truetrue3$0.120$0.000falsetrue3$0.12$0truefalse3$.120$.000falsefalse3$.12$0 + +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
leadingZerolastOperationStatusLastOperationStatus
useGrouping + Enables the use of the grouping separator when formatting currency amounts.Boolean + Enables the use of the grouping separator when formatting currency amounts. + +

When the useGrouping property is set to true, digits are grouped and + delimited by the grouping separator character. + For example: $123,456,789

+ +

When the useGrouping property is set to false, digits are not grouped or separated. + For example: $123456789

+ +

The groupingSeparator property defines the symbol to be used as a grouping separator. The + groupingPattern property defines the number of digits between grouping separators.

+ +

When this property is assigned a value and there are no errors or warnings, the lastOperationStatus property + is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the + LastOperationStatus class.

+ +
groupingPatterngroupingSeparatorlastOperationStatusLastOperationStatus
Collator + The Collator class provides locale-sensitive string comparison capabilities.Object + The Collator class provides locale-sensitive string comparison capabilities. + +

This class uses the string comparison services provided by the operating system. + The comparisons differ according to the locale identifier that is provided when the class instance is created. + ActionScript stores strings using the Unicode character set. The Boolean string comparison + operators (==, !=, <, <=, >, >=) use Unicode code points for comparison. In most cases the resulting + sort order doesn't match the conventions of a particular language and region, and thus + should not be used to sort strings that are presented in a user interface. In contrast the comparison methods in this class + provide an order that adheres to these conventions. +

+

Here are some examples where the sort order differs depending on the language: +

+
  • In English, lowercase a is before uppercase A and uppercase A is before lowercase b.
  • ö is after z in Swedish, whereas in German ö is after o
  • ch is sorted as one character between c-d in traditional Spanish
  • accented characters in French are sorted according to the last accent difference instead of the first accent + difference: for example, cote < côte < coté < côté instead of cote < coté < côte < côté
+

+ Sort orders can even differ within the same language and region depending on the usage. For example, in German there + is a different sort order used for names in a phone book versus words in a dictionary. In Chinese and Japanese + there are different ways of sorting the ideographic characters: by pronunciation or by the ideographic radical and the + number of strokes uses in the glyph. In Spanish and Georgian, there is a difference between modern and traditional sorting. +

+

+ The comparison methods in this class provide two main usage modes. The initialMode + parameter of the Collator() constructor controls these modes. The default "sorting" mode is for sorting items that are displayed to an end user. + In this mode, comparison is more strict to ensure that items that are otherwise the same are sorted in a + consistent manner. For example, uppercase letters and lowercase letters do not compare as equal. + In the "matching" mode the comparison is more lenient. For example in this mode uppercase and + lowercase letters are treated equally. Here's an example that demonstrates both of these modes: +

+ + var sortingCollator:Collator = new Collator("en-US", CollatorMode.SORTING); + var words:Array = new Array("Airplane" , "airplane", "boat", "Boat"); + words.sort(sortingCollator.compare); + trace(words); + + var matchingCollator:Collator = new Collator("en-US", CollatorMode.MATCHING); + if (matchingCollator.equals("Car", "car")) { + trace("The words match!"); + } + +

+ Even when providing a locale ID parameter to the constructor as shown above, collation behavior can differ by user + based on the user's operating system settings and whether a fallback locale is used when the + requested locale is not supported. +

+ +
The following example shows sorting results that differ based on the locale. + + The example takes the following steps: +
  1. Iterates through an array of locale ID names, including the default locale ID for the operating system + (as specified by LocaleID.DEFAULT)
  2. Creates a Collator object for each locale ID name using "sorting" mode (the default).
  3. Displays the requested and actual locale ID names and the value of the lastOperationStatus property + so you can see if a fallback locale was used.
  4. Sorts a data array using each collator and displays the results. The resulting order is different for each locale.
+ + +package { + import flash.globalization.Collator; + import flash.globalization.LocaleID; + + public class CollatorExample1 + { + public var col:Collator; + + public function CollatorExample1():void + { + var localeNames:Array = [LocaleID.DEFAULT, + "de-DE", "sv-SE", + "fr-FR", "lt-LT", + "es-ES"]; + + var testSortData:Array = [ + "y ", "i ", "k ", // Latvian + "acxa ", "acha ", "adxa ", // es_traditional + "n ", "ö ", "o ", "z ", "vu ", "wo ", // sw + "däd ", "daed ", // de + "öf ", "of ", // de_dictionary + "côte ", "coté " // fr + ]; + + for each (var localeName:String in localeNames) { + + col = new Collator(localeName); + + trace("LocaleID requested: " + col.requestedLocaleIDName + + "; actual: " + col.actualLocaleIDName); + + trace("Last Operation Status: " + col.lastOperationStatus ); + + var result:Array = testSortData.sort(col.compare); + + trace ("sorted data: " + result); + } + } + } +} +
The following examples shows uses a Collator object to control the behavior of string comparisons. + + The example takes the following steps: +
  1. Creates a Collator object for the user's default locale using "matching" mode.
  2. Alternately sets the Collator.ignoreDiacritics property to false and true
  3. Compares sets of strings that contain diacritics and upper case and lower case characters.
  4. Shows how the comparisons change when the + Collator.ignoreDiacritics and Collator.ignoreCase properties change.
+ + +package { + import flash.display.Sprite; + import flash.globalization.Collator; + import flash.globalization.CollatorMode; + import flash.globalization.LocaleID; + + public class CollatorExample2 extends Sprite + { + public var col:Collator; + public var testMatchData:Array = ["cote", "Cote", "côte", "coté"]; + public var wordToMatch:String = "Cote"; + + public function CollatorExample2() + { + col = new Collator( LocaleID.DEFAULT, CollatorMode.MATCHING ); + + trace("LocaleID requested: " + col.requestedLocaleIDName + + "; actual: " + col.actualLocaleIDName); + + trace("Last Operation Status: " + col.lastOperationStatus ); + + trace('\n' + "ignoreCase = " + col.ignoreCase); + trace("ignoreDiacritics = " + col.ignoreDiacritics); + + compareString(testMatchData, wordToMatch) // All variations of the word cote match + + col.ignoreDiacritics = false; + trace('\n' + "ignoreDiacritics = false"); + + compareString(testMatchData, wordToMatch) // Variations with different diacritics will not match + + col.ignoreCase = false; + trace('\n' + "ignoreCase = false"); + + compareString(testMatchData, wordToMatch) // Variations with different case will not match + } + + private function compareString(stringArray:Array, keyword:String):void + { + for each(var s:String in stringArray) + { + if(col.equals(s, keyword)) + { + trace(keyword + " = " + s); + } + } + } + } +} +
Collator + Constructs a new Collator object to provide string comparisons according to the conventions of a specified locale.when the requestedLocaleIDName parameter is null. + TypeErrorTypeErrorwhen the requestedLocaleIDName parameter contains an invalid value. + + ArgumentErrorArgumentErrorrequestedLocaleIDNameStringString to be used by this Collator object. + initialModeStringsortingA string value to specify the initial collation mode. The default value is + CollatorMode.SORTING. See the CollatorMode class + for a list of available modes. + + + Constructs a new Collator object to provide string comparisons according to the conventions of a specified locale. +

+ If the current operating system does not support the locale ID that is passed in the requestedLocaleIDName + parameter, then a fallback locale is determined. + If a fallback is used then the lastOperationStatus property is set to indicate the type of fallback. +

+

+ The initialMode parameter sets various collation options for general uses. + It can be set to one of the following values: +

+
  • CollatorMode.SORTING: sets collation options for general linguistic sorting usages such as + sorting a list of text strings that are displayed to an end user. + In this mode, differences in uppercase and lowercase letters, accented characters, and other differences + specific to the locale are considered when doing string comparisons.
  • CollatorMode.MATCHING: sets collation options for general usages such as + determining if two strings are equivalent. In this mode, differences in uppercase and lower + case letters, accented characters, and so on are ignored when doing string comparisons.
+

+ Here is an example of a sorted list created using a Collator with the locale ID "en-US" (English in US) + and the CollatorMode.SORTING option: +

+ AaÄäAEaeÆæBbCcç +

+ As shown above, all characters are treated as if they have different values, but in linguistic order. +

+ Here is an example of a sorted list created using Collator with the locale ID "en-US" (English in US) and the CollatorMode.MATCHING option: +

+ A a Ä ä A aAE ae Æ æB b B bC c ç C c +

Legend: Characters in a same row are treated as equivalent characters during comparison/sorting. For example, "a" (U+0040 = LATIN SMALL LETTER A) and "Ä" (U+00C4 = LATIN CAPITAL LETTER A WITH DIAERESIS) are considered to be equal. +

+ As shown above, some characters are in linguistic order and are treated as if they have the same character value. +

+ For finer control over sorting order, you can change collator properties such as + Collator.ignoreCase or Collator.ignoreDiacritics. +

+ For reference, here is a corresponding sorting example done using the standard Array.sort(), + which is not locale-aware: +

+ AAEBCaaebcÄÆäæç +

+ As you can see above, all characters are sorted simply in Unicode numeric value order. + It does not make much sense linguistically. +

+ To use the user's current operating system preferences, pass the static value LocaleID.DEFAULT + in the requestedLocaleIDName parameter to the constructor. +

+ Some locales have several sort order variants. For example, in German + one sort order is used for phone books and another sort order is used for dictionaries. + In Chinese, words are commonly supported by transliteration of the characters + into the pinyin. These different sort orders can be selected by including the "collation" keyword + in the string that is passed in the requestedLocaleIDName parameter to the constructor. +

+ + + var germanPhonebook:LocaleID = new LocaleID("de-DE@collation=phonebook"); + var chinesePinyin:LocaleID = new LocaleID("zh-Hant@collation=pinyin"); + + +

+ Possible values for the collation string are as follows, with the affected + languages shown in parentheses: +

+ + Collation stringDescriptionstandardThe default ordering for each language. phonebookFor a phonebook-style ordering (used in German).pinyinPinyin ordering for Latin and for CJK characters; that is, an ordering for + CJK characters based on a character-by-character transliteration into a pinyin. (used in Chinese)traditionalFor a traditional-style sort (used in Spanish) strokePinyin ordering for Latin, stroke order for CJK characters (used in Chinese)direct(used in Hindi) big5hanPinyin ordering for Latin, big5 character set ordering for CJK characters. (used in Chinese) gb2312han Pinyin ordering for Latin, gb2312han character set ordering for CJK characters. + (used in Chinese) unihanPinyin ordering for Latin, Unihan radical-stroke ordering for CJK characters. (used in Chinese) + +

+ If the host platform does not support the requested collation type, then a fallback is used + and the lastOperationStatus property is set to indicate that a fallback was selected. + You can use the actualLocaleIDName property to determine the value that was used as a fallback, + as shown in the following example: +

+ + var collator:Collator = new Collator("fr-FR"); + if (collator.lastOperationStatus == LastOperationStatus.USING_FALLBACK_WARNING) + { + trace ("Using fallback locale: " + collator.actualLocaleIDName); + } + + +

When the constructor completes successfully, then + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

When the requested locale ID is not available, then the lastOperationStatus property is set to one of the following:

+
  • LastOperationStatus.USING_FALLBACK_WARNING
  • LastOperationStatus.USING_DEFAULT_WARNING
+

Otherwise the lastOperationStatus property is set to one of the constants defined in the LastOperationStatus class.

+ +

For details on the warnings listed above and other possible values of lastOperationStatus, see + the descriptions in the LastOperationStatus class.

+ +
CollatorModeLastOperationStatusLocaleIDlastOperationStatusrequestedLocaleIDNameactualLocaleIDName
compare + Compares two strings and returns an integer value indicating whether the first string is + less than, equal to, or greater than the second string.when a required parameter is null. + TypeErrorTypeErrorwhen a parameter contains an invalid value. + + ArgumentErrorArgumentErrorAn integer value indicating whether the first string is + less than, equal to, or greater than the second string. +
  • If the return value is negative, string1 is less than string2.
  • If the return value is zero, string1 is equal to string2.
  • If the return value is positive, string1 is larger than string2.
+ +
int
string1StringFirst comparison string. + string2StringSecond comparison string. +
+ Compares two strings and returns an integer value indicating whether the first string is + less than, equal to, or greater than the second string. The comparison + uses the sort order rules for the locale ID that was specified in the Collator() constructor. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
equals()lastOperationStatusLastOperationStatus
equals + Compares two strings and returns a Boolean value indicating whether the strings are equal.when a required parameter is null. + TypeErrorTypeErrorwhen a parameter contains an invalid value. + + ArgumentErrorArgumentErrorA Boolean value indicating whether the strings are equal (true) or unequal (false). + + Booleanstring1StringFirst comparison string. + string2StringSecond comparison string. + + Compares two strings and returns a Boolean value indicating whether the strings are equal. + The comparison uses the sort order rules for the locale ID that was specified in the Collator() constructor. + +

When this method is called and it completes successfully, the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
compare()lastOperationStatusLastOperationStatus
getAvailableLocaleIDNames + Lists all of the locale ID names supported by this class.A vector of strings containing all of the locale ID names supported by this class. + + + Lists all of the locale ID names supported by this class. + +

If this class is not supported at all on the current operating system, this method returns a null value.

+ +
actualLocaleIDName + The name of the actual locale ID used by this Collator object.String + The name of the actual locale ID used by this Collator object. + +

There are three possibilities for the value of the name, depending on operating system and the + value of the requestedLocaleIDName parameter passed to the Collator() constructor.

+
  1. If the requested locale was not LocaleID.DEFAULT and + the operating system provides support for the requested locale, + then the name returned is the same as the requestedLocaleIDName property. +
  2. If LocaleID.DEFAULT was used as the value for the requestedLocaleIDName + parameter to the constructor, then the name of the current locale specified by the user's operating system + is used. The LocaleID.DEFAULT value preserves user's customized setting in the OS. Passing + an explicit value as the requestedLocaleIDName parameter does not necessarily give the + same result as using the LocaleID.DEFAULT even if the two locale ID names are the same. + The user might have customized the locale settings on their machine, and by requesting an + explicit locale ID name rather than using LocaleID.DEFAULT your application would not + retrieve those customized settings. +
    +

    For example:

    + + var fmt:Collator = new Collator(LocaleID.DEFAULT); + var aliName:String = fmt.actualLocaleIDName; + +

    In the above example, aliName is the name of the locale corresponding to + the user's current operating systems settings (e.g. "it-IT" if the user's locale is set to Italian-Italy), + and not "i-default" (the name of the LocaleID.DEFAULT locale).

    +
  3. If the system does not support the requestedLocaleIDName specified in the constructor + then a fallback locale ID name is provided. +
    +

    For Example:

    + + var fmt:Collator = new Collator("fr-CA"); + var aliName:String = fmt.actualLocaleIDName; + +

    Assuming that the operating system in the example above does not support the "fr-CA" (French-Canada) locale ID, + a fallback is used. In that case the aliName variable contains the fallback locale ID + "fr-FR" (French-France).

    +
+ +
LocaleIDrequestedLocaleIDName
ignoreCase + When this property is set to true, identical strings and strings that differ only in the case of the letters + are evaluated as equal.Boolean<code>true</code> when the <code>Collator()</code> constructor's <code>initialMode</code> parameter + is set to <code>Collator.MATCHING</code>. + <code>false</code> when the <code>Collator()</code> constructor's <code>initialMode</code> parameter + is set to Collator.SORTING. + + + When this property is set to true, identical strings and strings that differ only in the case of the letters + are evaluated as equal. + For example, compare("ABC", "abc") returns true when the + ignoreCase property is set to true. +

+ The case conversion of the string follows the rules for the specified locale. +

+ When the ignoreCase property is false then upper- and lowercase characters are not equal to one another. +

+ When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

+ Otherwise, the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
ignoreCharacterWidth + When this property is true, full-width and half-width forms of some Chinese and Japanese characters are evaluated as equal.Booleanfalse + + When this property is true, full-width and half-width forms of some Chinese and Japanese characters are evaluated as equal. + +

For compatibility with existing standards for Chinese and Japanese character sets, Unicode provides character codes + for both full-width and half width-forms of some characters. + For example, when the ignoreCharacterWidth property is set to true, + compare("Aア", "Aア") returns true.

+

+ If the ignoreCharacterWidth property is set to false, then full-width and half-width forms + are not equal to one another. +

+ +

When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

+ Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
ignoreDiacritics + When this property is set to true, strings that use the same base characters but + different accents or other diacritic marks are evaluated as equal.Booleanfalse + + When this property is set to true, strings that use the same base characters but + different accents or other diacritic marks are evaluated as equal. + For example compare("coté", "côte") returns true when the + ignoreDiacritics property is set to true. + +

When the ignoreDiacritics is set to false then base characters with + diacritic marks or accents are not considered equal to one another.

+ +

When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
ignoreKanaType + When this property is set to true, strings that differ only by the type of kana character being used are + treated as equal.Booleanfalse + + When this property is set to true, strings that differ only by the type of kana character being used are + treated as equal. + For example, compare("カナ", "かな") returns true when the + ignoreKanaType property is set to true. +

+ If the ignoreKanaType is set to false then hiragana and katakana characters that refer to the same + syllable are not equal to one another. +

+ +

When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
ignoreSymbols + When this property is set to is true, symbol characters such as spaces, currency symbols, math symbols, + and other types of symbols are ignored when sorting or matching.Booleanfalse + + When this property is set to is true, symbol characters such as spaces, currency symbols, math symbols, + and other types of symbols are ignored when sorting or matching. + For example the strings "OBrian", "O'Brian", and "O Brian" would all be treated as equal when the + ignoreSymbols property is set to true. +

+ If the ignoreSymbols property is false then symbol characters are considered in string comparisons. +

+ +

When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

+ Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
lastOperationStatus + The status of the most recent operation that this Collator object performed.String + The status of the most recent operation that this Collator object performed. + The lastOperationStatus is set whenever the constructor or a method of + this class is called, or when a property is set. For the possible values see the description under each method. + + LastOperationStatusnumericComparison + Controls how numeric values embedded in strings are handled during string comparison.Booleanfalse + + + Controls how numeric values embedded in strings are handled during string comparison. + +

When the numericComparison property is set to true, the compare method + converts numbers that appear in strings to numerical values for comparison.

+ +

When this property is set to false, the comparison treats numbers as character codes and + sort them according to the rules for sorting characters in the specified locale.

+ +

For example, when this property is true for the locale ID "en-US", then the strings + "version1", "version10", and "version2" + are sorted into the following order: version1 < version2 < version10.

+

When this property is false for "en-US", those same strings + are sorted into the following order: version1 < version10 < version2.

+ +

When this property is assigned a value and there are no errors or warnings, + the lastOperationStatus property is set to:

+
  • LastOperationStatus.NO_ERROR
+

+ Otherwise the lastOperationStatus property is set to one of the constants + defined in the LastOperationStatus class.

+ +
lastOperationStatuscompare()equals()LastOperationStatus
requestedLocaleIDName + The name of the requested locale ID that was passed to the constructor of this Collator object.String + The name of the requested locale ID that was passed to the constructor of this Collator object. + +

If the LocaleID.DEFAULT value was used then the name returned is "i-default". + The actual locale used can differ from the requested locale when a fallback locale is applied. + The name of the actual locale can be retrieved using the actualLocaleIDName property. +

+ +
LocaleIDactualLocaleIDName
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.html.xml b/language-server/playerglobal_docs/flash.html.xml new file mode 100644 index 0000000..c6195ff --- /dev/null +++ b/language-server/playerglobal_docs/flash.html.xml @@ -0,0 +1,1098 @@ +flash.htmlHTMLSWFCapability + + The HTMLSWFCapability class contains possible values of the swfCapability property of + an HTMLLoader object.Object + The HTMLSWFCapability class contains possible values of the swfCapability property of + an HTMLLoader object. + It also defines the values of the errorID property of an ErrorEvent object dispatched + when an attempt to load SWF content is unsuccessful. + + HTMLLoader.swfCapabilityERROR_INSTALLED_PLAYER_NOT_FOUND + No version of Adobe Flash Player is detected.3221int + No version of Adobe Flash Player is detected. An HTMLLoader + object cannot display PDF content. + + ERROR_INSTALLED_PLAYER_TOO_OLD + Adobe Flash Player is detected, but the version is too old.3222int + Adobe Flash Player is detected, but the version is too old. An HTMLLoader + object cannot display SWF content. + + STATUS_OK + A sufficient version of Adobe Flash Player is detected and SWF content + can be loaded in a HTMLLoader object.0int + A sufficient version of Adobe Flash Player is detected and SWF content + can be loaded in a HTMLLoader object. + + HTMLHistoryItem + An HTMLHistoryItem object describes a location in the navigation history of + an HTMLLoader object.Object + An HTMLHistoryItem object describes a location in the navigation history of + an HTMLLoader object. + + HTMLLoaderHTMLWindowCreateOptionsisPost + Indicates whether the HTML page includes POST data.Boolean + Indicates whether the HTML page includes POST data. + + originalUrl + The original URL of the HTML page, before any redirects.String + The original URL of the HTML page, before any redirects. + + title + The title of the HTML page.String + The title of the HTML page. + + url + The URL of the HTML page.String + The URL of the HTML page. + + HTMLHost + An HTMLHost object defines behaviors of an HTMLLoader object for user interface elements that + can be controlled by setting various properties or by calling various methods of the window + object of the HTML page.Object + An HTMLHost object defines behaviors of an HTMLLoader object for user interface elements that + can be controlled by setting various properties or by calling various methods of the window + object of the HTML page. These methods and properties are: + +
  • window.blur()
  • window.focus()
  • window.moveBy()
  • window.moveTo()
  • window.location
  • window.close()
  • window.open()
  • window.resizeBy()
  • window.resizeTo()
  • window.status
  • window.document.title
+ +

The methods in the HTMLHost class provide ways of handling changes in each of these window + settings. To use this class, create a new class (a subclass) that extends the HTMLHost class and + that overrides the methods for which you want to define behaviors. The methods of the HTMLHost class + handle JavaScript properties and methods as follows:

+ + JavaScript property or methodHTMLHost methodwindow.blur()windowBlur()window.focus()windowFocuswindow.locationupdateLocationwindow.close()windowClosewindow.open()createWindowwindow.statusupdateStatuswindow.document.titleupdateTitle + +

To respond to changes in the window.moveBy(), window.moveTo(), + window.resizeBy(), and window.resizeTo() methods, override + the set windowRect() method in the subclass of HTMLHost.

+ +

Each HTMLHost object can be associated with at most one HTMLLoader object. Assigning + an HTMLHost instance to the htmlHost property of the HTMLLoader object + establishes this relationship. Assigning null to the htmlHost + property of the HTMLLoader object or setting the HTMLHost object as the htmlHost + property of another HTMLLoader object removes the HTMLHost from the first HTMLLoader object.

+ +
The following code defines CustomHost, a subclass of HTMLHost. + Methods of the CustomHost class override the inherited methods in the HTMLHost + class to define actions taken when JavaScript code in the HTMLLoader page + sets various properties or calls various methods of the window + object: + +package +{ + import flash.html.HTMLHost; + import flash.html.HTMLLoader; + import flash.display.NativeWindow; + import flash.display.NativeWindowInitOptions; + import flash.display.StageScaleMode; + import flash.geom.Rectangle; + import flash.text.TextField; + + public class CustomHost extends HTMLHost + { + import flash.html.*; + public var statusField:TextField; + public function CustomHost(defaultBehaviors:Boolean=true) + { + super(defaultBehaviors); + } + override public function windowClose():void + { + htmlLoader.stage.window.close(); + } + override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader + { + var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions(); + var window:NativeWindow = new NativeWindow(initOptions); + window.visible = true; + var htmlLoader2:HTMLLoader = new HTMLLoader(); + htmlLoader2.width = window.width; + htmlLoader2.height = window.height; + window.stage.scaleMode = StageScaleMode.NO_SCALE; + window.stage.addChild(htmlLoader2); + return htmlLoader2; + } + override public function updateLocation(locationURL:String):void + { + trace(locationURL); + } + override public function set windowRect(value:Rectangle):void + { + htmlLoader.stage.nativeWindow.bounds = value; + } + override public function updateStatus(status:String):void + { + statusField.text = status; + } + override public function updateTitle(title:String):void + { + htmlLoader.stage.nativeWindow.title = title + "- Example Application"; + } + override public function windowBlur():void + { + htmlLoader.alpha = 0.5; + } + override public function windowFocus():void + { + htmlLoader.alpha = 1; + } + } +} + Create the following class, which adds an HTMLLoader object to the + stage, as well as a TextField object named statusBar. The HTMLLoader + object defines a CustomHost object as its htmlHost property: + + package + { + import flash.display.Sprite; + + public class SimpleHTMLBox extends Sprite + { + import flash.html.HTMLHost; + import flash.html.HTMLLoader; + import flash.text.TextField; + import flash.net.URLRequest; + import CustomHost; + private var host:CustomHost; + private var statusField:TextField; + private var html:HTMLLoader; + + public function SimpleHTMLBox() + { + html = new HTMLLoader(); + var url:String = "Test.html"; + var urlReq:URLRequest = new URLRequest(url); + html.load(urlReq); + + host = new CustomHost(); + html.htmlHost = host; + statusField = new TextField(); + host.statusField = statusField; + + configureUI(); + } + private function configureUI():void + { + html.width = 400; + html.height = 200; + statusField.width = 400; + statusField.height = 24; + statusField.border = true; + statusField.y = 200; + + addChild(html); + addChild(statusField); + } + + } + } + +

Build an AIR application that adds an object defined by this class to + the main window's stage.

+ +

Create an HTML page named Test.html in the application resources directory + (the directory that contains the application descriptor file), and add the + following content to it:

+ + <html> + <head> + <title>Test</title> + </head> + <body> + <a href="#" onclick="window.open('Test.html')">window.open('Test.html')</a> + <br/><a href="#" onclick="window.document.location = 'www.adobe.com'">window.document.location = 'www.adobe.com'</a> + <br/><a href="#" onclick="window.moveBy(6, 12)">moveBy(6, 12)</a> + <br/><a href="#" onclick="window.close()">window.close()</a> + <br/><a href="#" onclick="window.blur()">window.blur()</a> + <br/><a href="#" onclick="window.focus()">window.focus()</a> + <br/><a href="#" onclick="window.status = new Date().toString()">window.status = new Date().toString()</a> + </body> + </html> + +

When you test the application, the CustomHost class handles the user-interface-related + JavaScript settings in the HTML page.

+
HTMLLoaderHTMLWindowCreateOptionsHTMLHost + Creates an HTMLHost object.defaultBehaviorsBooleantrueIndicates wether root-content behaviors should be provided by default. + + + Creates an HTMLHost object. + + createWindow + The function called when JavaScript code in the HTMLLoader object calls the + window.open() method.An HTMLLoader object that contains the new HTML page. Typically, + you create a new HTMLLoader object in this method, add it to the stage of a new + NativeWindow object, and then return it. + + flash.html:HTMLLoaderwindowCreateOptionsflash.html:HTMLWindowCreateOptionsAn object containing properties in the string passed as the + features parameter of the call to window.open(). + + + The function called when JavaScript code in the HTMLLoader object calls the + window.open() method. + +

By default, a JavaScript call to window.open() in the HTML + page of an HTMLLoader does not open an new NativeWindow object in the + runtime. You can open a new NativeWindow object in the runtime by creating a + new NativeWindow object in the createWindow method override in + the subclass of the HTMLHost class.

+ +
updateLocation + The function called when JavaScript code in the HTMLLoader object sets the + window.location property.locationURLStringThe value to which the location property + of the window property of the HTMLLoader object is set. + + + The function called when JavaScript code in the HTMLLoader object sets the + window.location property. + + updateStatus + The function called when JavaScript code in the HTMLLoader object sets the + window.status property.statusStringThe value to which the status property + of the window property of the HTMLLoader object is set. + + + The function called when JavaScript code in the HTMLLoader object sets the + window.status property. + + updateTitle + The function called when JavaScript code in the HTMLLoader object sets the + window.document.title property or when the title + element changes, either via the DOM or because of a new page load.titleStringThe value to which the window.document.title property + of the HTMLLoader object is set. + + + The function called when JavaScript code in the HTMLLoader object sets the + window.document.title property or when the title + element changes, either via the DOM or because of a new page load. + + windowBlur + The function called when JavaScript code in the HTMLLoader object calls the + window.blur() method. + The function called when JavaScript code in the HTMLLoader object calls the + window.blur() method. + + windowClose + The function called when JavaScript code in the HTMLLoader object calls the + window.close() method. + The function called when JavaScript code in the HTMLLoader object calls the + window.close() method. + +

By default, a JavaScript call to window.close() in the HTML + page of an HTMLLoader object closes the windows containing the HTMLLoader object.

+ +
windowFocus + The function called when JavaScript code in the HTMLLoader object calls the + window.focus() method. + The function called when JavaScript code in the HTMLLoader object calls the + window.focus() method. + + htmlLoader + The HTMLLoader object to which this HostControl object applies.flash.html:HTMLLoader + The HTMLLoader object to which this HostControl object applies. The htmlHost + property of that HTMLLoader object is set to this HostControl object. + + HTMLLoader.htmlHostwindowRect + The property that is changed when JavaScript code in the HTMLLoader object calls + the window.moveBy(), window.moveTo(), + window.resizeBy(), or window.resizeTo() method.flash.geom:Rectangle + The property that is changed when JavaScript code in the HTMLLoader object calls + the window.moveBy(), window.moveTo(), + window.resizeBy(), or window.resizeTo() method. + +

In the subclass of HTMLHost, override the set windowRect() method + to handle the new window bounds, as desired.

+ +
HTMLPDFCapability + The HTMLPDFCapability class contains possible values of the pdfCapability property of + an HTMLLoader object.Object + The HTMLPDFCapability class contains possible values of the pdfCapability property of + an HTMLLoader object. + It also defines the values of the errorID property of an ErrorEvent object dispatched + when an attempt to load PDF content is unsuccessful. + + HTMLLoader.pdfCapabilityERROR_CANNOT_LOAD_READER + An error was returned by the OS when trying to load the Adobe Reader or Acrobat + application or one of its necessary libraries.3204int + An error was returned by the OS when trying to load the Adobe Reader or Acrobat + application or one of its necessary libraries. + +

Note: This is not returned from HTMLLoader.pdfCapability, but it is + sent as the errorID property of an ErrorEvent object dispatched when + an HTMLLoader object attempts to load PDF content and the operating system returns an error. + HTMLLoader.pdfCapability may return PDFCapability.STATUS_OK, + because it examines only the configuration and does not + attempt to load any libraries.

+ +
ERROR_INSTALLED_READER_NOT_FOUND + No version of Adobe Reader is detected.3201int + No version of Adobe Reader is detected. An HTMLLoader + object cannot display PDF content. + + ERROR_INSTALLED_READER_TOO_OLD + Adobe Reader is detected, but the version is too old.3202int + Adobe Reader is detected, but the version is too old. An HTMLLoader + object cannot display PDF content. + + ERROR_PREFERRED_READER_TOO_OLD + A sufficient version (8.1 or later) of Adobe Reader or Acrobat is detected, but the the version + of Adobe Reader that is set up to handle PDF content is older than Adobe Reader or Acrobat 8.1.3203int + A sufficient version (8.1 or later) of Adobe Reader or Acrobat is detected, but the the version + of Adobe Reader that is set up to handle PDF content is older than Adobe Reader or Acrobat 8.1. + An HTMLLoader object cannot display PDF content. + +
HTMLLoader + The HTMLLoader class defines a type of display object that is a container for HTML content.flash.display:Sprite + The HTMLLoader class defines a type of display object that is a container for HTML content. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or on AIR for TV devices. You can test + for support at run time using the HTMLLoader.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

The default dimensions of an HTMLLoader are 0 x 0 pixels. Set the width + and height properties to make the HTMLLoader object visible.

+ +

+ The maximum size for an HTMLLoader object is 4,096 pixels in height and 4,096 pixels in width. + Setting width or height of an HTMLLoader object to a number that exceeds + 4,095 causes the HTMLLoader object to throw an ArgumentError exception. (Note, prior to AIR 2, the + maximum size of HTMLLoader object was 2,880 pixels.) +

+ + + + + +

Note: When displayed in a transparent window, SWF content embedded + in an HTML page must be embedded using either the transparent or opaque wmode. + The default value for wmode is window, so if you do not specify a value, SWF content + may not be displayed. On Windows and Linux, SWF content always appears on top of other content + when wmode is set to window or opaque. PDF content + cannot be displayed in a transparent window no matter which wmode setting is used.

+ +
The following code initializes an HTMLLoader object, configures its width and height, + loads the URL http://www.adobe.com, and adds the object to the display list: + +package { + import flash.display.Sprite; + import flash.html.HTMLLoader; + import flash.net.URLRequest; + + public class HTMLLoaderExample extends Sprite + { + public function HTMLLoaderExample() + { + var html:HTMLLoader = new HTMLLoader(); + var urlReq:URLRequest = new URLRequest("http://www.adobe.com/"); + html.width = stage.stageWidth; + html.height = stage.stageHeight; + html.load(urlReq); + addChild(html); + } + } +} +
htmlDOMInitialize + Signals that the HTML DOM has been created in response to a load operation.flash.events.Event.HTML_DOM_INITIALIZEflash.events.Event + Signals that the HTML DOM has been created in response to a load operation. The load() + and loadString() methods of the HTMLLoader object throw an exception while + this event is being dispatched. Any property or method of any JavaScript object accessible from the + window property of the HTMLLoader object that controls the URL that is loaded in + the HTMLLoader object throws an exception if set or called while this event is dispatched. + For example, setting window.location by setting the window property of + the HTMLLoader object results in a JavaScript exception. + + loadString()load()uncaughtScriptException + Signals that an uncaught JavaScript exception occurred in the HTMLLoader object.flash.events.HTMLUncaughtScriptExceptionEvent.UNCAUGHT_SCRIPT_EXCEPTIONflash.events.HTMLUncaughtScriptExceptionEvent + Signals that an uncaught JavaScript exception occurred in the HTMLLoader object. + Event handlers can call any method or access any property of the HTMLLoader object. + + The event is cancelable, and the default behavior when running in the AIR Debug Launcher + is to send the JavaScript stack to the trace output. + + loadString()load()scroll + Signals that the scrollH or scrollV property has been changed + by the HTMLLoader object.flash.events.Event.SCROLLflash.events.Event + Signals that the scrollH or scrollV property has been changed + by the HTMLLoader object. The HTMLLoader object dispatches this event when JavaScript running in the + HTMLLoader object invokes the scrollTo() method of the window object + and the desired location is not already visible. The event is not dispatched when ActionScript + code changes the scrollH or scrollV property. + Event handlers may call any method or access any property + of the HTMLLoader object. + +

Event handlers for this event should check the scrollH and scrollV + properties to update any scroll bars associated with the HTMLLoader object.

+ +

The HTMLLoader object can dispatch this event any time after a load operation is initiated, + even after the object has dispatched the complete event.

+ +
htmlBoundsChange + Signals that one or both of the contentWidth and contentHeight + properties of the HTMLLoader object has changed.flash.events.Event.HTML_BOUNDS_CHANGEflash.events.Event + Signals that one or both of the contentWidth and contentHeight + properties of the HTMLLoader object has changed. This may be result from a new image or other content loading, + for example. Event handlers may call any method or access any property + of the HTMLLoader object. + +

The HTMLLoader object can dispatch this event any time after a load operation is initiated, + even after the object has dispatched the complete event.

+ +
contentWidthcontentHeight
locationChange + Signals that the location property of the HTMLLoader object has changed.flash.events.LocationChangeEvent.LOCATION_CHANGEflash.events.LocationChangeEventSignals that the location property of the HTMLLoader object has changed. + + + Signals that the location property of the HTMLLoader object has changed. + The event handler for this event can call any method or access any property of the + HTMLLoader object. + +

A locationChange event of type LocationChangeEvent is dispatched by the + HTMLLoader in applications using AIR namespace 2.7 and later. In earlier versions of AIR, + the dispatched event object is an instance of the Event class.

+ +
loadString()load()
locationChange + Signals that the location property of the HTMLLoader object has changed.flash.events.Event.LOCATION_CHANGEflash.events.EventSignals that the location property of the HTMLLoader object has changed. + + + Signals that the location property of the HTMLLoader object has changed. + The event handler for this event can call any method or access any property of the + HTMLLoader object. + +

A locationChange event of type Event is dispatched by the HTMLLoader + in applications using an AIR namespace prior to 2.7. In AIR 2.7 and later, the event object is + an instance of the LocationChangeEvent class, which provides an additional location property set + to the new page URL.

+ +
loadString()load()
locationChanging + Signals that the location property of the HTMLLoader object is about to change.flash.events.LocationChangeEvent.LOCATION_CHANGINGflash.events.LocationChangeEventSignals that the location property of the HTMLLoader object is about to change. + + Signals that the location property of the HTMLLoader object is about to change. + +

A locationChanging event is dispatched only when the location change is initiated through + user interaction, such as when a user clicks a link, or by code running inside the HTMLLoader, such as a client-side redirect. + By default, the new location is displayed in this + HTMLLoader object. You can call the preventDefault() method of the event + object to cancel the default behavior. For example, you could use the flash.net.navigateToURL() + function to open the page in the system browser based on the location + property of the event object.

+ +

A locationChanging() event is not dispatched when you call the following methods:

+
  • load()
  • loadString()
  • reload()
  • historyBack()
  • historyForward()
  • historyGo()
+

In addition, this event is not dispatched when the navigateInSystemBrowser property is true + and the destination page is opened in the system browser, since the HTMLLoader location does not change.

+ +
The following code initializes an HTMLLoader object, configures its width and height, + loads the URL http://www.adobe.com, and adds the object to the display list. If the user (or JavaScript on the page) + attempts to navigate to a URL that doesn't start with the base URL, the navigation is prevented: + +package{ + import flash.display.Sprite; + import flash.html.HTMLLoader; + import flash.net.URLRequest; + + public class LocationChanging extends Sprite + { + var htmlLoader:HTMLLoader = new HTMLLoader(); + public function LocationChanging() + { + htmlLoader.width = stage.stageWidth; + htmlLoader.height = stage.stageHeight; + htmlLoader.addEventListener( LocationChangeEvent.LOCATION_CHANGING, onLocationChanging ); + htmlLoader.load( new URLRequest( "http://www.adobe.com" ) ); + this.addChild( htmlLoader ); + } + + private function onLocationChanging( event:LocationChangeEvent ):void + { + trace( "Location changing: " + event.location ); + + if ( event.location.indexOf( "http://www.adobe.com" ) < 0 ) + { + event.preventDefault(); + } + } + } +} +
htmlRender + Signals that the rendering of content in the HTMLLoader object is fully up to date.flash.events.Event.HTML_RENDERflash.events.Event + Signals that the rendering of content in the HTMLLoader object is fully up to date. + This event can be dispatched quite frequently—whenever any rendering change is + made to the HTML content. For example, this event is dispatched when new content is + displayed as a result of a user clicking a link or when JavaScript in the page renders HTML. + Event listeners can call any method or access any property of the HTMLLoader object. + +

Handlers of this event should check the contentWidth and contentHeight + properties of the HTMLLoader object to update any scroll bars associated with it.

+ +

The HTMLLoader object can dispatch this event any time after a load operation is initiated, + even after the object has dispatched the complete event.

+ +
complete + Signals that the last load operation requested by loadString or + load method has completed.flash.events.Event.COMPLETEflash.events.Event + Signals that the last load operation requested by loadString or + load method has completed. + The event is dispatched after the JavaScript load event has fired + on the HTML DOM in the HTMLLoader object. + This event is always dispatched asynchronously. The event handler for this event can call any + method or access any property of the HTMLLoader object. + + loadString()load()HTMLLoader + Creates an HTMLLoader object. + Creates an HTMLLoader object. + + cancelLoad + Cancels any load operation in progress. + Cancels any load operation in progress. + + createRootWindow + Creates a new NativeWindow object that contains an HTMLLoader object.A new HTMLLoader object that is on the stage of the new NativeWindow object. + + flash.html:HTMLLoadervisibleBooleantrueSpecifies whether the window is visible. + + windowInitOptionsflash.display:NativeWindowInitOptionsnullSpecifies window initialization options; if null, uses default + NativeWindowInitOptions values. + + scrollBarsVisibleBooleantrueSpecifies whether the window provides scrollbars. + + boundsflash.geom:RectanglenullIf not null, specifies the window bounds. If any of x, y, + width, or height is NaN, then the corresponding dimension of the window is + left at its default value. + + + Creates a new NativeWindow object that contains an HTMLLoader object. Use the + HTMLLoader object that is returned by this method to load HTML content. + +

By default (when you set no parameters in calling this method), the new window uses + standard system chrome and includes scrollbar controls for the content. You can set the + parameters to change the properties of the new window.

+ +

As the window loads content and applies stylesheets, minor graphics glitches can occur. To prevent such + discontinuities from being visible, set the visible parameter to false. When the + window has loaded and layed out its content, reveal it by setting the window.nativeWindow.visible property to + true or call the window.nativeWindow.activate() method.

+ +
getHistoryAt + Returns the history entry at the specified position.A URLRequest object for the history entry at the specified position. + + flash.html:HTMLHistoryItempositionuintThe position in the history list. + + + Returns the history entry at the specified position. + + historyPositionhistoryBack + Navigates back in the browser history, if possible. + Navigates back in the browser history, if possible. + +

Calling this method of the HTMLLoader object has the same effect + as calling the back() method of the window.history + property in JavaScript in the HTML page.

+ +

This function throws no errors.

+ +
historyPosition
historyForward + Navigates forward in the browser history, if possible. + Navigates forward in the browser history, if possible. + +

Calling this method of the HTMLLoader object has the same effect + as calling the forward() method of the window.history + property in JavaScript in the HTML page.

+ +

This function throws no errors.

+ +
historyPosition
historyGo + Navigates the specified number of steps in the browser history.stepsintThe number of steps in the history list to move + forward (positive) or backward (negative). + + + Navigates the specified number of steps in the browser history. + Navigates forward if positive, backward if negative. + Navigation by zero forces a reload. + +

This method is equivalent to calling the go() method of + the window.history property in JavaScript in the HTML page.

+ +

This function throws no errors.

+ +
historyPosition
loadString + Loads the HTMLLoader object with the HTML content contained in the HTML string.htmlContentStringThe string containing the HTML content to load into the HTMLLoader object. + + + Loads the HTMLLoader object with the HTML content contained in the HTML string. When rendering of the + of the HTML in the string is complete, the complete event is dispatched. The + complete event is always dispatched asynchronously. + +

A call to this method implicitly cancels any pending previous load operation initiated with + this method or with the load() method. The complete event for the previous + load operation will never be delivered.

+ +

If the HTML specified in the string has no references to external resources, then this method + synchronously renders the HTML. However, the complete event is still dispatched + asynchronously. If the loaded property of this class is true immediately + following a call to this function, the HTML content specified in the htmlContent argument + was rendered synchronously.

+ +

It is possible that the complete event will never be delivered. This happens if any of + the HTML content loaded into the HTMLLoader object never downloads completely. This can happen if + the HTML content references a URL to a CGI script that repetedly generates content indefinitely.

+ +

Content loaded via the loadString() method is put in the application security sandbox + only if the placeLoadStringContentInApplicationSandbox property is set to true.

+ +
placeLoadStringContentInApplicationSandbox
load + Loads the HTMLLoader object with data from the site specified by the urlRequestToLoad parameter.urlRequestToLoadflash.net:URLRequestThe URLRequest object containing information about the URL to + load. In addition to the URL to load, a URLRequest object contains properties that define + the HTTP form submission method (GET or POST), any data to be transmitted with the request, + and request headers. + + + Loads the HTMLLoader object with data from the site specified by the urlRequestToLoad parameter. + Calling this method initially sets the loaded property to false. This method + initiates an operation that always completes asynchronously. + +

A call to this method implicitly cancels any pending previous load operation initiated with + this method or with the loadString() method. The complete event for the previous + load operation will never be delivered.

+ +

It is possible that the complete event will never be delivered. This happens if any of + the HTML content loaded into the HTMLLoader object never downloads completely. This can happen if + the HTML content references a URL to a CGI script that repetedly generates content indefinitely.

+ +
flash.net.URLRequest
reload + Reloads the page from the current location. + Reloads the page from the current location. + + authenticate + Specifies whether authentication requests should be handled (true) + or not (false) for HTTP requests issued by this object.Booleaninitialized from URLRequestDefaults.authenticate + + + Specifies whether authentication requests should be handled (true) + or not (false) for HTTP requests issued by this object. If false, authentication + challenges return an HTTP error. + + flash.net.URLRequest.authenticateflash.net.URLRequestDefaults.authenticatecacheResponse + Specifies whether successful response data should be cached for HTTP requests issued by this object.Booleaninitialized from URLRequestDefaults.cacheResponse + + + Specifies whether successful response data should be cached for HTTP requests issued by this object. + When set to true, the HTMLLoader object uses the operating system's HTTP cache. + + flash.net.URLRequestDefaults.cacheResponsecontentHeight + The height, in pixels, of the HTML content.Number + The height, in pixels, of the HTML content. This property can change as the dimensions of the HTMLLoader object change. + For example, an HTML page often uses the entire height of the HTMLLoader object, and the contentHeight property may + change if you change the height of the HTMLLoader object. + + contentWidth + The width, in pixels, of the HTML content.Number + The width, in pixels, of the HTML content. This property can change as the dimensions of the HTMLLoader object change. + For example, an HTML page often uses the entire width of the HTMLLoader object, and the contentWidth property may + change if you change the width of the HTMLLoader object. + + hasFocusableContent + Indicates whether any content in the HTMLLoader object is focusable.Boolean + Indicates whether any content in the HTMLLoader object is focusable. + + height + Specifies the height of the rectangle of the HTML canvas that is being rendered.Number + Specifies the height of the rectangle of the HTML canvas that is being rendered. + This property value is the height of the HTMLLoader display object in pixels. The maximum height value is 4095 pixels. + Changing this property causes the HTMLLoader object to re-render the HTML document. + htmlBoundsChanged events may dispatched in response to changing this property. + +

When you set the width or + height property of an HTMLLoader object, the bounds of the object change but + the content is not scaled (as would happen with other types of display objects).

+ +
historyLength + The overall length of the history list, including back and forward entries.uint + The overall length of the history list, including back and forward entries. + This property has the same value as the window.history.length + JavaScript property of the HTML page. + + historyPositionhistoryPosition + The current position in the history list.uint + The current position in the history list. The history list corresponds to the + window.history object of the HTML page. + Entries less than the current position are the "back" list; entries greater are "forward." + Attempts to set position beyond the end set it to the end. + + getHistoryAt()historyBack()historyGo()historyForward()historyLengthhtmlHost + The HTMLHost object used to handle changes to certain user interface elements, such as the + window.document.title property of the HTMLLoader object.flash.html:HTMLHostThe HTMLHost object used to handle changes to certain user interface elements, such as the + window.document.title property of the HTMLLoader object. + + + The HTMLHost object used to handle changes to certain user interface elements, such as the + window.document.title property of the HTMLLoader object. To override default + behaviors for the HTMLLoader object, create a subclass of the HTMLHost class and override its member + functions to handle various user interface changes in the HTML content. + + HTMLHost classidleTimeout + Specifies the idle timeout value (in milliseconds) for HTTP requests issued by this object.Numberinitialized from URLRequestDefaults.idleTimeout + + + Specifies the idle timeout value (in milliseconds) for HTTP requests issued by this object. + +

The idle timeout is the amount of time the client waits for a response from the server, after the connection is established, + before abandoning the request.

+ +
URLRequestDefaults.idleTimeout
isSupported + Indicates whether the HTMLLoader class is supported on the client system.Boolean + Indicates whether the HTMLLoader class is supported on the client system. + + loaded + Indicates whether the JavaScript load event corresponding to the previous call to the + load() or loadString() method has been delivered to + the HTML DOM in the HTMLLoader object.Boolean + Indicates whether the JavaScript load event corresponding to the previous call to the + load() or loadString() method has been delivered to + the HTML DOM in the HTMLLoader object. + + This property is true before the complete event is dispatched. + + It is possible that this property will never become true. This happens in the + same cases as when the complete event is never dispatched. + + location + The URL for the content loaded in the HTMLLoader object.String + The URL for the content loaded in the HTMLLoader object. + + manageCookies + Specifies whether the HTTP protocol stack should manage cookies for this + object.Booleaninitialized from URLRequestDefaults.manageCookies + + + Specifies whether the HTTP protocol stack should manage cookies for this + object. If true, cookies are added to the request + and response cookies are remembered. If false, cookies are + not added to the request and response cookies are not + remembered. + + flash.net.URLRequest.manageCookiesflash.net.URLRequestDefaults.manageCookiesnavigateInSystemBrowser + Specifies whether navigation of the root frame of the HTML content (such as when the user clicks a link, when the + window.location property is set, or when calling window.open()) results in + navigation in the HTMLLoader object (false) or in the default system web browser + (true).Booleanfalse + + Whether navigation of the root frame of the HTML content results in navigation in the + HTMLLoader object (false) or in the default system web browser (true). + + + Specifies whether navigation of the root frame of the HTML content (such as when the user clicks a link, when the + window.location property is set, or when calling window.open()) results in + navigation in the HTMLLoader object (false) or in the default system web browser + (true). Set this property to true if you want all navigation to occur in the + system web browser (not in the HTMLLoader object). + + paintsDefaultBackground + Specifies whether the background of the HTMLLoader document is opaque white (true) or + not (false).BooleanDetermines whether the background of the HTMLLoader document is opaque white (true) + or not (false). + + + Specifies whether the background of the HTMLLoader document is opaque white (true) or + not (false). If this property is set to false, the HTMLLoader + object uses its display object container as a background for the HTML and it uses the opacity + (alpha value) of the display object container as the HTML background. However, if + the body element or any other element of the HTML document has an opaque background + color (specified by style="background-color:gray", for instance), then that portion + of the rendered HTML uses the specified opaque background color. + + pdfCapability + The type of PDF support on the user's system, defined as an integer code value.int + The type of PDF support on the user's system, defined as an integer code value. + An HTMLLoader object can display PDF content only if this property evaluates to + PDFCapability.STATUS_OK. The PDFCapability class defines constants + for possible values of the pdfCapability property, as follows: + + PDFCapability constantMeaningSTATUS_OKA sufficient version (8.1 or later) of Acrobat or Adobe Reader is detected and PDF content + can be loaded in an HTMLLoader object. + +

Note: On Windows, if Acrobat or Adobe Reader version 7.x or later, + is currently running on the user's system, that version is used even if a later version + that supports loading PDF loaded in an HTMLLoader object is installed. In this case, + if the value of the pdfCapability property is PDFCapability.STATUS_OK, + when an AIR application attempts to load PDF content, the older version of Acrobat or Adobe Reader + displays an alert (and the AIR runtime displays no error message). If this is a possibile situation + for your users, consider instructing them to close Acrobat or Adobe Reader while running your + application. Consider displaying these instructions if the PDF + content does not load within an acceptable amount of time.

ERROR_INSTALLED_READER_NOT_FOUNDNo version of Acrobat or Adobe Reader is detected. An HTMLLoader + object cannot display PDF content.ERROR_INSTALLED_READER_TOO_OLDAcrobat or Adobe Reader has been detected, but the version is too old. An HTMLLoader + object cannot display PDF content.ERROR_PREFERED_READER_TOO_OLDA sufficient version (8.1 or later) of Acrobat or Adobe Reader is detected, but the + the version that is set up to handle PDF content is older than 8.1. An HTMLLoader + object cannot display PDF content.
+ +
HTMLPDFCapability class
placeLoadStringContentInApplicationSandbox + Specifies whether content loaded via the loadString() method is put in + the application sandbox (true) or in a non-application sandbox + (false).Booleanfalse + + + Specifies whether content loaded via the loadString() method is put in + the application sandbox (true) or in a non-application sandbox + (false). + +

When this property is set to false, content loaded via the loadString() + method is placed in a non-application sandbox with the following characteristics:

+ +
  • It has access to load content from the network (but not from the filesystem).
  • It cannot load data using XMLHttpRequest.
  • The window.location property is set to "about:blank".
  • The content cannot access the window.runtime property (like content + in any non-application sandbox).
+ +

When this property is set to true, the content loaded via the loadString() + method is placed in the application sandbox, with access to the window.runtime property + and to all AIR APIs. You should ensure that the data source for a string used in a call to the + loadString() method is trusted. Code statements in the HTML string are executed with full + application privileges when this property is set to true. You should only set this property to + true when you are certain that the string cannot contain harmful code.

+ +

In applications compiled with the AIR 1.0 or AIR 1.1 SDKs, content loaded via the loadString() + method is placed in the application sandbox.

+ +
loadString()
runtimeApplicationDomain + The application domain to use for the window.runtime object in JavaScript + in the HTML page.flash.system:ApplicationDomainif the ApplicationDomain object is not from the + caller's security domain. + + SecurityErrorSecurityErrorThe application domain to use for the window.runtime + object in JavaScript in the HTML page. + + + The application domain to use for the window.runtime object in JavaScript + in the HTML page. + +

If null, or if the HTML content is from a different + security domain than the SWF content that contains the HTMLLoader object, the page uses + a default application domain for its domain.

+ +
flash.system.ApplicationDomainflash.system.SecurityDomain
scrollH + The horizontal scroll position of the HTML content in the HTMLLoader object.Number + The horizontal scroll position of the HTML content in the HTMLLoader object. + + scrollV + The vertical scroll position of the HTML content in the HTMLLoader object.Number + The vertical scroll position of the HTML content in the HTMLLoader object. + + swfCapability + The type of SWF support on the user's system, defined as an integer code value.int + The type of SWF support on the user's system, defined as an integer code value. + An HTMLLoader object can display SWF content only if this property evaluates to + HTMLSWFCapability.STATUS_OK. The HTMLSWFCapability class defines constants + for possible values of the swfCapability property, as follows: + + HTMLSWFCapability constantMeaningSTATUS_OKA sufficient version of Adobe Flash Player is detected and SWF content + can be loaded in an HTMLLoader object.ERROR_INSTALLED_PLAYER_NOT_FOUNDNo version of Adobe Flash Player is detected. An HTMLLoader + object cannot display SWF content.ERROR_INSTALLED_PLAYER_TOO_OLDAdobe Flash Player has been detected, but the version is too old. An HTMLLoader + object cannot display SWF content. + + HTMLSWFCapability classtextEncodingFallback + The character encoding used by the HTMLLoader content if an HTML page does not specify + a character encoding.String + The character encoding used by the HTMLLoader content if an HTML page does not specify + a character encoding. An HTML page specifies a character encoding in a meta tag, + as in the following: + + <meta http-equiv="content-type" content="text/html" charset="ISO-8859-1"> + +

Values are defined in the IANA list of + valid + character sets. +

+ +

If no encoding is specified by the HTML page, by the textEncodingFallback + property, or by the textEncodingOverride property, the HTML content uses + ISO-8859-1 encoding.

+ +
textEncodingOverride
textEncodingOverride + The character encoding used by the HTMLLoader content, overriding any setting in the HTML page.String + The character encoding used by the HTMLLoader content, overriding any setting in the HTML page. + An HTML page specifies a character encoding in a meta tag, as in the following: + + <meta http-equiv="content-type" content="text/html" charset="ISO-8859-1"> + +

This setting also overrides any setting in the textEncodingFallback + property.

+ +

Values are defined in the IANA list of + valid + character sets. +

+ +

Set the textEncodingOverride property after the HTML content has loaded + to have AIR refresh the HTML content using the specified encoding. After the HTMLLoader + navigates to a new page, you need to set the property again if you want the new page to + use a specific encoding.

+ +

If no encoding is specified by the HTML page, by the textEncodingFallback + property, or by the textEncodingOverride property, the HTML content uses ISO-8859-1 + encoding.

+ +

Setting the textEncodingOverride property to null restores + the default behavior.

+ +
textEncodingFallback
useCache + Specifies whether the local cache should be consulted before HTTP requests issued by this object + fetch data.Booleaninitialized from URLRequestDefaults.useCache + + + Specifies whether the local cache should be consulted before HTTP requests issued by this object + fetch data. + + flash.net.URLRequest.useCacheflash.net.URLRequestDefaults.useCacheuserAgent + The user agent string to be used in any upcoming content requests from this HTMLLoader + object.String + The user agent string to be used in any upcoming content requests from this HTMLLoader + object. + +

To set the user agent string, set the userAgent property of the HTMLLoader + object before calling the load() method. The userAgent + property of the URLRequest object passed to the load() method is not used.

+ +

You can set the default user agent string used by all HTMLLoader objects in an application + domain by setting the URLRequestDefaults.userAgent property. If no value + is set for the userAgent property of the HTMLLoader object (or if the value + is set to null), the user agent string is set to the value of the static + URLRequestDefaults.userAgent property.

+ +

If a value is set for neither the userAgent property of the HTMLLoader nor for + URLRequestDefaults.userAgent, a default value is used as the user agent string. + This default value varies depending on the runtime operating system (such as Mac OS, Linux, or Windows), + the runtime language, and the runtime version, as in the following examples:

+ +
  • "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (Windows; U; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
+ +
flash.net.URLRequest.userAgentflash.net.URLRequestDefaults.userAgent
width + Specifies the width of the rectangle of the HTML canvas that is being rendered.Number + Specifies the width of the rectangle of the HTML canvas that is being rendered. + This is the width of the HTMLLoader display object in pixels. The maximum width value is 4095 pixels. + Changing this property causes the HTMLLoader object to re-render the HTML document. + htmlBoundsChange events may dispatched in response to changing this property. + + When you set the width and + height properties of an HTMLLoader object, the bounds of the object change but + content is not scaled (as would happen with other types of display objects). + + window + The global JavaScript object for the content loaded into the HTML control.Object + The global JavaScript object for the content loaded into the HTML control. + +
HTMLWindowCreateOptions + This class defines the options that can be specified when JavaScript running + in an HTMLLoader object tries to create a new HTML window by calling the + window.open() method.Object + This class defines the options that can be specified when JavaScript running + in an HTMLLoader object tries to create a new HTML window by calling the + window.open() method. + +

This class defines the properties and methods that correspond to options in the + features parameter passed to the window.open() method in JavaScript.

+ +

For example, JavaScript in an HTML document (in an HTMLLoader object) + can include the following call to window.open(), in which + the features parameter (the third parameter) lists a number + of options:

+ + window.open("http://www.adobe.com", "AdobeWindow", "scrollbars=1,menubar=1,location=0,status=0") + +

You use the HTMLWindowCreateOptions class in overriding the + createWindow() method of a subclass of the + HTMLHost class. The HTMLLoader object passes an HTMLWindowCreateOptions object + as the windowCreateOptions parameter of the createWindow() + method of the HTMLHost object.

+ +
HTMLHost#createWindow()fullscreen + Specifies whether the window should be full screen.falseBoolean + Specifies whether the window should be full screen. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "fullscreen", "fullscreen=1", or + "fullscreen=y". + + height + Specifies the desired initial height of the new window.NaNNumber + Specifies the desired initial height of the new window. This is set to the height value + in the features string of the JavaScript call to the window.open() + method. If the value is NaN, the default when no height value is + specified in the features string, then a default window height is used. + + locationBarVisible + Whether a location bar should be displayed.falseBoolean + Whether a location bar should be displayed. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "location", "location=1", or "location=y". + + menuBarVisible + Specifies whether a menu bar should be displayed.falseBoolean + Specifies whether a menu bar should be displayed. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "menubar", "menubar=1", or + "menubar=y". + + resizable + Specifies whether the window should be resizable.falseBoolean + Specifies whether the window should be resizable. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "resizable", "resizable=1", or + "resizable=y". + + scrollBarsVisible + Specifies whether scrollbars should be displayed.trueBoolean + Specifies whether scrollbars should be displayed. This property is set to true if the + features string of JavaScript call to the window.open() + method includes "scrollbars", "scrollbars=1", or + "scrollbars=y". + + statusBarVisible + Specifies whether a status bar should be displayed.falseBoolean + Specifies whether a status bar should be displayed. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "status", "status=1", or "status=y". + + toolBarVisible + Specifies whether a toolbar bar should be displayed.falseBoolean + Specifies whether a toolbar bar should be displayed. This property is set to true if the + features string of the JavaScript call to the window.open() + method includes "toolbar", "toolbar=1", or "toolbar=y". + + width + Specifies the desired initial width of the new window.NaNNumber + Specifies the desired initial width of the new window. This is set to the width value + in the features string of the JavaScript call to the window.open() + method. If the value is NaN, the default when no width value is + specified in the features string, then a default window width is used. + + x + Specifies the desired initial x position of the new window on the screen.NaNNumber + Specifies the desired initial x position of the new window on the screen. This is set to the + value specified for left or screenX in the features + string of the JavaScript call to the window.open() method. If the value + is NaN, the default when no left or screenX value is + specified in the features string, then a default window x position is used. + + y + Specifies the desired initial y position of the new window on the screen.NaNNumber + Specifies the desired initial y position of the new window on the screen. This is set to the + value specified for top or screenY in the features + string of the JavaScript call to the window.open() method. If the value is + NaN, the default when no left or screenX value is specified + in the features string, then a default window x position is used. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.media.xml b/language-server/playerglobal_docs/flash.media.xml new file mode 100644 index 0000000..3ed52f6 --- /dev/null +++ b/language-server/playerglobal_docs/flash.media.xml @@ -0,0 +1,4687 @@ +flash.mediaID3Info + + The ID3Info class contains properties that reflect ID3 metadata.Object + The ID3Info class contains properties that reflect ID3 metadata. You can get additional + metadata for MP3 files by accessing the id3 + property of the Sound class; for example, mySound.id3.TIME. + For more information, see the entry for Sound.id3 and + the ID3 tag definitions at http://www.id3.org. + Sound.id3album + The name of the album; corresponds to the ID3 2.0 tag TALB.String + The name of the album; corresponds to the ID3 2.0 tag TALB. + artist + The name of the artist; corresponds to the ID3 2.0 tag TPE1.String + The name of the artist; corresponds to the ID3 2.0 tag TPE1. + comment + A comment about the recording; corresponds to the ID3 2.0 tag COMM.String + A comment about the recording; corresponds to the ID3 2.0 tag COMM. + genre + The genre of the song; corresponds to the ID3 2.0 tag TCON.String + The genre of the song; corresponds to the ID3 2.0 tag TCON. + songName + The name of the song; corresponds to the ID3 2.0 tag TIT2.String + The name of the song; corresponds to the ID3 2.0 tag TIT2. + track + The track number; corresponds to the ID3 2.0 tag TRCK.String + The track number; corresponds to the ID3 2.0 tag TRCK. + year + The year of the recording; corresponds to the ID3 2.0 tag TYER.String + The year of the recording; corresponds to the ID3 2.0 tag TYER. + MediaType + The MediaType class enumerates the general types of media that can be returned by a camera.Object + The MediaType class enumerates the general types of media that can be returned by a camera. + +

Use the constants defined in this class as input to the launch() method + of the CameraUI class. MediaType values are also used in the mediaType property + of the MediaPromise class.

+ +
CameraUI.launch()MediaPromise.mediaTypeIMAGE + A single image.imageString + A single image. + + VIDEO + A video.videoString + A video. + +
scanHardware + Forces a rescan of the microphones and cameras on the system. + Forces a rescan of the microphones and cameras on the system. + + Camera + Use the Camera class to capture video from the client system's camera.flash.events:EventDispatcher + Use the Camera class to capture video from the client system's camera. + Use the Video class to monitor the video locally. + Use the NetConnection and NetStream classes to transmit the video to Flash Media Server. + Flash Media Server can send the video stream to other servers and broadcast it to other clients running Flash Player. + +

A Camera instance captures video in landscape aspect ratio. On devices that can change the screen orientation, + such as mobile phones, a Video object attached to the camera will only show upright video in a landscape-aspect orientation. + Thus, mobile apps should use a landscape orientation when displaying video and should not auto-rotate.

+ +

As of AIR 2.6, autofocus is enabled automatically on mobile devices with an autofocus camera. If the camera does not support continuous autofocus, + and many mobile device cameras do not, then the camera is focused when the Camera object is attached to a video stream and whenever + the setMode() method is called. On desktop computers, autofocus behavior is dependent on the camera driver and settings.

+ +

In an AIR application on Android and iOS, the camera does not capture video while an AIR app is not the active, foreground application. + In addition, streaming connections can be lost when the application is in the background. On iOS, the camera video cannot be + displayed when an application uses the GPU rendering mode. The camera video can still be streamed to a server.

+ +

Mobile Browser Support: This class is not supported in mobile browsers.

+ +

AIR profile support: This feature is supported + on desktop operating systems, but it is not supported on all mobile devices. It is not + supported on AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

You can test + for support at run time using the Camera.isSupported property. + Note that for AIR for TV devices, Camera.isSupported is true but + Camera.getCamera() always returns null.

+ +

+ For information about capturing audio, see the Microphone class. +

+ +

+ Important: Flash Player displays a Privacy dialog box that lets the user choose whether + to allow or deny access to the camera. Make sure your application window size is at least 215 x 138 pixels; + this is the minimum size required to display the dialog box. +

+ +

To create or reference a Camera object, use the getCamera() method.

+ +
The following example shows the image from a camera after acknowledging the + security warning. The Stage is set such that it cannot be scaled and is aligned to the + top-left of the player window. The activity event is dispatched at the + start and end (if any) of the session and is captured by the activityHandler() + method, which prints out information about the event. + +

Note: A camera must be attached to your computer for this example + to work correctly.

+ + +package { + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.*; + import flash.media.Camera; + import flash.media.Video; + + public class CameraExample extends Sprite { + private var video:Video; + + public function CameraExample() { + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + + var camera:Camera = Camera.getCamera(); + + if (camera != null) { + camera.addEventListener(ActivityEvent.ACTIVITY, activityHandler); + video = new Video(camera.width * 2, camera.height * 2); + video.attachCamera(camera); + addChild(video); + } else { + trace("You need a camera."); + } + } + + private function activityHandler(event:ActivityEvent):void { + trace("activityHandler: " + event); + } + } +} +
flash.media.MicrophoneCristophe Coenraets: Video Chat for Android in 30 Lines of CodeMichael Chaize: Android, AIR, and the Camerastatus + Dispatched when a camera reports its status.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when a camera reports its status. + Before accessing a camera, Flash Player displays a Privacy dialog box to let users + allow or deny access to their camera. If the value of the code property is "Camera.Muted", + the user has refused to allow the SWF file access to the user's camera. + If the value of the code property is "Camera.Unmuted", + the user has allowed the SWF file access to the user's camera. + Camera.getCamera()activity + Dispatched when a camera begins or ends a session.flash.events.ActivityEvent.ACTIVITYflash.events.ActivityEvent + Dispatched when a camera begins or ends a session. + Call Camera.setMotionLevel() to specify the amount of motion + required to trigger an activity event with an activating + value of true, or the time without activity + that must elapse before triggering an activity event with an activating + value of false. + + + + getCamera + Returns a reference to a Camera object for capturing video.If the name parameter is not specified, this method returns a reference + to the default camera or, if it is in use by another application, to the first + available camera. (If there is more than one camera installed, the user may specify + the default camera in the Flash Player Camera Settings panel.) If no cameras are available + or installed, the method returns null. + + flash.media:CameranameStringnullSpecifies which camera to get, as determined from the array + returned by the names property. For most applications, get the default camera + by omitting this parameter. To specify a value for this parameter, use the string representation + of the zero-based index position within the Camera.names array. For example, to specify the third + camera in the array, use Camera.getCamera("2"). + + + Returns a reference to a Camera object for capturing video. To begin capturing + the video, you must attach the Camera object to a Video object (see Video.attachCamera() + ). To transmit video to Flash Media Server, call NetStream.attachCamera() + to attach the Camera object to a NetStream object. + +

Multiple calls to the getCamera() method reference the same camera driver. + Thus, if your code contains code like firstCam:Camera = getCamera() + and secondCam:Camera = getCamera(), + both firstCam and secondCam reference the same camera, + which is the user's default camera.

+ +

On iOS devices with a both a front- and a rear-facing camera, you can only capture + video from one camera at a time. On Android devices, you can only access the rear-facing camera.

+ +

In general, you shouldn't pass a value for the name parameter; simply use + getCamera() to return a reference to the default camera. By means of the Camera + settings panel (discussed later in this section), the user can specify the default camera + to use.

+ +

You can't use ActionScript to set a user's Allow or Deny permission setting + for access to the camera, but you can display the Adobe Flash Player Settings camera + setting dialog box where the user can set the camera permission. When a SWF file using + the attachCamera() method tries to + attach the camera returned by the getCamera() method to a Video or + NetStream object, Flash Player displays a dialog box that lets the user choose + to allow or deny access to the camera. (Make sure your application window size is at least + 215 x 138 pixels; this is the minimum size Flash Player requires to display the dialog box.) + When the user responds to the camera setting dialog box, Flash Player returns an + information object in the status event that indicates the user's response: + Camera.muted indicates + the user denied access to a camera; Camera.Unmuted indicates the user allowed access + to a camera. To determine whether the user has denied or allowed access to the camera without + handling the status event, use the muted property.

+ +

In Flash Player, the user can specify permanent privacy settings for a particular domain by right-clicking + (Windows and Linux) or Control-clicking (Macintosh) while a SWF file is playing, selecting Settings, + opening the Privacy dialog, and selecting Remember. If the user selects Remember, Flash Player no longer + asks the user whether to allow or deny SWF files from this domain access to your camera.

+ +

Note: The attachCamera() method will not invoke the dialog box + to Allow or Deny access to the camera if the user has denied access by selecting Remember + in the Flash Player Settings dialog box. In this case, you can prompt the user to change the + Allow or Deny setting by displaying the Flash Player Privacy panel for the user + using Security.showSettings(SecurityPanel.PRIVACY).

+ +

If getCamera() returns null, either the camera is in use by another + application, or there are no cameras installed on the system. To determine whether any cameras + are installed, use the names.length property. To display the Flash Player Camera Settings panel, + which lets the user choose the camera to be referenced by getCamera(), use + Security.showSettings(SecurityPanel.CAMERA).

+ +

Scanning the hardware for cameras takes time. When the runtime finds at least one camera, + the hardware is not scanned again for the lifetime of the player instance. However, if + the runtime doesn't find any cameras, it will scan each time getCamera is called. + This is helpful if the camera is present but is disabled; if your SWF file provides a + Try Again button that calls getCamera, Flash Player can find the camera without the + user having to restart the SWF file.

+ +
In the following example, after the user allows access to the camera, the attached + camera is used to capture video images. Information about the video stream, such as + the current frames per second, is also displayed. + +

The Camera.getCamera() method returns a reference to a camera object, or returns null if + no camera is available or installed. The if statement checks whether the camera was found and whether + the user allowed access to the camera. If the user denied access, the muted + property is set to true.

+ +

Usually, when the attachCamera() method is invoked, a dialog box appears and prompts the + user to allow or deny Flash Player access to the camera. However, if the user denied access + and selected the Remember option, the dialog box does not appear and nothing displays. + To make sure the user has the option to allow access to the camera, the myTextField text field + instructs the user to click the text field to invoke the Flash Player Settings dialog box.

+ +

The clickHandler() method calls Security.showSettings() method, which + displays the PRIVACY panel of the Settings dialog box. If the user allows access, + the StatusEvent.STATUS event is dispatched and the value of the event's code + property is set to Camera.Unmuted. (The camera object's mute property is also + set to false.)

+ +

The statusHandler() method, added to listen to the status change of the user's setting, + invokes the connectCamera() method, if the user allows access. The connectCamera() + method instantiates a video object with the captured stream's width and height. To display the + camera's captured video, the reference to the video stream is attached to the video object, and the video + object is added to the display list.

+ +

A Timer object also is started. Every second, a Timer object's timer event is dispatched and the + timerHandler() method is invoked. The timerHandler() method is displayed and updates + a number of properties of the Camera object.

+

Note: For this example, the only property that changes + is the currentFPS property.

+ + +package { + import flash.display.Sprite; + import flash.media.Camera; + import flash.media.Video; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.utils.Timer; + import flash.events.TimerEvent; + import flash.events.StatusEvent; + import flash.events.MouseEvent; + import flash.system.SecurityPanel; + import flash.system.Security; + + public class Camera_getCameraExample extends Sprite { + private var myTextField:TextField; + private var cam:Camera; + private var t:Timer = new Timer(1000); + + public function Camera_getCameraExample() { + myTextField = new TextField(); + myTextField.x = 10; + myTextField.y = 10; + myTextField.background = true; + myTextField.selectable = false; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + if (Camera.isSupported) + { + cam = Camera.getCamera(); + + if (!cam) { + myTextField.text = "No camera is installed."; + + } else if (cam.muted) { + myTextField.text = "To enable the use of the camera,\n" + + "please click on this text field.\n" + + "When the Flash Player Settings dialog appears,\n" + + "make sure to select the Allow radio button\n" + + "to grant access to your camera."; + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + }else { + myTextField.text = "Connecting"; + connectCamera(); + } + + addChild(myTextField); + + t.addEventListener(TimerEvent.TIMER, timerHandler); + }else { + myTextField.text = "The Camera class is not supported on this device."; + } + } + + private function clickHandler(e:MouseEvent):void { + Security.showSettings(SecurityPanel.PRIVACY); + + cam.addEventListener(StatusEvent.STATUS, statusHandler); + + myTextField.removeEventListener(MouseEvent.CLICK, clickHandler); + } + + private function statusHandler(event:StatusEvent):void { + + if (event.code == "Camera.Unmuted") { + connectCamera(); + cam.removeEventListener(StatusEvent.STATUS, statusHandler); + } + } + + private function connectCamera():void { + var vid:Video = new Video(cam.width, cam.height); + vid.x = 10; + vid.y = 10; + vid.attachCamera(cam); + addChild(vid); + + t.start(); + } + + private function timerHandler(event:TimerEvent):void { + myTextField.y = cam.height + 20; + myTextField.text = ""; + myTextField.appendText("bandwidth: " + cam.bandwidth + "\n"); + myTextField.appendText("currentFPS: " + Math.round(cam.currentFPS) + "\n"); + myTextField.appendText("fps: " + cam.fps + "\n"); + myTextField.appendText("keyFrameInterval: " + cam.keyFrameInterval + "\n"); + } + } +} +
indexmutednamessetMode()statusVideo.attachCamera()statusflash.events:StatusEventDispatched when a camera reports its status. + Before accessing a camera, Flash Player displays a Privacy dialog box to let users + allow or deny access to their camera. If the value of the code property is "Camera.muted", + the user has refused to allow the SWF file access to the user's camera. + If the value of the code property is "Camera.Unmuted", + the user has allowed the SWF file access to the user's camera. + Dispatched when a camera reports its status.
setKeyFrameInterval + Specifies which video frames are transmitted in full (called keyframes) + instead of being interpolated by the video compression algorithm.keyFrameIntervalintA value that specifies which video frames are transmitted in full + (as keyframes) instead of being interpolated by the video compression algorithm. + A value of 1 means that every frame is a keyframe, a value of 3 means that every third frame + is a keyframe, and so on. Acceptable values are 1 through 48. + + + Specifies which video frames are transmitted in full (called keyframes) + instead of being interpolated by the video compression algorithm. This method + is applicable only if you are transmitting video using Flash Media Server. + +

The Flash Video compression algorithm compresses video by transmitting + only what has changed since the last frame of the video; these portions are + considered to be interpolated frames. Frames of a video can be interpolated according + to the contents of the previous frame. A keyframe, however, is a video frame that + is complete; it is not interpolated from prior frames.

+ +

To determine how to set a value for the keyFrameInterval parameter, + consider both bandwidth use and video playback accessibility. For example, + specifying a higher value for keyFrameInterval (sending keyframes less frequently) + reduces bandwidth use. + However, this may increase the amount of time required to position the playhead + at a particular point in the video; more prior video frames may have to be interpolated + before the video can resume.

+ +

Conversely, specifying a lower value for keyFrameInterval + (sending keyframes more frequently) increases bandwidth use because entire video frames + are transmitted more often, but may decrease the amount of time required to seek a + particular video frame within a recorded video.

+ +
keyFrameInterval
setLoopback + Specifies whether to use a compressed video stream for a local view of the camera.compressBooleanfalseSpecifies whether to use a compressed video stream (true) + or an uncompressed stream (false) for a local view of what the camera + is receiving. + + Specifies whether to use a compressed video stream for a local view of the camera. + This method is applicable only if you are transmitting video using Flash Media Server; + setting compress to true lets you see more precisely how the video + will appear to users when they view it in real time. + +

Although a compressed stream is useful for testing purposes, such as previewing video + quality settings, it has a significant processing cost, because the local view is not + simply compressed; it is compressed, edited for transmission as it would be over a live + connection, and then decompressed for local viewing.

+ +

To set the amount of compression used when you set compress to true, + use Camera.setQuality().

+ +
setQuality()
setMode + Sets the camera capture mode to the native mode that best meets the specified requirements.widthintThe requested capture width, in pixels. The default value is 160. + heightintThe requested capture height, in pixels. The default value is 120. + fpsNumberThe requested rate at which the camera should capture data, in frames per second. + The default value is 15. + favorAreaBooleantrueSpecifies whether to manipulate the width, height, and frame rate if + the camera does not have a native mode that meets the specified requirements. + The default value is true, which means that maintaining capture size + is favored; using this parameter selects the mode that most closely matches + width and height values, even if doing so adversely affects + performance by reducing the frame rate. To maximize frame rate at the expense + of camera height and width, pass false for the favorArea parameter. + + + + Sets the camera capture mode to the native mode that best meets the specified requirements. + If the camera does not have a native mode that matches all the parameters you pass, + Flash Player selects a capture mode that most closely synthesizes the requested mode. + This manipulation may involve cropping the image and dropping frames. + +

By default, Flash Player drops frames as needed to maintain image size. To minimize the number + of dropped frames, even if this means reducing the size of the image, pass false + for the favorArea parameter.

+ +

When choosing a native mode, Flash Player tries to maintain the requested aspect ratio + whenever possible. For example, if you issue the command myCam.setMode(400, 400, 30), + and the maximum width and height values available on the camera are 320 and 288, Flash Player sets + both the width and height at 288; by setting these properties to the same value, Flash Player + maintains the 1:1 aspect ratio you requested.

+ +

To determine the values assigned to these properties after Flash Player selects the mode + that most closely matches your requested values, use the width, height, + and fps properties.

+ +

+ If you are using Flash Media Server, you can also capture single frames or create time-lapse + photography. For more information, see NetStream.attachCamera(). +

+ +
In the following example, when a user clicks on the Stage, the video + is resized and the frames per second capture rate is set to a new value. + +

The Stage is set so it does not scale. The Camera.getCamera() method + returns a reference to a camera object, or returns null if no camera is available or installed. + If a camera exists, the connectCamera() method is called. + The connectCamera() method instantiates a video object. To + display the camera's captured video, the reference to the video stream is attached + to the video object, and the video object is added to the display list. An event listener + also is set for a MouseEvent.CLICK event. After the user clicks on the Stage, + the clickHandler() method is invoked. The method checks the width of the + captured video and sets the camera capture mode's width, height, and the frame per second + request rate. In order for these setting to take effect, the video object must be removed + and re-created. The video's width and height also must be set to the camera object's width + and height.

+ + +package { + import flash.display.Sprite; + import flash.media.Camera; + import flash.media.Video; + import flash.events.MouseEvent; + import flash.display.StageScaleMode; + + public class Camera_setModeExample extends Sprite { + private var cam:Camera; + private var vid:Video; + + public function Camera_setModeExample() { + stage.scaleMode = StageScaleMode.NO_SCALE; + + cam = Camera.getCamera(); + + if (!cam) { + trace("No camera is installed."); + }else { + connectCamera(); + } + } + + private function connectCamera():void { + vid = new Video(); + vid.width = cam.width; + vid.height = cam.height; + vid.attachCamera(cam); + addChild(vid); + + stage.addEventListener(MouseEvent.CLICK, clickHandler); + } + + private function clickHandler(e:MouseEvent):void { + + switch (cam.width) { + case 160: + cam.setMode(320, 240, 10); + break; + case 320: + cam.setMode(640, 480, 5); + break; + default: + cam.setMode(160, 120, 15); + break; + } + + removeChild(vid); + connectCamera(); + } + } +} +
fpsheightwidthflash.net.NetStream.attachCamera()
setMotionLevel + Specifies how much motion is required to dispatch the activity event.motionLevelintSpecifies the amount of motion required to dispatch the + activity event. Acceptable values range from 0 to 100. The default value is 50. + + timeoutint2000Specifies how many milliseconds must elapse without activity + before Flash Player considers activity to have stopped and dispatches the activity event. + The default value is 2000 milliseconds (2 seconds). + + + Specifies how much motion is required to dispatch the activity event. + Optionally sets the number of milliseconds that must elapse without activity before + Flash Player considers motion to have stopped and dispatches the event. +

Note: Video can be displayed regardless of the value of the + motionLevel parameter. This parameter determines only when and under + what circumstances the event is dispatched—not whether video is actually being + captured or displayed.

+

+ To prevent the camera from detecting motion at all, pass a value of 100 for the + motionLevel parameter; the activity event is never dispatched. + (You would probably use this value only for testing purposes—for example, to + temporarily disable any handlers that would normally be triggered when the event is dispatched.) +

+

+ To determine the amount of motion the camera is currently detecting, use the + activityLevel property. + Motion sensitivity values correspond directly to activity values. + Complete lack of motion is an activity value of 0. Constant motion is an activity value of 100. + Your activity value is less than your motion sensitivity value when you're not moving; + when you are moving, activity values frequently exceed your motion sensitivity value. +

+

+ This method is similar in purpose to the Microphone.setSilenceLevel() method; + both methods are used to specify when the activity event + should be dispatched. However, these methods have a significantly different impact + on publishing streams: +

+ +
  • Microphone.setSilenceLevel() is designed to optimize bandwidth. + When an audio stream is considered silent, no audio data is sent. Instead, a single message + is sent, indicating that silence has started.
  • Camera.setMotionLevel() is designed to detect motion and does not affect + bandwidth usage. Even if a video stream does not detect motion, video is still sent.
+ + + +
In the following example, the user's camera is used as a monitor or + a surveillance camera. The camera detects motion and a text field shows + the activity level. (The example can be extended to sound an alarm or + send a message through a web service to other applications.) + +

The Camera.getCamera() method returns a reference to a camera object, + or returns null if no camera is available or installed. The if statement checks whether a camera + is available, and invokes the connectCamera() method when it is available. + The connectCamera() method instantiates a video object with the captured stream's + width and height. To display the camera's captured video, the reference to the + video stream is attached to the video object, and the video object is added to the display list. + (Usually, when the attachCamera() method is invoked, a dialog box appears and + prompts the user to allow or deny Flash Player access to the camera. However, if the + user denied access and selected the Remember option, the dialog box does not appear + and nothing is displayed. To make sure the user has the option to allow access to the camera, use the + system.Security.showSettings() method to invoke the Flash Player + Settings dialog box.)

+ +

The setMotionLevel() method sets the level of activity (amount of motion), before + the activity event is invoked, to five, for minimal motion. The time between when the camera stops + detecting motion and when the activity event is invoked, is set to 1 second (1000 millisecond). After 1 second + passes without activity or the level of activity reaches five, the ActivityEvent.ACTIVITY + event is dispatched and the activityHandler() method is invoked. If the event + was triggered by the level of activity, the activating property is set to + true and a Timer object is started. Every second, a Timer object’s timer event + is dispatched and the timerHandler() method is invoked, which displays the current + level of activity. (Although a level of five or larger triggers the timer, the displayed + current level of activity might be a smaller number.)

+ + +package { + import flash.display.Sprite; + import flash.media.Camera; + import flash.media.Video; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.utils.Timer; + import flash.events.TimerEvent; + import flash.events.ActivityEvent; + + public class Camera_setMotionLevelExample extends Sprite { + private var myTextField:TextField; + private var cam:Camera; + private var t:Timer = new Timer(1000); + + public function Camera_setMotionLevelExample() { + myTextField = new TextField(); + myTextField.background = true; + myTextField.selectable = false; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + cam = Camera.getCamera(); + + if (!cam) { + myTextField.text = "No camera is installed."; + + }else { + myTextField.text = "Waiting to connect."; + connectCamera(); + } + + addChild(myTextField); + + t.addEventListener(TimerEvent.TIMER, timerHandler); + } + + private function connectCamera():void { + var vid:Video = new Video(cam.width, cam.height); + vid.x = 10; + vid.y = 10; + vid.attachCamera(cam); + addChild(vid); + + cam.setMotionLevel(5, 1000); + cam.addEventListener(ActivityEvent.ACTIVITY, activityHandler); + } + + private function activityHandler(e:ActivityEvent):void { + if (e.activating == true) { + t.start(); + } else { + myTextField.text = "Everything is quiet."; + t.stop(); + } + } + + private function timerHandler(event:TimerEvent):void { + myTextField.x = 10; + myTextField.y = cam.height + 20; + myTextField.text = "There is some activity. Level: " + cam.activityLevel; + } + } +} +
motionLevelmotionTimeoutMicrophone.setSilenceLevel()
setQuality + Sets the maximum amount of bandwidth per second or the required picture quality + of the current outgoing video feed.bandwidthintSpecifies the maximum amount of bandwidth that the current outgoing video + feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth + as needed to maintain the value of quality, pass 0 for + bandwidth. The default value is 16384. + + qualityintAn integer that specifies the required level of picture quality, + as determined by the amount of compression being applied to each video frame. + Acceptable values range from 1 (lowest quality, maximum compression) to 100 (highest + quality, no compression). To specify that picture quality can vary as needed to avoid + exceeding bandwidth, pass 0 for quality. + + + Sets the maximum amount of bandwidth per second or the required picture quality + of the current outgoing video feed. This method is generally applicable only if + you are transmitting video using Flash Media Server. + +

Use this method to specify which element of the outgoing video feed is more + important to your application—bandwidth use or picture quality.

+ +
  • To indicate that bandwidth use takes precedence, pass a value for bandwidth + and 0 for quality. Flash Player transmits video at the highest quality + possible within the specified bandwidth. If necessary, Flash Player reduces picture + quality to avoid exceeding the specified bandwidth. In general, as motion increases, + quality decreases.
  • To indicate that quality takes precedence, pass 0 for bandwidth + and a numeric value for quality. Flash Player uses as much bandwidth + as required to maintain the specified quality. If necessary, Flash Player reduces the frame + rate to maintain picture quality. In general, as motion increases, bandwidth use also + increases.
  • To specify that both bandwidth and quality are equally important, pass numeric + values for both parameters. Flash Player transmits video that achieves the specified quality + and that doesn't exceed the specified bandwidth. If necessary, Flash Player reduces the + frame rate to maintain picture quality without exceeding the specified bandwidth.
+ +
getCamera()quality
activityLevel + The amount of motion the camera is detecting.Number + The amount of motion the camera is detecting. Values range from 0 (no motion is being detected) to + 100 (a large amount of motion is being detected). The value of this property can help you determine if you need to pass a setting + to the setMotionLevel() method. +

If the camera is available but is not yet being used because the + Video.attachCamera() method has not been called, this property + is set to -1.

+

If you are streaming only uncompressed local video, this property is set only if you have assigned a function to the event + handler. Otherwise, it is undefined.

+ +
motionLevelsetMotionLevel()
bandwidth + The maximum amount of bandwidth the current outgoing video feed can use, in bytes.int + The maximum amount of bandwidth the current outgoing video feed can use, in bytes. + A value of 0 means the feed can use as much bandwidth as needed to maintain the desired frame quality. +

To set this property, use the setQuality() method.

+ +
setQuality()
currentFPS + The rate at which the camera is capturing data, in frames per second.Number + The rate at which the camera is capturing data, in frames per second. + This property cannot be set; however, you can use the setMode() method + to set a related property—fps—which specifies the maximum + frame rate at which you would like the camera to capture data. + + setMode()fps + The maximum rate at which the camera can capture data, in frames per second.Number + The maximum rate at which the camera can capture data, in frames per second. + The maximum rate possible depends on the capabilities of the camera; this frame rate may not be achieved. +
  • To set a desired value for this property, use the setMode() method.
  • To determine the rate at which the camera is currently capturing data, use the currentFPS property.
+ +
currentFPSsetMode()
height + The current capture height, in pixels.int + The current capture height, in pixels. To set a value for this property, + use the setMode() method. + + widthsetMode()index + A zero-based integer that specifies the index of the camera, as reflected in + the array returned by the names property.int + A zero-based integer that specifies the index of the camera, as reflected in + the array returned by the names property. + + namesgetCamera()isSupported + The isSupported property is set to true if the + Camera class is supported on the current platform, otherwise it is + set to false.Boolean + The isSupported property is set to true if the + Camera class is supported on the current platform, otherwise it is + set to false. + + keyFrameInterval + The number of video frames transmitted in full (called keyframes) + instead of being interpolated by the video compression algorithm.int + The number of video frames transmitted in full (called keyframes) + instead of being interpolated by the video compression algorithm. + The default value is 15, which means that every 15th frame is a keyframe. + A value of 1 means that every frame is a keyframe. The allowed values are + 1 through 48. + + setKeyFrameInterval()loopback + Indicates whether a local view of what the camera is capturing is compressed + and decompressed (true), as it would be for live transmission using + Flash Media Server, or uncompressed (false).Boolean + Indicates whether a local view of what the camera is capturing is compressed + and decompressed (true), as it would be for live transmission using + Flash Media Server, or uncompressed (false). The default value is + false. + +

+ Although a compressed stream is useful for testing, such as when previewing + video quality settings, it has a significant processing cost. The local view + is compressed, edited for transmission as it would be over a live connection, + and then decompressed for local viewing. +

+ +

To set this value, use Camera.setLoopback(). To set the amount of + compression used when this property is true, use Camera.setQuality().

+ +
setLoopback()setQuality()
motionLevel + The amount of motion required to invoke the activity event.int + The amount of motion required to invoke the activity event. Acceptable values range from 0 to 100. + The default value is 50. +

Video can be displayed regardless of the value of the motionLevel property. For more information, see + setMotionLevel().

+ +
setMotionLevel()
motionTimeout + The number of milliseconds between the time the camera stops detecting motion and the time the activity event is invoked.int + The number of milliseconds between the time the camera stops detecting motion and the time the activity event is invoked. The + default value is 2000 (2 seconds). +

To set this value, use setMotionLevel().

+ +
setMotionLevel()
muted + A Boolean value indicating whether the user has denied access to the camera + (true) or allowed access (false) in the Flash Player Privacy dialog box.Boolean + A Boolean value indicating whether the user has denied access to the camera + (true) or allowed access (false) in the Flash Player Privacy dialog box. + + When this value changes, the statusevent is dispatched. + + getCamera()statusname + The name of the current camera, as returned by the camera hardware.String + The name of the current camera, as returned by the camera hardware. + + namesgetCamera()names + An array of strings indicating the names of all available cameras + without displaying the Flash Player Privacy dialog box.Array + An array of strings indicating the names of all available cameras + without displaying the Flash Player Privacy dialog box. This array behaves in the + same way as any other ActionScript array, implicitly providing the zero-based + index of each camera and the number of cameras on the system (by means of + names.length). For more information, see the names Array class entry. + +

Calling the names property requires an extensive examination of the hardware. + In most cases, you can just use the default camera.

+ +

On Android, only one camera is supported, even if the device has more than one camera devices. The + name of the camera is always, "Default."

+ +
getCamera()indexname
quality + The required level of picture quality, as determined by the amount of compression being applied to each video + frame.int + The required level of picture quality, as determined by the amount of compression being applied to each video + frame. Acceptable quality values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). The + default value is 0, which means that picture quality can vary as needed to avoid exceeding available bandwidth. + +

To set this property, use the setQuality() method.

+
setQuality()
width + The current capture width, in pixels.int + The current capture width, in pixels. To set a desired value for this property, + use the setMode() method. + + setMode()
SoundTransform + The SoundTransform class contains properties for volume and panning.Object + The SoundTransform class contains properties for volume and panning. + + The following example loads and plays an MP3 file. As the MP3 file plays, + move the mouse or other user input device; the + volume and panning change as you move the user input device over the Stage. + To run this example, place a file named MySound.mp3 in the same directory as your SWF file. + +package { + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.*; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.media.SoundTransform; + import flash.net.URLRequest; + import flash.utils.Timer; + + public class SoundTransformExample extends Sprite { + private var url:String = "MySound.mp3"; + private var soundFactory:Sound; + private var channel:SoundChannel; + private var positionTimer:Timer; + + public function SoundTransformExample() { + stage.align = StageAlign.TOP_LEFT; + stage.scaleMode = StageScaleMode.NO_SCALE; + + var request:URLRequest = new URLRequest(url); + soundFactory = new Sound(); + soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + soundFactory.load(request); + channel = soundFactory.play(); + stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function ioErrorHandler(event:Event):void { + trace("ioErrorHandler: " + event); + } + + private function setPan(pan:Number):void { + trace("setPan: " + pan.toFixed(2)); + var transform:SoundTransform = channel.soundTransform; + transform.pan = pan; + channel.soundTransform = transform; + } + + private function setVolume(volume:Number):void { + trace("setVolume: " + volume.toFixed(2)); + var transform:SoundTransform = channel.soundTransform; + transform.volume = volume; + channel.soundTransform = transform; + } + + private function mouseMoveHandler(event:MouseEvent):void { + var halfStage:uint = Math.floor(stage.stageWidth / 2); + var xPos:uint = event.stageX; + var yPos:uint = event.stageY; + var value:Number; + var pan:Number; + + if (xPos > halfStage) { + value = xPos / halfStage; + pan = value - 1; + } else if (xPos < halfStage) { + value = (xPos - halfStage) / halfStage; + pan = value; + } else { + pan = 0; + } + + var volume:Number = 1 - (yPos / stage.stageHeight); + + setVolume(volume); + setPan(pan); + + } + } +} +flash.display.SimpleButton.soundTransformflash.display.Sprite.soundTransformflash.media.Microphone.soundTransformflash.media.SoundChannel.soundTransformflash.media.SoundMixer.soundTransformflash.net.NetStream.soundTransformSoundTransform + Creates a SoundTransform object.volNumber1The volume, ranging from 0 (silent) to 1 (full volume). + + panningNumber0The left-to-right panning of the sound, ranging from -1 (full pan left) + to 1 (full pan right). A value of 0 represents no panning (center). + + + + Creates a SoundTransform object. + + In the following example, the sound plays only from the + right channel, and the volume is set to 50 percent. + +

In the constructor, the sound is loaded and is assigned to a sound channel + (channel). A SoundTranform object (transform) is also + created. Its first argument sets the volume at 50 percent (the range is 0.0 + to 1.0). Its second argument sets the panning. In this example, panning is set to 1.0, which means + the sound comes from the right speaker only. In order for these settings to + take effect, the transform SoundTranform object is + assigned to the sound channel's souundTransform property.

+

Note: There is + limited error handling written for this example.

+ + +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.media.SoundTransform; + import flash.events.IOErrorEvent; + + public class SoundTransform_constructorExample extends Sprite + { + public function SoundTransform_constructorExample() { + var mySound:Sound = new Sound(); + var url:URLRequest = new URLRequest("mySound.mp3"); + var channel:SoundChannel; + var transform:SoundTransform = new SoundTransform(0.5, 1.0); + + mySound.load(url); + channel = mySound.play(); + channel.soundTransform = transform; + + mySound.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + trace("The sound could not be loaded: " + errorEvent.text); + } + } +} +
leftToLeft + A value, from 0 (none) to 1 (all), specifying how much of the left input is played in the + left speaker.Number + A value, from 0 (none) to 1 (all), specifying how much of the left input is played in the + left speaker. + + leftToRight + A value, from 0 (none) to 1 (all), specifying how much of the left input is played in the + right speaker.Number + A value, from 0 (none) to 1 (all), specifying how much of the left input is played in the + right speaker. + + pan + The left-to-right panning of the sound, ranging from -1 (full pan left) + to 1 (full pan right).Number + The left-to-right panning of the sound, ranging from -1 (full pan left) + to 1 (full pan right). A value of 0 represents no panning (balanced center between + right and left). + + rightToLeft + A value, from 0 (none) to 1 (all), specifying how much of the right input is played in the + left speaker.Number + A value, from 0 (none) to 1 (all), specifying how much of the right input is played in the + left speaker. + + rightToRight + A value, from 0 (none) to 1 (all), specifying how much of the right input is played in the + right speaker.Number + A value, from 0 (none) to 1 (all), specifying how much of the right input is played in the + right speaker. + + volume + The volume, ranging from 0 (silent) to 1 (full volume).Number + The volume, ranging from 0 (silent) to 1 (full volume). + +
StageVideoAvailability + This class defines an enumeration that indicates whether stage video is currently available.An enumeration that indicates whether stage video is currently available. + Object + This class defines an enumeration that indicates whether stage video is currently available. + flash.events.StageVideoAvailabilityEventAVAILABLE + Stage video is currently available.availableStringStage video is currently available. + + Stage video is currently available. + UNAVAILABLE + Stage video is not currently available.unavailableStringStage video is not currently available. + + Stage video is not currently available. + StageWebView + The StageWebView class displays HTML content in a stage view port.flash.events:EventDispatcher + The StageWebView class displays HTML content in a stage view port. + +

The StageWebView class provides a simple means to display HTML content on + devices where the HTMLLoader class is not supported. The class provides no + interaction between ActionScript and the HTML content except through + the methods and properties of the StageWebView class itself. There is, for example, + no way to pass values or call functions between ActionScript and JavaScript.

+ +

AIR profile support: This feature is supported + on all desktop operating systems and mobile devices, but is not supported on AIR for TV devices. You can test + for support at run time using the StageWebView.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

On devices in the mobile and extended mobile profiles, the StageWebView class uses + the system web control provided by the device operating system. Thus, the available + features and rendering appearance may vary from device to device. On desktop computers (in the + desktop and extended desktop profiles), the StageWebView class uses the internal AIR + WebKit engine. The features available and rendering appearance are the same as those of the + HTMLLoader class (without the close integration and script bridging between ActionScript and + JavaScript provided by an HTMLLoader instance). Test the isSupported property + of the StageWebView class to determine whether the class is supported on the current device.

+ +

The StageWebView class is NOT a display object and cannot be added to the Flash display list. + Instead you display a StageWebView object by attaching it directly to a stage using the + stage property. The StageWebView instance attached to a stage is displayed on top + of any Flash display objects. You control the size and position of the rendering area with the + viewPort property. There is no way to control the depth ordering of different + StageWebView objects. Overlapping two instances is not recommended.

+ +

When the content within the StageWebView object has focus, the StageWebView object has the first + opportunity to handle keyboard input. The stage to which the StageWebView object is attached + dispatches any keyboard input that is not handled. The normal event capture/bubble cycle does not + apply here since the StageWebView instance is not part of the display list.

+ +

In Android 3.0+, an application must enable hardware acceleration in the Android manifestAdditions + element of the AIR application descriptor to display plug-in content in a StageWebView object.

+ +
The following example sets up a StageWebView object to fill the stage. The example + loads a web site with the loadURL() method and uses the device Back and Search + softkeys for history navigation. + +package { + import flash.display.MovieClip; + import flash.media.StageWebView; + import flash.geom.Rectangle; + import flash.events.KeyboardEvent; + import flash.ui.Keyboard; + import flash.desktop.NativeApplication; + + public class StageWebViewExample extends MovieClip{ + + private var webView:StageWebView = new StageWebView(); + + public function StageWebViewExample() + { + webView.stage = this.stage; + webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight ); + webView.loadURL( "http://www.example.com" ); + + stage.addEventListener( KeyboardEvent.KEY_DOWN, onKey ); + } + + private function onKey( event:KeyboardEvent ):void + { + if( event.keyCode == Keyboard.BACK && webView.isHistoryBackEnabled ) + { + trace("Back."); + webView.historyBack(); + event.preventDefault(); + } + + if( event.keyCode == Keyboard.SEARCH && webView.isHistoryForwardEnabled ) + { + trace("Forward."); + webView.historyForward(); + } + } + } +} +
HTMLLoader classMark Doherty: AIR on Android: TweetrAppMark Doherty: OAuth SupportEnabling Flash Player and other plug-ins in a StageWebView objectfocusOut + Dispatched when the StageWebView relinquishes focus.flash.events.FocusEvent + Dispatched when the StageWebView relinquishes focus. + + focusIn + Dispatched when this StageWebView object receives focus.flash.events.FocusEvent + Dispatched when this StageWebView object receives focus. + + error + Signals that an error has occurred.flash.events.ErrorEvent + Signals that an error has occurred. + + complete + Signals that the last load operation requested by loadString() or + loadURL() method has completed.flash.events.Event.COMPLETEflash.events.EventSignals that the last load operation requested by loadString() or + load() method has completed. + + + Signals that the last load operation requested by loadString() or + loadURL() method has completed. + + locationChanging + Signals that the location property of the StageWebView object is about to change.flash.events.LocationChangeEvent.LOCATION_CHANGINGflash.events.LocationChangeEventSignals that the location property of the StageWebView object is about to change. + + + Signals that the location property of the StageWebView object is about to change. + +

A locationChanging event is only dispatched when the location change is initiated through + HTML content or code running inside the StageWebView object,such as when a user clicks a link. + By default, the new location is displayed in this + StageWebView object. You can call the preventDefault() method of the event + object to cancel the default behavior. For example, you could use the flash.net.navigateToURL() + function to open the page in the system browser based on the location + property of the event object

+ +

A locationChanging event is not dispatched when you change the location with the following methods:

+
  • historyBack()
  • historyForward()
  • historyGo()
  • loadString()
  • loadURL()
  • reload()
+ +
locationChange + Signals that the location property of the StageWebView object has changed.flash.events.LocationChangeEvent.LOCATION_CHANGEflash.events.LocationChangeEventSignals that the location property of the StageWebView object has changed. + + + Signals that the location property of the StageWebView object has changed. + +

The event cannot be canceled.

+ +
StageWebView + Creates a StageWebView object. + Creates a StageWebView object. + +

The object is invisible until it is attached to a stage and until the viewPort + is set.

+ +
assignFocus + Assigns focus to the content within this StageWebView object.directionStringnonespecifies whether the first or last focusable object + in the displayed content should receive focus. + + + Assigns focus to the content within this StageWebView object. + +

Direction values are defined in FocusDirection class and include: + "bottom", "none", and "top".

+ +
FocusDirection
dispose + Disposes of this StageWebView object. + Disposes of this StageWebView object. + +

Calling dispose() is optional. If you do not maintain a reference to this + StageWebView instance it will be eligible for garbage collection. Calling dispose() + can make garbage collection occur sooner, or at a more convenient time.

+ +
drawViewPortToBitmapData + Draws the StageWebView's view port to a bitmap. The bitmap's width or height is different from view port's width or height. + ArgumentErrorArgumentErrorThe bitmap is null. + ErrorErrorbitmapflash.display:BitmapDataThe BitmapData object on which to draw the visible portion of the StageWebView's view port. + + Draws the StageWebView's view port to a bitmap. +

Capture the bitmap and set the stage to null for displaying the content above the StageWebView object.

+ +
The following example displays two labels: google and facebook. + Clicking on the label captures the corresponding web page and displays it as a snapshot on the stage. + + +package +{ + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.display.Sprite; + import flash.events.*; + import flash.geom.Rectangle; + import flash.media.StageWebView; + import flash.net.*; + import flash.text.TextField; + + public class stagewebview1 extends Sprite + { + public var webView:StageWebView = new StageWebView(); + public var textGoogle:TextField=new TextField(); + public var textFacebook:TextField=new TextField(); + + public function stagewebview() + + { + textGoogle.htmlText="<b>Google</b>"; + textGoogle.x=300; + textGoogle.y=-80; + addChild(textGoogle); + textFacebook.htmlText="<b>Facebook</b>"; + textFacebook.x=0; + textFacebook.y=-80; + addChild(textFacebook); + textGoogle.addEventListener(MouseEvent.CLICK,goGoogle); + textFacebook.addEventListener(MouseEvent.CLICK,goFaceBook); + webView.stage = this.stage; + webView.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); + + } + + public function goGoogle(e:Event):void + + { + webView.loadURL("http://www.google.com"); + webView.stage = null; + webView.addEventListener(Event.COMPLETE,handleLoad); + } + + public function goFaceBook(e:Event):void + { + webView.loadURL("http://www.facebook.com"); + webView.stage = null; + webView.addEventListener(Event.COMPLETE,handleLoad); + } + + public function handleLoad(e:Event):void + { + var bitmapData:BitmapData = new BitmapData(webView.viewPort.width, webView.viewPort.height); + webView.drawViewPortToBitmapData(bitmapData); + var webViewBitmap:Bitmap=new Bitmap(bitmapData); + addChild(webViewBitmap); + } + } +} +
historyBack + Navigates to the previous page in the browsing history. + Navigates to the previous page in the browsing history. + + historyForward + Navigates to the next page in the browsing history. + Navigates to the next page in the browsing history. + + loadString + Loads and displays the specified HTML string.textStringthe string of HTML or XHTML content to display. + mimeTypeStringtext/htmlThe MIME type of the content, either "text/html" or "application/xhtml+xml". + + + Loads and displays the specified HTML string. + +

When the loadString() method is used, the location + is reported as "about:blank." Only standard URI schemes can be used in URLs within + the HTML string. The AIR URI schemes, "app:" and "app-storage:" are not allowed.

+ +

The HTML content cannot load local resources, such as image files. XMLHttpRequests + are not allowed.

+ +

Only the "text/html" and "application/xhtml+xml" MIME types are supported.

+ +
The following example sets up a StageWebView object to fill the stage. The example + loads an HTML page with the loadString() method. + + +var webView:StageWebView = new StageWebView(); +webView.stage = this.stage; +webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight ); + +var htmlString:String = "<!DOCTYPE HTML>" + + "<html>" + + "<body>" + + "<h1>Example</h1>" + + "<p>King Phillip cut open five green snakes.</p>" + + "</body>" + + "</html>"; + +webView.loadString( htmlString, "text/html" ); +
loadURL + Loads the page at the specified URL.urlString + Loads the page at the specified URL. + +

The URL can use the following URI schemes: http:, https:, file:, data:, and javascript:. + Content loaded with the file: scheme can load other local resources.

+ +
The following example sets up a StageWebView object to fill the stage. The example + loads a web site with the loadURL() method. + +

Note: On Android, you must specify the INTERNET permission in your AIR application + descriptor to load remote URLs.

+ + +var webView:StageWebView = new StageWebView(); +webView.stage = this.stage; +webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight ); + +webView.loadURL( "http://www.example.com" ); + +
reload + Reloads the current page. + Reloads the current page. + + stop + Halts the current load operation. + Halts the current load operation. + + isHistoryBackEnabled + Reports whether there is a previous page in the browsing history.Boolean + Reports whether there is a previous page in the browsing history. + + isHistoryForwardEnabled + Reports whether there is a next page in the browsing history.Boolean + Reports whether there is a next page in the browsing history. + + isSupported + Reports whether the StageWebView class is supported on the current device.Boolean + Reports whether the StageWebView class is supported on the current device. + + location + The URL of the current location.String + The URL of the current location. + + stage + The stage on which this StageWebView object is displayed.flash.display:Stage + The stage on which this StageWebView object is displayed. + +

Set stage to null to hide this StageWebView object.

+ +
title + The HTML title value.String + The HTML title value. + + viewPort + The area on the stage in which the StageWebView object is displayed.flash.geom:RectangleThe Rectangle value is not valid. + RangeErrorRangeError + The area on the stage in which the StageWebView object is displayed. + +
VideoStatus + This class defines an enumeration that describes possible levels of video decoding.An enumeration that describes possible levels of video decoding. + Object + This class defines an enumeration that describes possible levels of video decoding. + ACCELERATED + Indicates hardware-accelerated (GPU) video decoding.acceleratedStringIndicates hardware-accelerated (GPU) video decoding. + + Indicates hardware-accelerated (GPU) video decoding. + SOFTWARE + Indicates software video decoding.softwareStringIndicates software video decoding. + + Indicates software video decoding. + UNAVAILABLE + Video decoding is not supported.unavailableStringVideo is not supported. + + Video decoding is not supported. + MediaPromise + The MediaPromise class represents the promise to deliver a media object.flash.desktop:IFilePromiseflash.events:EventDispatcher + The MediaPromise class represents the promise to deliver a media object. + +

The data property of a MediaEvent object is a MediaPromise + instance. You can use the MediaPromise methods to access the promised media + object. Supported media formats include still images and video.

+ +

You cannot create a MediaPromise object. Calling new MediaPromise() + generates a run-time error.

+ +
MediaEventIFilePromiseLoader.LoadFilePromise()IDataInputCameraRoll.browseForImage()CameraUIcomplete + A MediaPromise object dispatches a complete event when all data has been read.flash.events.Event.COMPLETEflash.events.Event + A MediaPromise object dispatches a complete event when all data has been read. + The event indicates that there is no more data available in the underlying stream. + +

A complete event is not dispatched by a synchronous data source.

+ +
progress + A MediaPromise object dispatches progress events as the data becomes available.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + A MediaPromise object dispatches progress events as the data becomes available. + +

The bytesTotal property of all progress events except the last has the value 0. + If all the data is available immediately, no progress events may be dispatched. + No progress events are dispatched by synchronous data sources.

+ +
ioError + A MediaPromise object dispatches an ioError event when an error is encountered while reading + the underlying data stream.flash.events.IOErrorEvent.IOERRORflash.events.IOErrorEvent + A MediaPromise object dispatches an ioError event when an error is encountered while reading + the underlying data stream. No more data can be read after this event is dispatched. + + close + A MediaPromise object dispatches a close event when the underlying data stream has closed.flash.events.Event.CLOSEflash.events.Event + A MediaPromise object dispatches a close event when the underlying data stream has closed. + + close + Closes the data source. + Closes the data source. + + open + Opens the underlying data source and returns the IDataInput instance allowing you to read it.flash.utils:IDataInput + Opens the underlying data source and returns the IDataInput instance allowing you to read it. + +

If the underlying data source is asynchronous, then the MediaPromise object dispatches + progress and complete events to indicate whether data is available + to be read. If the data source is synchronous, all data is available immediately and these + events are not dispatched.

+ +

Note: You can load a MediaPromise object using the loadFilePromise() + method of the Loader class instead of reading the data manually.

+ +
Loader.loadFilePromise()
reportError + Used by the runtime to report errors.eflash.events:ErrorEventthe error vent to dispatch. + + Used by the runtime to report errors. + +

Application code should not call this method.

+ +
file + The File instance representing the media object, if one exists.flash.filesystem:File + The File instance representing the media object, if one exists. + +

This property references a File object if the underlying data source is file-based and the + file is accessible to your application. + Otherwise, the property is null.

+ +
isAsync + Reports whether the underlying data source is asynchronous or synchronous.Boolean + Reports whether the underlying data source is asynchronous or synchronous. + +

+ + mediaType + The general type of media, either image or video.String + The general type of media, either image or video. + +

The constants in the MediaType class define possible values of this property:

+
  • MediaType.IMAGE
  • MediaType.VIDEO
+ +
MediaType
relativePath + The file name of the media object, if one exists.String + The file name of the media object, if one exists. + +

A file name is available if the underlying data source is file-based and the + file is accessible to your application. + Otherwise, the property is null.

+ +
SoundLoaderContext + The SoundLoaderContext class provides security checks for files that load sound.Object + The SoundLoaderContext class provides security checks for files that load sound. + SoundLoaderContext objects are passed as an argument to the constructor and the + load() method of the Sound class. + +

When you use this class, consider the following security model:

+ +
  • Loading and playing a sound is not allowed if the calling file is in a network sandbox + and the sound file to be loaded is local.
  • By default, loading and playing a sound is not allowed if the calling is local and + tries to load and play a remote sound. A user must grant explicit permission to allow this.
  • Certain operations dealing with sound are restricted. The data in a loaded sound cannot + be accessed by a file in a different domain unless you implement a URL policy file. + Sound-related APIs that fall under this restriction are the Sound.id3 property and the + SoundMixer.computeSpectrum(), SoundMixer.bufferTime, + and SoundTransform() methods.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
SoundLoaderContext + Creates a new sound loader context object.bufferTimeNumber1000The number of seconds to preload a streaming sound into a buffer + before the sound starts to stream. + + checkPolicyFileBooleanfalseSpecifies whether the existence of a URL policy file + should be checked upon loading the object (true) or not. + + + Creates a new sound loader context object. + + In the following example, the buffer for the sound that will be loaded + is set to three seconds. + +

The first parameter of a SoundLoaderContext object (context) is used to increase + the default buffer value of one second to three seconds. (The value is in milliseconds.) + If the second parameter of the SoundLoaderContext object is set to true, + Flash Player will check for a cross-domain policy file upon loading the object. Here it is + set to the default value false, so no policy file will be checked. + The load() method of the sound object will use the context setting to make sure + it will take three seconds to preload the streaming sound into a buffer before the sound starts + to stream. The URLRequest object determines the location of the file, which is a + podcast from Adobe. If an IOErrorEvent.IO_ERROR error occurs during the loading + of the sound file, the errorHandler() method is invoked.

+ +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.media.SoundLoaderContext; + import flash.events.IOErrorEvent; + + public class SoundLoaderContextExample extends Sprite { + + public function SoundLoaderContextExample() { + var snd:Sound = new Sound(); + var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); + var context:SoundLoaderContext = new SoundLoaderContext(3000, false); + + snd.load(req, context); + snd.play(); + + snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + trace("The sound could not be loaded: " + errorEvent.text); + } + + } +} +
bufferTime + The number of milliseconds to preload a streaming sound into a buffer + before the sound starts to stream.1000Number + The number of milliseconds to preload a streaming sound into a buffer + before the sound starts to stream. + +

Note that you cannot override the value of SoundLoaderContext.bufferTime + by setting the global SoundMixer.bufferTime property. + The SoundMixer.bufferTime property affects the buffer time + for embedded streaming sounds in a SWF file and is independent of dynamically created + Sound objects (that is, Sound objects created in ActionScript).

+ +
checkPolicyFile + Specifies whether the application should try to download a URL policy file from the + loaded sound's server before beginning to load the sound.falseBoolean + Specifies whether the application should try to download a URL policy file from the + loaded sound's server before beginning to load the sound. This property applies to + sound that is loaded from outside + the calling file's own domain using the Sound.load() method. + + + +

Set this property to true when you load a sound from outside the + calling file's own domain and code in the calling file needs low-level access to + the sound's data. Examples of low-level access to a sound's data + include referencing the Sound.id3 property to get an + ID3Info object or calling the SoundMixer.computeSpectrum() method to get + sound samples from the loaded sound. If you try to access sound data without + setting the checkPolicyFile property to true at loading time, + you may get a SecurityError exception because the required policy file has not been downloaded.

+ +

If you don't need low-level access to the sound data that you are loading, avoid setting + checkPolicyFile to true. Checking for a policy file consumes + network bandwidth + and might delay the start of your download, so it should only be done when necessary.

+ +

When you call Sound.load() with SoundLoaderContext.checkPolicyFile set + to true, Flash Player or AIR must + either successfully download a relevant URL policy file or determine that no such policy file + exists before it begins downloading the specified sound. + Flash Player or AIR performs the following + actions, in this order, to verify the existence of a policy file:

+ +
  • Flash Player or AIR considers policy files that have already been downloaded.
  • Flash Player or AIR tries to download any pending policy files specified in calls to + Security.loadPolicyFile().
  • Flash Player or AIR tries to download a + policy file from the default location that corresponds to the sound's URL, which is + /crossdomain.xml on the same server as URLRequest.url. + (The sound's URL is specified in the url property of the URLRequest object + passed to Sound.load() or the Sound() constructor function.)
+ +

In all cases, Flash Player or AIR + requires that an appropriate policy file exist on the sound's server, that it provide access + to the sound file at URLRequest.url by virtue of the policy file's location, and + that it allow the domain of the calling file to access the sound, through one or more + <allow-access-from> tags. +

+ +

If you set checkPolicyFile to true, + Flash Player or AIR waits until the policy file is verified + before loading the sound. You should wait to perform + any low-level operations on the sound data, such as calling Sound.id3 or + SoundMixer.computeSpectrum(), until progress and complete + events are dispatched from the Sound object. +

+ +

If you set checkPolicyFile to true but no appropriate policy file is found, + you will not receive an error until you perform an operation that requires + a policy file, and then Flash Player or AIR throws a + SecurityError exception. After you receive a complete + event, you can test whether a relevant policy file was found by getting the value + of Sound.id3 within a try block and seeing if a + SecurityError is thrown.

+ + +

Be careful with checkPolicyFile if you are downloading sound from a URL that + uses server-side HTTP redirects. Flash Player or AIR tries to retrieve policy files that + correspond to the url property of the URLRequest object + passed to Sound.load(). If the final + sound file comes from a different URL because of HTTP redirects, then the initially downloaded + policy files might not be applicable to the sound's final URL, which is the URL that matters + in security decisions.

+ +

If you find yourself in this situation, here is one possible solution. + After you receive a progress or complete event, you can examine the value of + the Sound.url property, which contains the sound's final URL. + Then call the Security.loadPolicyFile() method + with a policy file URL that you calculate based on the sound's final URL. Finally, poll the value + of Sound.id3 until no exception is thrown.

+ +

This does not apply to content in the AIR application sandbox. + Content in the application sandbox always has programatic access to sound content, regardless + of its origin.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ + +
flash.media.Sound.load()flash.media.Sound.id3flash.media.SoundMixer.computeSpectrum()flash.media.Sound.urlflash.system.Security.loadPolicyFile()
SoundChannel + The SoundChannel class controls a sound in an application.flash.events:EventDispatcher + The SoundChannel class controls a sound in an application. Every sound + is assigned to a sound channel, and the application can have multiple + sound channels that are mixed together. The SoundChannel class contains a stop() method, + properties for monitoring the amplitude (volume) of the channel, and a property for assigning a + SoundTransform object to the channel. + + The following example loads an MP3 file, plays it, and displays + information about sound events that take place as the MP3 file is loaded and played. A Timer + object provides updated information about the position of the playhead every 50 milliseconds. + To run this example, place a file named MySound.mp3 in the same directory as your SWF file. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.net.URLRequest; + import flash.utils.Timer; + + public class SoundChannelExample extends Sprite { + private var url:String = "MySound.mp3"; + private var soundFactory:Sound; + private var channel:SoundChannel; + private var positionTimer:Timer; + + public function SoundChannelExample() { + var request:URLRequest = new URLRequest(url); + soundFactory = new Sound(); + soundFactory.addEventListener(Event.COMPLETE, completeHandler); + soundFactory.addEventListener(Event.ID3, id3Handler); + soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler); + soundFactory.load(request); + + channel = soundFactory.play(); + channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); + + positionTimer = new Timer(50); + positionTimer.addEventListener(TimerEvent.TIMER, positionTimerHandler); + positionTimer.start(); + } + + + private function positionTimerHandler(event:TimerEvent):void { + trace("positionTimerHandler: " + channel.position.toFixed(2)); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function id3Handler(event:Event):void { + trace("id3Handler: " + event); + } + + private function ioErrorHandler(event:Event):void { + trace("ioErrorHandler: " + event); + positionTimer.stop(); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler: " + event); + } + + private function soundCompleteHandler(event:Event):void { + trace("soundCompleteHandler: " + event); + positionTimer.stop(); + } + } +} +SoundSoundTransformsoundComplete + Dispatched when a sound has finished playing.flash.events.Event.SOUND_COMPLETEflash.events.Event + Dispatched when a sound has finished playing. + In the following example, the user selects songs from a playlist, + and then selects Play to play the song in the order selected. + +

In the constructor, a text field is defined that holds the song list + and a line for the selection to play. (Usually, buttons are + used for play and list boxes for a song list.) A text format object is + defined that changes the format of the song lines to italic after they are + selected. When a user selects the text field, the clickHandler() + method is invoked.

+ +

In the clickHandler() method, the getLineIndexAtPoint() + method of the text field object returns the index of the line that the user selected. Using + the line index, the getLineText() method gets the content of the text. + The if statement checks whether the user selected to play a song or add a song to the + play list. If a user selected to play and a song has been selected, then the event + listener for mouse click is removed and the playNext() method is called to + begin playing the songs. If the user selected a song title, the content of the + line is added to the songList array and the format of the line is set to italic.

+ +

The playNext() method iterates through the array list to load + and play each song. The song is also assigned to a sound channel. An event listener + for the sound channel is added to respond when the song finishes playing and the + Event.SOUND_COMPLETE event is dispatched. The soundCompleteHandler() + method then invokes the playNext() method to play the next song. This process + continues until all the songs listed in the array finish playing.

+ +package { + import flash.display.Sprite; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.MouseEvent; + import flash.text.TextFormat; + import flash.net.URLRequest; + import flash.events.Event; + import flash.events.IOErrorEvent; + + public class SoundChannel_event_soundCompleteExample extends Sprite { + private var channel:SoundChannel = new SoundChannel(); + private var songList:Array = new Array(); + private var listTextField:TextField = new TextField(); + private var songFormat:TextFormat = new TextFormat(); + private var arrayIndex:int = 0; + private var songSelected:Boolean = false; + + public function SoundChannel_event_soundCompleteExample() { + + listTextField.autoSize = TextFieldAutoSize.LEFT; + listTextField.border = true + listTextField.background = true; + listTextField.text = "Song1.mp3\n" + "Song2.mp3\n" + + "Song3.mp3\n" + "Song4.mp3\n" + "PLAY"; + + songFormat.italic = true; + + listTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + addChild(listTextField); + } + + private function clickHandler(e:MouseEvent):void { + var index:int = listTextField.getLineIndexAtPoint(e.localX, e.localY); + var line:String = listTextField.getLineText(index); + var firstIndex:uint = listTextField.getLineOffset(index); + var playLine:uint = listTextField.numLines - 1; + + if((index == playLine) && (songSelected == true)) { + listTextField.removeEventListener(MouseEvent.CLICK, clickHandler); + playNext(); + + } else if (index != playLine) { + songList.push(line.substr(0, (line.length - 1))); + listTextField.setTextFormat(songFormat, firstIndex, + (firstIndex + listTextField.getLineLength(index))); + songSelected = true; + } + } + + private function playNext():void { + + if(arrayIndex < songList.length) { + var snd:Sound = new Sound(); + snd.load(new URLRequest(songList[arrayIndex])); + channel = snd.play(); + + channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); + arrayIndex++; + + } else { + songSelected = false; + + while(arrayIndex > 0) { + songList.pop(); + arrayIndex--; + } + } + } + + private function soundCompleteHandler(e:Event):void { + playNext(); + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + trace(errorEvent.text); + } + } +} +
stop + Stops the sound playing in the channel. + Stops the sound playing in the channel. + + In the following example, the user can pause and replay a sound file. + +

In the constructor, the sound file is loaded. (This example assumes that the file is + in the same directory as the SWF file.) A text field is used as a button for the user + to play or pause the sound. When the user selects the button + text field, the clickHandler() method is invoked.

+ +

In the clickHandler() method, the first time the user selects + the text field, the sound is set to play and is assigned to a sound channel. Next, when + the user selects the text field to pause, the sound stops playing. The sound channel's + position property records the position of the sound at the + time it was stopped. This property is used to resume the sound starting at that position, after + the user selects the text field to start playing again. Each time the + Sound.play() method is called, a new SoundChannel object is created and + assigned to the channel variable. The Sound object must be + assigned to a SoundChannel object in order to use the sound channel's + stop() method to pause the sound.

+ + + +package { + import flash.display.Sprite; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.events.MouseEvent; + import flash.text.TextFieldAutoSize; + + public class SoundChannel_stopExample extends Sprite { + private var snd:Sound = new Sound(); + private var channel:SoundChannel = new SoundChannel(); + private var button:TextField = new TextField(); + + public function SoundChannel_stopExample() { + var req:URLRequest = new URLRequest("MySound.mp3"); + snd.load(req); + + button.x = 10; + button.y = 10; + button.text = "PLAY"; + button.border = true; + button.background = true; + button.selectable = false; + button.autoSize = TextFieldAutoSize.CENTER; + + button.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(button); + } + + private function clickHandler(e:MouseEvent):void { + var pausePosition:int = channel.position; + + if(button.text == "PLAY") { + channel = snd.play(pausePosition); + button.text = "PAUSE"; + } + else { + channel.stop(); + button.text = "PLAY"; + } + } + } +} +
leftPeak + The current amplitude (volume) of the left channel, from 0 (silent) to 1 (full amplitude).Number + The current amplitude (volume) of the left channel, from 0 (silent) to 1 (full amplitude). + + position + When the sound is playing, the position property indicates in milliseconds the current point + that is being played in the sound file.Number + When the sound is playing, the position property indicates in milliseconds the current point + that is being played in the sound file. When the sound is stopped or paused, the + position property indicates the last point that was played in the sound file. + +

A common use case is to save the value of the position property when the + sound is stopped. You can resume the sound later by restarting it from that saved position. +

+ +

If the sound is looped, position is reset to 0 at the beginning of each loop.

+ +
rightPeak + The current amplitude (volume) of the right channel, from 0 (silent) to 1 (full amplitude).Number + The current amplitude (volume) of the right channel, from 0 (silent) to 1 (full amplitude). + + soundTransform + The SoundTransform object assigned to the sound channel.flash.media:SoundTransform + The SoundTransform object assigned to the sound channel. A SoundTransform object + includes properties for setting volume, panning, left speaker assignment, and right + speaker assignment. + + SoundTransform
SoundMixer +The SoundMixer class contains static properties and methods for global sound control +in the application.Object +The SoundMixer class contains static properties and methods for global sound control +in the application. The SoundMixer class controls embedded and streaming sounds in the application. +it does not control dynamically created sounds (that is, sounds generated in response +to a Sound object dispatching a sampleData event). + +areSoundsInaccessible + Determines whether any sounds are not accessible due to security restrictions.The string representation of the boolean. + Boolean + Determines whether any sounds are not accessible due to security restrictions. For example, + a sound loaded from a domain other than that of the content calling this method is not accessible if + the server for the sound has no URL policy file that grants access to + the domain of that domain. The sound can still be loaded and played, but low-level + operations, such as getting ID3 metadata for the sound, cannot be performed on + inaccessible sounds. + +

For AIR application content in the application security sandbox, calling this method always + returns false. All sounds, including those loaded from other domains, are accessible + to content in the application security sandbox.

+ +
computeSpectrum()
computeSpectrum + Takes a snapshot of the current sound wave and places it into the specified ByteArray object.outputArrayflash.utils:ByteArrayA ByteArray object that holds the values associated with the sound. + If any sounds are not available due to security restrictions + (areSoundsInaccessible == true), the outputArray object + is left unchanged. If all sounds are stopped, the outputArray object is + filled with zeros. + + FFTModeBooleanfalseA Boolean value indicating whether a Fourier transformation is performed + on the sound data first. Setting this parameter to true causes the method to return a + frequency spectrum instead of the raw sound wave. In the frequency spectrum, low frequencies + are represented on the left and high frequencies are on the right. + + stretchFactorint0The resolution of the sound samples. + If you set the stretchFactor value to 0, data is sampled at 44.1 KHz; + with a value of 1, data is sampled at 22.05 KHz; with a value of 2, data is sampled 11.025 KHz; + and so on. + + + Takes a snapshot of the current sound wave and places it into the specified ByteArray object. + The values are formatted as normalized floating-point values, in the range -1.0 to 1.0. + The ByteArray object passed to the outputArray parameter is overwritten with the new values. + The size of the ByteArray object created is fixed to 512 floating-point values, where the + first 256 values represent the left channel, and the second 256 values represent + the right channel. + +

Note: This method is subject to local file security restrictions and + restrictions on cross-domain loading. If you are working with local files or sounds loaded from a server in a + different domain than the calling content, you might need to address sandbox restrictions + through a cross-domain policy file. For more information, see the Sound class description. + In addition, this method cannot be used to extract data from RTMP streams, even when + it is called by content that reside in the same domain as the RTMP server.

+ + +

This method is supported over RTMP in Flash Player 9.0.115.0 + and later and in Adobe AIR. You can control access to streams on + Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess + and Client.videoSampleAccess properties in + Server-Side ActionScript Language Reference for Adobe Flash Media Server.

+ +
In the following example, the computeSpectrum() method is + used to produce a graphic representation of the sound wave data. + +

In the constructor, a sound file is loaded and set to play. (There is no error handling + in this example and it is assumed that the sound file is in the same directory as the SWF file.) + The example listens for the Event.ENTER_FRAME event while the sound plays, repeatedly + triggering the onEnterFrame() method to draw a graph of the sound data values. + When the sound finishes playing the onPlaybackComplete() method stops the drawing process + by removing the listener for the Event.ENTER_FRAME event.

+ +

In the onEnterFrame() method, the computeSpectrum() method stores the raw + sound in the bytes byte array object. The data is sampled at 44.1 KHz. + The byte array containing 512 bytes of data, each of which contains a floating-point value + between -1 and 1. The first 256 values represent the left channel, and the second 256 values + represent the right channel. The first for loop, reads the first 256 data values (the left stereo channel) + and draws a line from each point to the next using the Graphics.lineTo() method. (The vector + graphic display of the sound wave is written directly on to the class's sprite object.) The sound bytes + are read as 32-bit floating-point number from the byte stream and multiplied by the plot height to allow + for the vertical range of the graph. The width is set to twice the width of the channel length. The + second for loop reads the next set of 256 values (the right stereo channel), and plots the lines in + reverse order. The g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); and g.lineTo(0, PLOT_HEIGHT); + methods draw the baseline for the waves. The resulting waveform plot produces a mirror-image effect.

+ + +package { + import flash.display.Sprite; + import flash.display.Graphics; + import flash.events.Event; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.media.SoundMixer; + import flash.net.URLRequest; + import flash.utils.ByteArray; + import flash.text.TextField; + + public class SoundMixer_computeSpectrumExample extends Sprite { + + public function SoundMixer_computeSpectrumExample() { + var snd:Sound = new Sound(); + var req:URLRequest = new URLRequest("Song1.mp3"); + snd.load(req); + + var channel:SoundChannel; + channel = snd.play(); + addEventListener(Event.ENTER_FRAME, onEnterFrame); + channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete); + } + + private function onEnterFrame(event:Event):void { + var bytes:ByteArray = new ByteArray(); + const PLOT_HEIGHT:int = 200; + const CHANNEL_LENGTH:int = 256; + + SoundMixer.computeSpectrum(bytes, false, 0); + + var g:Graphics = this.graphics; + + g.clear(); + + g.lineStyle(0, 0x6600CC); + g.beginFill(0x6600CC); + g.moveTo(0, PLOT_HEIGHT); + + var n:Number = 0; + + for (var i:int = 0; i < CHANNEL_LENGTH; i++) { + n = (bytes.readFloat() * PLOT_HEIGHT); + g.lineTo(i * 2, PLOT_HEIGHT - n); + } + + g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); + g.endFill(); + + g.lineStyle(0, 0xCC0066); + g.beginFill(0xCC0066, 0.5); + g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); + + for (i = CHANNEL_LENGTH; i > 0; i--) { + n = (bytes.readFloat() * PLOT_HEIGHT); + g.lineTo(i * 2, PLOT_HEIGHT - n); + } + + g.lineTo(0, PLOT_HEIGHT); + g.endFill(); + } + + private function onPlaybackComplete(event:Event):void { + removeEventListener(Event.ENTER_FRAME, onEnterFrame); + } + } +} + +
areSoundsInaccessible()flash.utils.ByteArrayflash.media.Soundflash.media.SoundLoaderContext.checkPolicyFile
stopAll + Stops all sounds currently playing. + Stops all sounds currently playing. + +

>In Flash Professional, this method does not stop the playhead. + Sounds set to stream will resume playing as the playhead moves over the frames in which they + are located.

+ +

When using this property, consider the following security model:

+ +
  • By default, calling the SoundMixer.stopAll() method stops + only sounds in the same security sandbox as the object that is calling the method. + Any sounds whose playback was not started from the same sandbox as the calling object + are not stopped.
  • When you load the sound, using the load() method of the Sound class, you can + specify a context parameter, which is a SoundLoaderContext object. If you set the + checkPolicyFile property of the SoundLoaderContext object to true, + Flash Player or Adobe AIR + checks for a cross-domain policy file on the server from which the sound is loaded. If the server has a + cross-domain policy file, and the file permits the domain of the calling content, then the file can stop the loaded + sound by using the SoundMixer.stopAll() method; otherwise it cannot.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
In the following example, the stopAll() method is used to mute two + sounds that are playing at the same time. + +

In the constructor, two different sound files are loaded and set to play. The first sound is + loaded locally and is assigned to a sound channel. (It is assumed that the file is + in the same directory as the SWF file.) The second file is loaded and streamed from the Adobe + site. In order to use the SoundMixer.stopAll() method, all sound must be accessible. + (A SoundLoaderContext object can be used to check for the cross-domain policy file.) Each sound + also has an event listener that is invoked if an IO error occurred while loading the sound file. + A muteButton text field is also created. It listens for a click event, which + will invoke the muteButtonClickHandler() method.

+ +

In the muteButtonClickHandler() method, if the text field content is "MUTE," + the areSoundsInaccessible() method checks if the sound mixer has access to the files. + If the files are accessible, the stopAll() method stops the sounds. By selecting the + text field again, the first sound begins playing and the text field's content changes to + "MUTE" again. This time, the stopAll() method mutes the one sound that is running. + Note that sound channel stop() method can also be used to stop a specific sound + assigned to the channel. (To use the channel functionally, the sound needs to be reassigned + to the channel each time the play() method is invoked.)

+ + +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.media.SoundLoaderContext; + import flash.media.SoundChannel; + import flash.media.SoundMixer; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.MouseEvent; + import flash.events.IOErrorEvent; + + public class SoundMixer_stopAllExample extends Sprite { + private var firstSound:Sound = new Sound(); + private var secondSound:Sound = new Sound(); + private var muteButton:TextField = new TextField(); + private var channel1:SoundChannel = new SoundChannel(); + + public function SoundMixer_stopAllExample() { + firstSound.load(new URLRequest("mySound.mp3")); + secondSound.load(new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3")); + + firstSound.addEventListener(IOErrorEvent.IO_ERROR, firstSoundErrorHandler); + secondSound.addEventListener(IOErrorEvent.IO_ERROR, secondSoundErrorHandler); + + channel1 = firstSound.play(); + secondSound.play(); + + muteButton.autoSize = TextFieldAutoSize.LEFT; + muteButton.border = true; + muteButton.background = true; + muteButton.text = "MUTE"; + + muteButton.addEventListener(MouseEvent.CLICK, muteButtonClickHandler); + + this.addChild(muteButton); + } + + private function muteButtonClickHandler(event:MouseEvent):void { + + if(muteButton.text == "MUTE") { + + if(SoundMixer.areSoundsInaccessible() == false) { + SoundMixer.stopAll(); + muteButton.text = "click to play only one of sound."; + } + else { + muteButton.text = "The sounds are not accessible."; + } + } + else { + firstSound.play(); + muteButton.text = "MUTE"; + } + } + + private function firstSoundErrorHandler(errorEvent:IOErrorEvent):void { + trace(errorEvent.text); + } + + private function secondSoundErrorHandler(errorEvent:IOErrorEvent):void { + trace(errorEvent.text); + } + } +} +
bufferTime + The number of seconds to preload an embedded streaming sound into a buffer before it starts + to stream.int + The number of seconds to preload an embedded streaming sound into a buffer before it starts + to stream. The data in a loaded sound, including its buffer time, + cannot be accessed by a SWF file that is in a different domain + unless you implement a cross-domain policy file. + For more information about security and sound, see the Sound class description. + The data in a loaded sound, including its buffer time, + cannot be accessed by code in a file that is in a different domain + unless you implement a cross-domain policy file. However, in the application sandbox + in an AIR application, code can access data in sound files from any source. + For more information about security and sound, see the Sound class description. + +

The SoundMixer.bufferTime property only affects the buffer time + for embedded streaming sounds in a SWF and is independent of dynamically created + Sound objects (that is, Sound objects created in ActionScript). + The value of SoundMixer.bufferTime cannot override + or set the default of the buffer time specified in the SoundLoaderContext object + that is passed to the Sound.load() method.

+ +
Sound
soundTransform + The SoundTransform object that controls global sound properties.flash.media:SoundTransform + The SoundTransform object that controls global sound properties. A SoundTransform object + includes properties for setting volume, panning, left speaker assignment, and right + speaker assignment. The SoundTransform object used in this property provides final sound settings + that are applied to all sounds after any individual sound settings are applied. + + SoundTransform
CameraUI + The CameraUI class allows you to capture a still image or video using the default camera application on a device.flash.events:EventDispatcher + The CameraUI class allows you to capture a still image or video using the default camera application on a device. + +

The launch() method requests that the device open the default camera application. + The captured image or video is available in the MediaEvent object dispatched for the complete event. + Since the default camera application can save the image or video in a variety of formats, there + is no guarantee that returned media object can be loaded and displayed by the AIR runtime.

+ +

On some platforms, the media object returned by the camera is accessible as a file-based media promise. On others, + the media promise is not file-based and the file and relativePath + properties of the MediaPromise object are null. Do not use these properties in + code that is used on more than one platform.

+ +

On some platforms, the media object is automatically stored in the device media library. On those + platforms on which images and video are not automatically stored by the default camera application, you can use the + CameraRoll addBitmapData() function to store the media object.

+ +

On Android, the default camera application does not open if the external storage card is not available + (such as when the user has mounted the card as a USB mass storage device). In addition, the AIR application + that launches the camera loses focus. If the device runs low on resources, the AIR application can be + terminated by the operating system before the media capture is complete.

+ +

AIR profile support: This feature is supported + on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. You can test + for support at run time using the CameraUI.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
The following example uses the CameraUI class to launch the default camera + application on the device. When a picture is taken by the user, the example places the + image on the display list. + +package { + import flash.desktop.NativeApplication; + import flash.display.Loader; + import flash.display.MovieClip; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.ErrorEvent; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.MediaEvent; + import flash.media.CameraUI; + import flash.media.MediaPromise; + import flash.media.MediaType; + + public class CameraUIStillImage extends MovieClip{ + + private var deviceCameraApp:CameraUI = new CameraUI(); + private var imageLoader:Loader; + + public function CameraUIStillImage() { + this.stage.align = StageAlign.TOP_LEFT; + this.stage.scaleMode = StageScaleMode.NO_SCALE; + + if( CameraUI.isSupported ) + { + trace( "Initializing camera..." ); + + deviceCameraApp.addEventListener( MediaEvent.COMPLETE, imageCaptured ); + deviceCameraApp.addEventListener( Event.CANCEL, captureCanceled ); + deviceCameraApp.addEventListener( ErrorEvent.ERROR, cameraError ); + deviceCameraApp.launch( MediaType.IMAGE ); + } + else + { + trace( "Camera interface is not supported."); + } + } + + private function imageCaptured( event:MediaEvent ):void + { + trace( "Media captured..." ); + + var imagePromise:MediaPromise = event.data; + + if( imagePromise.isAsync ) + { + trace( "Asynchronous media promise." ); + imageLoader = new Loader(); + imageLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, asyncImageLoaded ); + imageLoader.addEventListener( IOErrorEvent.IO_ERROR, cameraError ); + + imageLoader.loadFilePromise( imagePromise ); + } + else + { + trace( "Synchronous media promise." ); + imageLoader.loadFilePromise( imagePromise ); + showMedia( imageLoader ); + } + } + + private function captureCanceled( event:Event ):void + { + trace( "Media capture canceled." ); + NativeApplication.nativeApplication.exit(); + } + + private function asyncImageLoaded( event:Event ):void + { + trace( "Media loaded in memory." ); + showMedia( imageLoader ); + } + + private function showMedia( loader:Loader ):void + { + this.addChild( loader ); + } + + private function cameraError( error:ErrorEvent ):void + { + trace( "Error:" + error.text ); + NativeApplication.nativeApplication.exit(); + } + } +} +
Michael Chaize: Android, AIR, and the Cameracancel + The cancel event is dispatched when the user closes the Camera UI without + saving a picture or video.flash.events.Event.CANCELflash.events.Event + The cancel event is dispatched when the user closes the Camera UI without + saving a picture or video. + + error + The error event is dispatched when the default camera cannot be opened.flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + The error event is dispatched when the default camera cannot be opened. + + complete + The complete event is dispatched when the user either captures a still picture or + video in the Camera UI.flash.events.MediaEvent.COMPLETEflash.events.MediaEvent + The complete event is dispatched when the user either captures a still picture or + video in the Camera UI. + + CameraUI + Creates a CameraUI object. + Creates a CameraUI object. + + launch + Launches the default camera application on the device.requestedMediaTypeStringThe type of media object to capture. The valid values for this parameter + are defined in the MediaType class: +
  • MediaType.IMAGE
  • MediaType.VIDEO
+ +
+ Launches the default camera application on the device. + +

You can capture either still images or video with this class. Video capture uses the + "Quality Low" camcorder profile on the device.

+ +

When the launch() method is called, the default camera application on + the device is invoked. The AIR application loses focus and waits for the user to + capture a still image or to finish capturing video. Once the desired media is captured by the user, + the AIR application regains focus and this CameraUI object dispatches a complete + event. If the user cancels the operation, this CameraUI object dispatches a cancel + event instead.

+ +

Note: It is possible for the AIR application to be shut down by the Android operating + system while it is in the background waiting for the user to capture an image or video. If this happens, + the user must restart the application. The AIR application does not dispatch a media event for the + previous image capture.

+ +

You can access the captured media file using the data property of the + MediaEvent object dispatched for the complete event. This property is an instance + of the MediaPromise class, which you can load into your application using the + loadFilePromise() method of the Loader class. Note that the device camera can + save captured media in a variety of formats. Video is particularly problematic in this regard. + It might not be possible to display the captured media in AIR.

+ +
MediaTypeMediaPromiseLoader.loadFilePromise()completeflash.events:MediaEventDispatched when a media object is captured. + Dispatched when a media object is captured.cancelflash.events:EventDispatched when the user exits from the native camera without capturing a media object. + Dispatched when the user exits from the native camera without capturing a media object.errorflash.events:ErrorEventDispatched if the default camera application is already in use. + Dispatched if the default camera application is already in use.errorflash.events:ErrorEventDispatched if the AIR application is in the background when it calls this function. + + Dispatched if the AIR application is in the background when it calls this function.
isSupported + Reports whether the CameraUI class is supported on the current device.Boolean + Reports whether the CameraUI class is supported on the current device. + +
SoundCodec +The SoundCodec class is an enumeration of constant values used in setting the codec property +of the Microphone class.Object +The SoundCodec class is an enumeration of constant values used in setting the codec property +of the Microphone class. + +NELLYMOSER + Specifies that the Nellymoser codec be used for compressing audio.NellyMoserString + Specifies that the Nellymoser codec be used for compressing audio. + This constant is the default value of the Microphone.codec property. + + SPEEX + Specifies that the Speex codec be used for compressing audio.SpeexString + Specifies that the Speex codec be used for compressing audio. + + CameraRoll +The CameraRoll class allows you to access image data in the system media library or "camera roll." + +AIR profile support: This feature is supported +on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices.flash.events:EventDispatcher +The CameraRoll class allows you to access image data in the system media library or "camera roll." + +

AIR profile support: This feature is supported +on mobile devices, but it is not supported on desktop operating systems or AIR for TV devices. See + +AIR Profile Support for more information regarding API support across multiple profiles.

+ +

The CameraRoll.addBitmapData() method adds an image to the device's dedicated media library. To check at run time whether your +application supports the CameraRoll.addBitmapData() method, check the CameraRoll.supportsAddBitmapData property.

+ +

The CameraRoll.browseForImage() method opens an image-choosing dialog that allows a user to choose an image in the + media library. When the user selects an image, the CameraRoll object dispatches a select event. Use the MediaEvent object + dispatched for this event to access the chosen image. To check at run time whether your +application supports the CameraRoll.browseForImage() method, check the CameraRoll.supportsBrowseForImage property.

+ +
cancel + Dispatched when a user cancels a browse-for-image operation without selecting an image.flash.events.Event.CANCELflash.events.Event + Dispatched when a user cancels a browse-for-image operation without selecting an image. + + select + Dispatched when a user selects an image from the device media library.flash.events.MediaEvent.SELECTflash.events.MediaEvent + Dispatched when a user selects an image from the device media library. + +

The MediaEvent object dispatched for this event provides access to the chosen media.

+ +
error + The error event is dispatched when an error occurs.flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + The error event is dispatched when an error occurs. + +

Sources of errors include:

+
  • An image browser cannot be opened.
  • An image browser is already in use.
  • The AIR application attempts to browse for an image while in the background.
  • An image cannot be added to the media library.
  • A method is called that is not supported on the device.
+ +
complete + Signals that an addBitmapData() operation completed successfully.flash.events.Event.COMPLETEflash.events.Event + Signals that an addBitmapData() operation completed successfully. + + CameraRoll + Creates a CameraRoll object. + Creates a CameraRoll object. + +

There is only a single media library supported by ActionScript. All CameraRoll objects + save to the same image repository.

+ +
addBitmapData + Adds an image to the device camera roll.bitmapDataflash.display:BitmapDataa BitmapData object containing the image to send to the camera roll. + + + Adds an image to the device camera roll. + + +

To check at run time whether your application supports the CameraRoll.addBitmapData() method, + check the CameraRoll.supportsAddBitmapData property.

+ +
browseForImage + Opens an image browser dialog to allow the user to select an existing image from the device camera roll. + Opens an image browser dialog to allow the user to select an existing image from the device camera roll. + +

When the user selects an image, this CameraRoll instance dispatches a select event containing a MediaEvent + object. Use the data property of the MediaEvent object to load the image. The data property + is a MediaPromise object, which you can load using the loadFilePromise() method of the Loader class.

+ +

To check at run time whether your application supports the CameraRoll.browseForImage() method, + check the CameraRoll.supportsBrowseForImage property.

+ +
package flash.media.examples +{ + import flash.media.CameraRoll; + import flash.media.MediaPromise; + import flash.media.MediaType; + import flash.events.MediaEvent; + import flash.events.Event; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.IOErrorEvent; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + + public class CameraRollTest extends Sprite{ + private var mediaSource:CameraRoll = new CameraRoll(); + + public function CameraRollTest() { + this.stage.align = StageAlign.TOP_LEFT; + this.stage.scaleMode = StageScaleMode.NO_SCALE; + + if( CameraRoll.supportsBrowseForImage ) + { + log( "Browsing for image..." ); + mediaSource.addEventListener( MediaEvent.SELECT, imageSelected ); + mediaSource.addEventListener( Event.CANCEL, browseCanceled ); + + mediaSource.browseForImage(); + } + else + { + log( "Browsing in camera roll is not supported."); + } + } + + private var imageLoader:Loader; + private function imageSelected( event:MediaEvent ):void + { + log( "Image selected..." ); + + var imagePromise:MediaPromise = event.data; + + imageLoader = new Loader(); + if( imagePromise.isAsync ) + { + log( "Asynchronous media promise." ); + imageLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, imageLoaded ); + imageLoader.contentLoaderInfo.addEventListener( IOErrorEvent.IO_ERROR, imageLoadFailed ); + imageLoader.loadFilePromise( imagePromise ); + } + else + { + log( "Synchronous media promise." ); + imageLoader.loadFilePromise( imagePromise ); + this.addChild( imageLoader ); + } + } + + private function browseCanceled( event:Event ):void + { + log( "Image browse canceled." ); + } + + private function imageLoaded( event:Event ):void + { + log( "Image loaded asynchronously." ); + this.addChild( imageLoader ); + } + + private function imageLoadFailed( event:Event ):void + { + log( "Image load failed." ); + } + + private function log( text:String ):void + { + trace( text ); + } + + } + + } +
MediaEventMediaPromiseLoader.loadFilePromise()selectflash.events:MediaEventDispatched when the user chooses an image. + Dispatched when the user chooses an image.cancelflash.events:EventDispatched when a user cancels the browse operation. + Dispatched when a user cancels the browse operation.errorflash.events:ErrorEventDispatched if the default image browser application is already in use. + Dispatched if the default image browser application is already in use.errorflash.events:ErrorEventDispatched if the AIR application is in the background when it calls this function. + + Dispatched if the AIR application is in the background when it calls this function.
supportsAddBitmapData + Whether the CameraRoll.addBitmapData() method is supported.Boolean + Whether the CameraRoll.addBitmapData() method is supported. Currently, the feature + is only supported in AIR applications on mobile devices. + + supportsBrowseForImage + Reports whether the CameraRoll.browseForImage() method is supported.BooleanReports whether the CameraRoll browseForImage() method is supported. + + Reports whether the CameraRoll.browseForImage() method is supported. Currently, the feature + is only supported in AIR applications on mobile devices. + +
Microphone + Use the Microphone class to monitor or capture audio from a microphone.flash.events:EventDispatcher + Use the Microphone class to monitor or capture audio from a microphone. + +

+ To get a reference to a Microphone instance, use the Microphone.getMicrophone() method + or the Microphone.getEnhancedMicrophone() method. An enhanced microphone instance can + perform acoustic echo cancellation. Use acoustic echo cancellation to create real-time audio/video applications + that don't require headsets. +

+ +

Create a real-time chat application

+

To create a real-time chat application, capture audio and send it to Flash Media Server. + Use the NetConnection and NetStream classes to send the audio stream to Flash Media Server. + Flash Media Server can broadcast the audio to other clients. + To create a chat application that doesn't require headsets, use acoustic echo + cancellation. Acoustic echo cancellation prevents the feedback loop that occurs when audio enters a microphone, + travels out the speakers, and enters the microphone again. To use acoustic echo cancellation, call + the Microphone.getEnhancedMicrophone() method to get a reference to a Microphone instance. + Set Microphone.enhancedOptions to an instance of the MicrophoneEnhancedOptions class to + configure settings.

+ +

Play microphone audio locally

+

Call the Microphone setLoopback() method to route the microphone audio directly to + the local computer or device audio output. Uncontrolled audio feedback is an inherent danger and is likely + to occur whenever the audio output can be picked up by the microphone input. The + setUseEchoSuppression() method can reduce, but not eliminate, the risk of feedback + amplification.

+ +

Capture microphone audio for local recording or processing

+

To capture microphone audio, listen for the sampleData events dispatched by a + Microphone instance. The SampleDataEvent object dispatched for this event contains the audio data.

+ +

For information about capturing video, see the Camera class.

+ +

Runtime microphone support

+

The Microphone class is not supported in Flash Player running in a mobile browser.

+ +

AIR profile support: The Microphone class is supported + on desktop operating systems, but it is not supported on all mobile devices. + It is not supported on AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

You can test for support at run time using the Microphone.isSupported property. + Note that for AIR for TV devices, Microphone.isSupported is true but + Microphone.getMicrophone() always returns null.

+ +

Privacy controls

+

+ Flash Player displays a Privacy dialog + box that lets the user choose whether to allow or deny access to + the microphone. Your application window size must be at least 215 x 138 + pixels, the minimum size required to display the dialog box, or access is denied automatically. +

+

Content running in the AIR application sandbox does not need permission to access the microphone + and no dialog is displayed. AIR content running outside the application sandbox does require permission + and the Privacy dialog is displayed.

+ +
The following example captures sound using echo suppression from a microphone after the + user allows access to their computer's microphone. + The Security.showSettings() method displays the Flash Player dialog box, which requests + permission to access the user's microphone. The call to setLoopBack(true) reroutes + input to the local speaker, so you can hear the sound while you run the example. + +

Two listeners listen for activity and + status events. The activity event is dispatched at the + start and end (if any) of the session and is captured by the activityHandler() + method, which traces information on the event. The status event is dispatched if + the attached microphone object reports any status information; it is captured and traced using + the statusHandler() method.

+ +

Note: A microphone must be attached to your computer for this example + to work correctly.

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Microphone; + import flash.system.Security; + + public class MicrophoneExample extends Sprite { + public function MicrophoneExample() { + var mic:Microphone = Microphone.getMicrophone(); + Security.showSettings("2"); + mic.setLoopBack(true); + + if (mic != null) { + mic.setUseEchoSuppression(true); + mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler); + mic.addEventListener(StatusEvent.STATUS, statusHandler); + } + } + + private function activityHandler(event:ActivityEvent):void { + trace("activityHandler: " + event); + } + + private function statusHandler(event:StatusEvent):void { + trace("statusHandler: " + event); + } + } +} +
flash.media.Cameraflash.media.MicrophoneEnhancedModeflash.media.MicrophoneEnhancedOptionsaYo Binitie: Implementing Acoustic Echo Suppression in Flash/Flex applicationsCristophe Coenraets: Voice Notes for AndroidMichael Chaize: AIR, Android, and the Microphonestatus + Dispatched when a microphone reports its status.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when a microphone reports its status. + If the value of the code property is "Microphone.Muted", + the user has refused to allow the SWF file access to the microphone. + If the value of the code property is "Microphone.Unmuted", + the user has allowed the SWF file access to the microphone. + +

Status events are not dispatched in Adobe AIR applications; access to the microphone + cannot be changed dynamically. On most platforms, AIR applications can always access the microphone. + On Android, an application must specify the Android RECORD_AUDIO permission in the application + descriptor. Otherwise, Android denies access to the microphone altogether.

+ +
Microphone.getMicrophone()
sampleData + Dispatched when the microphone has sound data in the buffer.flash.events.SampleDataEvent.SAMPLE_DATAflash.events.SampleDataEvent + Dispatched when the microphone has sound data in the buffer. +

+ The Microphone.rate property determines the number of samples generated + per second. The number of samples per event is a factor of the number of samples + per second and the latency between event calls. +

+ +
The following example captures 4 seconds of audio samples from the default microphone + and then plays the audio back. Be sure that there is a microphone attached. The the micSampleDataHandler() + is the event listener for the sampleData event of the Microphone object. The micSampleDataHandler() + method gets the samples as they become available and appends their values to a ByteArray object. A Timer + object is set for 4 seconds. The Timer removes the sampleData event of the Microphone object event listener, + creates a Sound object, and adds a sampleData event listener for the Sound object. The sampleData + event listener for the Sound object, the playbackSampleHandler() method, provides audio samples + for the Sound object to play. These audio samples are retrieved from the ByteArray object that stored the + Microphone samples. The samples are written to the Sound object twice since the Microphone samples are + recorded in monaural sound and the Sound object requests stereo pairs of samples. The rate + property of the Microphone object is set to 44, to match the 44-kHz sample rate used by Sound objects. + + + +const DELAY_LENGTH:int = 4000; + +var mic:Microphone = Microphone.getMicrophone(); +mic.setSilenceLevel(0, DELAY_LENGTH); +mic.gain = 100; +mic.rate = 44; +mic.addEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler); + +var timer:Timer = new Timer(DELAY_LENGTH); +timer.addEventListener(TimerEvent.TIMER, timerHandler); +timer.start(); + +var soundBytes:ByteArray = new ByteArray(); + +function micSampleDataHandler(event:SampleDataEvent):void +{ + while(event.data.bytesAvailable) + { + var sample:Number = event.data.readFloat(); + soundBytes.writeFloat(sample); + } +} + +function timerHandler(event:TimerEvent):void +{ + mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler); + timer.stop(); + soundBytes.position = 0; + var sound:Sound = new Sound(); + sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playbackSampleHandler); + sound.play(); +} + +function playbackSampleHandler(event:SampleDataEvent):void +{ + for (var i:int = 0; i < 8192 && soundBytes.bytesAvailable > 0; i++) + { + var sample:Number = soundBytes.readFloat(); + event.data.writeFloat(sample); + event.data.writeFloat(sample); + } +} + The following example captures sound using echo suppression from a microphone after the + user allows access to their computer's microphone. + The Security.showSettings() method displays the Flash Player dialog box, which requests + permission to access the user's microphone. The call to setLoopBack(true) reroutes + input to the local speaker, so you can hear the sound while you run the example. + +

Two listeners listen for activity and + status events. The activity event is dispatched at the + start and end (if any) of the session and is captured by the activityHandler() + method, which traces information on the event. The status event is dispatched if + the attached microphone object reports any status information; it is captured and traced using + the statusHandler() method.

+ +

Note: A microphone must be attached to your computer for this example + to work correctly.

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Microphone; + import flash.system.Security; + + public class MicrophoneExample extends Sprite { + public function MicrophoneExample() { + var mic:Microphone = Microphone.getMicrophone(); + Security.showSettings("2"); + mic.setLoopBack(true); + + if (mic != null) { + mic.setUseEchoSuppression(true); + mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler); + mic.addEventListener(StatusEvent.STATUS, statusHandler); + } + } + + private function activityHandler(event:ActivityEvent):void { + trace("activityHandler: " + event); + } + + private function statusHandler(event:StatusEvent):void { + trace("statusHandler: " + event); + } + } +} +
flash.events.SampleDataEvent
activity + Dispatched when a microphone starts or stops recording due to detected silence.flash.events.ActivityEvent.ACTIVITYflash.events.ActivityEvent + Dispatched when a microphone starts or stops recording due to detected silence. + +

+ To specify the amount of sound required to trigger this event + with an activating property of true, + or the amount of time that must elapse without sound to + trigger this event with an activating property of + false, use Microphone.setSilenceLevel(). +

+

For a Microphone object to dispatch activity events, the application must be monitoring + the input, either by calling setLoopback( true ), by listening for + sampleData events, or by attaching the microphone to a NetStream object.

+ +
setSilenceLevel()
getEnhancedMicrophone + Returns a reference to an enhanced Microphone object that can + perform acoustic echo cancellation.A reference to a Microphone object for capturing audio. If enhanced audio fails to initialize, returns null. + flash.media:Microphoneindexint-1The index value of the microphone. + + Returns a reference to an enhanced Microphone object that can + perform acoustic echo cancellation. Use acoustic echo cancellation to create audio/video chat applications + that don't require headsets. + +

The index parameter for the Microphone.getEnhancedMicrophone() method and the Microphone.getMicrophone() + method work the same way.

+ +

Important: At any given time you can have only a single instance of enhanced microphone device. + All other Microphone instances stop providing audio data and receive a StatusEvent with the + code property Microphone.Unavailable. When enhanced audio fails to initialize, + calls to this method return null, setting a value for Microphone.enhancedOptions has no effect, + and all existing Microphone instances function as before.

+ +

To configure an enhanced Microphone object, set the Microphone.enhancedOptions property. The following + code uses an enhanced Microphone object and full-duplex acoustic echo cancellation in a local test:

+ +
+	     var mic:Microphone = Microphone.getEnhancedMicrophone();
+	     var options:MicrophoneEnhancedOptions = new MicrophoneEnhancedOptions();
+	     options.mode = MicrophoneEnhancedMode.FULL_DUPLEX;
+	     mic.enhancedOptions = options;
+	     mic.setLoopBack(true);
+	 
+ +

The setUseEchoSuppression() method is ignored when using acoustic echo cancellation. +

+ +

+ When a SWF file tries to access the object returned by Microphone.getEnhancedMicrophone() + —for example, when you call NetStream.attachAudio()— + Flash Player displays a Privacy dialog box that lets the user choose whether to + allow or deny access to the microphone. (Make sure your Stage size is at least + 215 x 138 pixels; this is the minimum size Flash Player requires to display the dialog box.) +

+ + +
Microphone.getMicrophone()Microphone.enhancedOptionsMicrophone.status
getMicrophone + + Returns a reference to a Microphone object for capturing audio.A reference to a Microphone object for capturing audio. + + flash.media:Microphoneindexint-1The index value of the microphone. + + + + Returns a reference to a Microphone object for capturing audio. + To begin capturing the audio, you must attach the Microphone + object to a NetStream object (see NetStream.attachAudio()). + +

+ Multiple calls to Microphone.getMicrophone() reference the same microphone. + Thus, if your code contains the lines mic1 = Microphone.getMicrophone() + and + mic2 = Microphone.getMicrophone() + , both mic1 and mic2 + reference the same (default) microphone.

+ +

+ In general, you should not pass a value for index. Simply call + air.Microphone.getMicrophone() + to return a reference to the default microphone. + Using the Microphone Settings section in the Flash Player settings panel, the user can specify the default + microphone the application should use. (The user access the Flash Player settings panel by right-clicking + Flash Player content running in a web browser.) If you pass a value for index, you can + reference a microphone other than the one the user chooses. You can use index in + rare cases—for example, if your application is capturing audio from two microphones + at the same time. Content running in Adobe AIR also uses the Flash Player setting for the default + microphone.

+ +

+ Use the Microphone.index property to get the index value of the current + Microphone object. You can then pass this value to other methods of the + Microphone class. +

+ +

+ When a SWF file tries to access the object returned by Microphone.getMicrophone() + —for example, when you call NetStream.attachAudio()— + Flash Player displays a Privacy dialog box that lets the user choose whether to + allow or deny access to the microphone. (Make sure your Stage size is at least + 215 x 138 pixels; this is the minimum size Flash Player requires to display the dialog box.) +

+ +

+ When the user responds to this dialog box, a status event is dispatched + that indicates the user's response. You can also check the Microphone.muted + property to determine if the user has allowed or denied access to the microphone. +

+ +

+ If Microphone.getMicrophone() returns null, either the microphone is in use + by another application, or there are no microphones installed on the system. To determine + whether any microphones are installed, use Microphones.names.length. To display + the Flash Player Microphone Settings panel, which lets the user choose the microphone to be + referenced by Microphone.getMicrophone, use Security.showSettings(). + +

+ +
The following example shows how you can request access to the user's microphone using the static Microphone.getMicrophone() method and listening for the status event. + Example provided by + ActionScriptExamples.com. + +var mic:Microphone = Microphone.getMicrophone(); +mic.setLoopBack(); +mic.addEventListener(StatusEvent.STATUS, mic_status); + +var tf:TextField = new TextField(); +tf.autoSize = TextFieldAutoSize.LEFT; +tf.text = "Detecting microphone..."; +addChild(tf); + +function mic_status(evt:StatusEvent):void { + tf.text = "Microphone is muted?: " + mic.muted; + switch (evt.code) { + case "Microphone.Unmuted": + tf.appendText("\n" + "Microphone access was allowed."); + break; + case "Microphone.Muted": + tf.appendText("\n" + "Microphone access was denied."); + break; + } +} +
Microphone.statusflash.net.NetStream.attachAudio()flash.system.Security.showSettings()statusflash.events:StatusEventDispatched when a microphone reports its status. + If the value of the code property is "Microphone.Muted", + the user has refused to allow the SWF file access to the user's microphone. + If the value of the code property is "Microphone.Unmuted", + the user has allowed the SWF file access to the user's microphone. + + Dispatched when a microphone reports its status.
setLoopBack + Routes audio captured by a microphone to the local speakers.stateBooleantrue + Routes audio captured by a microphone to the local speakers. + + setSilenceLevel + Sets the minimum input level that should be considered sound and (optionally) the amount + of silent time signifying that silence has actually begun.silenceLevelNumberThe amount of sound required to activate the microphone + and dispatch the activity event. Acceptable values range from 0 to 100. + + timeoutint-1The number of milliseconds that must elapse without + activity before Flash Player or Adobe AIR considers sound to have stopped and dispatches the + dispatch event. The default value is 2000 (2 seconds). + (Note: The default value shown + in the signature, -1, is an internal value that indicates to Flash Player or Adobe AIR to use 2000.) + + + Sets the minimum input level that should be considered sound and (optionally) the amount + of silent time signifying that silence has actually begun. +
  • To prevent the microphone from detecting sound at all, pass a value of 100 for + silenceLevel; the activity event is never dispatched.
  • To determine the amount of sound the microphone is currently detecting, use Microphone.activityLevel.
+ +

Speex includes voice activity detection (VAD) and automatically reduces bandwidth when no voice is detected. + When using the Speex codec, Adobe recommends that you set the silence level to 0.

+ +

Activity detection is the ability to detect when audio levels suggest that a person is talking. + When someone is not talking, bandwidth can be saved because there is no need to send the associated + audio stream. This information can also be used for visual feedback so that users know + they (or others) are silent.

+ +

Silence values correspond directly to activity values. Complete silence is an activity value of 0. + Constant loud noise (as loud as can be registered based on the current gain setting) is an activity value + of 100. After gain is appropriately adjusted, your activity value is less than your silence value when + you're not talking; when you are talking, the activity value exceeds your silence value.

+ +

This method is similar to Camera.setMotionLevel(); both methods are used to + specify when the activity event is dispatched. However, these methods have + a significantly different impact on publishing streams:

+ +
  • Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth + usage. Even if a video stream does not detect motion, video is still sent.
  • Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio + stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating + that silence has started.
+ +
flash.media.Camera.setMotionLevel()flash.media.Microphone.activityLevelflash.media.Microphone.activityflash.media.Microphone.gainflash.media.Microphone.silenceLevelflash.media.Microphone.silenceTimeout
setUseEchoSuppression + Specifies whether to use the echo suppression feature of the audio codec.useEchoSuppressionBooleanA Boolean value indicating whether to use echo suppression + (true) or not (false). + + + Specifies whether to use the echo suppression feature of the audio codec. The default value is + false unless the user has selected Reduce Echo in the Flash Player Microphone + Settings panel. + +

Echo suppression is an effort to reduce the effects of audio feedback, which is caused when + sound going out the speaker is picked up by the microphone on the same system. (This is different + from acoustic echo cancellation, which completely removes the feedback. The setUseEchoSuppression() method + is ignored when you call the getEnhancedMicrophone() method to use acoustic echo cancellation.)

+ +

Generally, echo suppression is advisable when the sound being captured is played through + speakers — instead of a headset —. If your SWF file allows users to specify the + sound output device, you may want to call Microphone.setUseEchoSuppression(true) + if they indicate they are using speakers and will be using the microphone as well.

+ +

Users can also adjust these settings in the Flash Player Microphone Settings panel.

+ +
flash.media.Microphone.setUseEchoSuppression()flash.media.Microphone.useEchoSuppression
activityLevel + The amount of sound the microphone is detecting.Number + The amount of sound the microphone is detecting. Values range from + 0 (no sound is detected) to 100 (very loud sound is detected). The value of this property can + help you determine a good value to pass to the Microphone.setSilenceLevel() method. + +

If the microphone muted property is true, the value of this property is always -1.

+ +
flash.media.Microphone.getMicrophone()flash.media.Microphone.setSilenceLevel()flash.media.Microphone.gain
codec + The codec to use for compressing audio.String + The codec to use for compressing audio. Available codecs are Nellymoser (the default) and Speex. The enumeration class SoundCodec contains + the various values that are valid for the codec property. + +

If you use the Nellymoser codec, you can set the sample rate using Microphone.rate(). + If you use the Speex codec, the sample rate is set to 16 kHz.

+ +

Speex includes voice activity detection (VAD) and automatically reduces bandwidth when no voice is detected. + When using the Speex codec, Adobe recommends that you set the silence level to 0. To set the silence level, use the + Microphone.setSilenceLevel() method.

+ + + +
setSilenceLevel()
enableVAD + Enable Speex voice activity detection.Boolean + Enable Speex voice activity detection. + + encodeQuality + The encoded speech quality when using the Speex codec.int + The encoded speech quality when using the Speex codec. Possible values are from 0 to 10. The default value is 6. + Higher numbers represent higher quality but require more bandwidth, as shown in the following table. The bit rate values that are listed + represent net bit rates and do not include packetization overhead. +

+ Quality valueRequired bit rate (kilobits per second)0 3.9515.7527.7539.80412.8516.8620.6723.8827.8934.21042.2 +

+ +
codec
enhancedOptions + Controls enhanced microphone options.flash.media:MicrophoneEnhancedOptions + Controls enhanced microphone options. For more information, see + MicrophoneEnhancedOptions class. This property is ignored for non-enhanced Microphone instances. + + flash.media.MicrophoneEnhancedOptionsframesPerPacket + Number of Speex speech frames transmitted in a packet (message).int + Number of Speex speech frames transmitted in a packet (message). + Each frame is 20 ms long. The default value is two frames per packet. + +

The more Speex frames in a message, the lower the bandwidth required but the longer the delay in sending the + message. Fewer Speex frames increases bandwidth required but reduces delay.

+ +
gain + The amount by which the microphone boosts the signal.Number + The amount by which the microphone boosts the signal. Valid values are 0 to 100. The default value is 50. + + + flash.media.Microphone.gainindex + The index of the microphone, as reflected in the array returned by + Microphone.names.int + The index of the microphone, as reflected in the array returned by + Microphone.names. + + + flash.media.Microphone.getMicrophone()flash.media.Microphone.namesisSupported + The isSupported property is set to true if the + Microphone class is supported on the current platform, otherwise it is + set to false.Boolean + The isSupported property is set to true if the + Microphone class is supported on the current platform, otherwise it is + set to false. + + muted + Specifies whether the user has denied access to the microphone (true) + or allowed access (false).Boolean + Specifies whether the user has denied access to the microphone (true) + or allowed access (false). When this value changes, + a status event is dispatched. + For more information, see Microphone.getMicrophone(). + + + flash.media.Microphone.getMicrophone()flash.media.Microphone.statusname + The name of the current sound capture device, as returned by the sound capture hardware.String + The name of the current sound capture device, as returned by the sound capture hardware. + + + flash.media.Microphone.getMicrophone()flash.media.Microphone.namesnames + An array of strings containing the names of all available sound capture devices.Array + An array of strings containing the names of all available sound capture devices. + The names are returned without + having to display the Flash Player Privacy Settings panel to the user. This array + provides the zero-based index of each sound capture device and the + number of sound capture devices on the system, through the Microphone.names.length property. + For more information, see the Array class entry. + +

Calling Microphone.names requires an extensive examination of the hardware, and it + may take several seconds to build the array. In most cases, you can just use the default microphone.

+ +

Note: To determine the name of the current microphone, + use the name property.

+ +
Arrayflash.media.Microphone.nameflash.media.Microphone.getMicrophone()
noiseSuppressionLevel + Maximum attenuation of the noise in dB (negative number) used for Speex encoder.int + Maximum attenuation of the noise in dB (negative number) used for Speex encoder. If enabled, noise suppression is applied to sound captured from Microphone before + Speex compression. Set to 0 to disable noise suppression. Noise suppression is enabled by default with maximum attenuation of -30 dB. Ignored when Nellymoser + codec is selected. + + rate + The rate at which the microphone is capturing sound, in kHz.int + The rate at which the microphone is capturing sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 + kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz + that your sound capture device supports, usually 11 kHz. + +

Note: The actual rate differs slightly from the rate value, as noted + in the following table:

+ + rate valueActual frequency4444,100 Hz2222,050 Hz1111,025 Hz88,000 Hz55,512 Hz + + + +
flash.media.Microphone.rate
silenceLevel + The amount of sound required to activate the microphone and dispatch + the activity event.Number + The amount of sound required to activate the microphone and dispatch + the activity event. The default value is 10. + + flash.media.Microphone.gainflash.media.Microphone.setSilenceLevel()silenceTimeout + The number of milliseconds between the time the microphone stops + detecting sound and the time the activity event is dispatched.int + The number of milliseconds between the time the microphone stops + detecting sound and the time the activity event is dispatched. The default + value is 2000 (2 seconds). + +

To set this value, use the Microphone.setSilenceLevel() method.

+ + +
flash.media.Microphone.setSilenceLevel()
soundTransform + Controls the sound of this microphone object when it is in loopback mode.flash.media:SoundTransform + Controls the sound of this microphone object when it is in loopback mode. + + useEchoSuppression + Set to true if echo suppression is enabled; false otherwise.Boolean + Set to true if echo suppression is enabled; false otherwise. The default value is + false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel. + + + flash.media.Microphone.setUseEchoSuppression()
StageVideo + The StageVideo object uses the device's hardware acceleration capabilities, if available, to display + live or recorded video in an application.flash.events:EventDispatcher + The StageVideo object uses the device's hardware acceleration capabilities, if available, to display + live or recorded video in an application. Hardware acceleration capabilities are available on most devices. + The StageVideo object supports the same video formats as the Video object. + See the flash.net.NetStream class for more information about these formats. + +

AIR profile support: In AIR 2.5, this feature is supported + only on devices that run AIR for TV. See + + AIR Profile Support for more information regarding API support across multiple profiles. +

+ +

The video displayed by the StageVideo object always appears in a rectangular area on the stage + behind all Flash display list objects. Therefore, the StageVideo object takes advantage of hardware acceleration + while supporting the most common case for displaying video: a rectangular display area overlaid with + video controls.

+ + +

The benefits to using a StageVideo object instead of the Video object are:

+ +

  • Optimal video playback performance because of using hardware acceleration.
  • Decreased processor and power usage.
  • Flexibility and creativity for development of content, such as video controls, + that appears in front of the StageVideo object.

+ +

Because the StageVideo object uses device hardware capabilities, a StageVideo object is subject to the following constraints + compared to a Video object:

+ +

  • The video display area can only be a rectangle. You cannot use more advanced display areas, such as + elliptical or irregular shapes.
  • You cannot rotate a StageVideo object.
  • You cannot bitmap cache a StageVideo object,
  • You cannot use BitmapData to access the video data.
  • You cannot embed the video in the SWF file. You can use a StageVideo object only with the NetStream object.
  • You cannot apply filters, blend modes, or alpha values to a StageVideo object.
  • You cannot apply color transforms, 3D transforms, or matrix transforms to a StageVideo object.
  • You cannot apply a mask or scale9Grid to a StageVideo object.
  • Blend modes that you apply to display objects that are in front of a StageVideo object do not apply to the StageVideo object.
  • You can place a StageVideo object only on full pixel boundaries.
  • For each SWF file, Flash Player limits the number of StageVideo objects that can concurrently display + videos to four. However, the actual limit can be lower, depending on device hardware resources. + On AIR for TV devices, only one StageVideo object at a time can display a video.
  • The video timing is not synchronized with the timing of Flash content that the runtime displays.
  • Though the video presentation is the best available for the given device hardware, it is not 100% "pixel identical" across devices. + Slight variations can occur due to driver and hardware differences.
  • A few devices do not support all required color spaces. For example, some devices do not support BT.709, the H.264 standard. In such + cases you can use BT.601 for fast display.
  • You cannot use stage video with WMODE settings such as normal, opaque, or transparent. + Stage video supports only WMODE=direct when not in full screen mode. WMODE has no effect in Safari 4 or higher, IE 9 or higher, + or in AIR for TV.

+ +

The following steps summarize how to use a StageVideo object to play a video:

+ +

  1. Listen for the StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY event to find out when the + Stage.stageVideos vector has changed. (Not supported for AIR 2.5 for TV.)
  2. If the StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY event reports that stage video is available, + use the Stage.stageVideos Vector object within the event handler to access a StageVideo object. + In AIR 2.5 for TV, access Stage.stageVideos after the first SWF frame has rendered. + Note: You cannot create a StageVideo object.
  3. Attach a NetStream object using StageVideo.attachNetStream().
  4. Play the video using NetStream.play().
  5. Listen for the StageVideoEvent.RENDER_STATE event on the StageVideo object to determine the status of playing the video. + Receipt of this event also indicates that the width and height properties of the video have been initialized or changed.
  6. Listen for the VideoEvent.RENDER_STATE event on the Video object. This event provides the same statuses as + StageVideoEvent.RENDER_STATE, so you can also use it to determine whether GPU acceleration is available. Receipt of this event + also indicates that the width and height properties of the video have been initialized or changed. (Not supported for AIR 2.5 for TV.)

+ + +

If a StageVideoEvent.RENDER_STATE event indicates that the video cannot be played, + you can revert to using a Video object instead of a StageVideo object. This event is + dispatched after the video has been attached to a NetStream object and is playing. Also, depending on the platform, + any change in the playing status can result in dispatching the event. + Handle the StageVideoEvent.RENDER_STATE event to ensure that the application plays the video + or gracefully does not play the video. +

+ +

If a running video goes into full screen mode from a WMODE that does not support stage video, stage video can become available. + Likewise, if the user exits full screen mode, stage video can become unavailable. In these cases, the Stage.stageVideos vector changes. + To receive notification of this change, listen to the StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABITY event. NOTE: This notification + is not available in AIR 2.5 for TV.

+
flash.events.StageVideoEventflash.events.StageVideoAvailabilityEventflash.events.VideoEventflash.display.Stage.stageVideosflash.media.Videoflash.net.NetStreamUsing the StageVideo class for hardware-accelerated renderingrenderState + Dispatched by the StageVideo object when the render state of the StageVideo object changes.flash.events.StageVideoEvent.RENDER_STATEflash.events.StageVideoEvent + Dispatched by the StageVideo object when the render state of the StageVideo object changes. + + attachNetStream + Specifies a video stream to be displayed within the boundaries of the StageVideo object in the application.netStreamflash.net:NetStreamA NetStream object. To drop the connection to the StageVideo object, pass + null. + + Specifies a video stream to be displayed within the boundaries of the StageVideo object in the application. + The video stream is either a video file played with NetStream.play(), or null. + A video file can be stored on the local file + system or on Flash Media Server. If the value of the netStream argument is null, + the video is no longer played in the StageVideo object. + + +

Before calling attachNetStream() a second time, + call the currently attached NetStream object's close() method. + Calling close() + releases all the resources, including hardware decoders, involved with playing the video. + Then you can call attachNetStream() + with either another NetStream object or null.

+ +

+ You do not need to use this method if a video file contains only audio; the audio + portion of a video file is played automatically + when you call NetStream.play(). To control the audio + associated with a video file, use the soundTransform property + of the NetStream object that plays the video file. +

+ +
colorSpaces + Returns the names of available color spaces for this video surface. + Returns the names of available color spaces for this video surface. + Usually this list includes "BT.601" and "BT.709". On some configurations, only + "BT.601" is supported which means a video is possibly not rendered in the + correct color space. + +

Note: On AIR for TV devices, a value of "BT.601" indicates software playback, + and a value of "BT.709" indicates hardware playback.

+ +
depth + The depth level of a StageVideo object relative to other StageVideo objects.intThe depth of a StageVideo object relative to other StageVideo objects. + + The depth level of a StageVideo object relative to other StageVideo objects. + +

StageVideo objects always display behind other objects on the stage. If a platform supports more than one + StageVideo object, the depth property indicates a StageVideo object's depth level. + The bottom StageVideo object's depth property has the smallest value. + If multiple StageVideo objects have the same depth setting, the order they appear in the + stage,stageVideos Vector determines their relative depth.

+ +

Note: AIR for TV devices support only one StageVideo object. Therefore, this property is not + applicable for those devices. It is a placeholder + for future support on other devices.

+ +
flash.display.Stage.stageVideos
pan + The pan setting for displaying the video, specified as a Point object.flash.geom:PointThe Point value is not valid. + + RangeErrorRangeErrorDetermines which rectangle of a zoomed video is displayed. + + The pan setting for displaying the video, specified as a Point object. + +

By default, the value of pan is (0,0). + This default value centers the video in the rectangle specified by StageVideo.viewPort.

+ +

The pan value is significant only when the zoom property value is not the + default value (1.0, 1.0). When a video displays in the StageVideo.viewPort rectangle + with the default zoom value, the platform sizes the video to fit exactly into the rectangle. Therefore, the entire + video is visible. However, if a zoom factor is specified, the entire video is not visible. In this case, you can + set the pan value to specify which subrectangle of the video to show + in the StageVideo.viewPort rectangle.

+ +

The valid values of the pan property range from (-1.0, -1.0) to (1.0, 1.0). + Specifically:

+ +

  • + A pan value of (-1.0, -1.0) places the upper-left pixel of the video at the upper-left + position of the StageVideo.viewPort rectangle. +
  • + A pan value of (1.0, 1.0) places the lower-right pixel of the video at the lower-right + position of the StageVideo.viewPort rectangle. +
  • + A pan value of (1.0, -1.0) places the upper-right pixel of the video at the upper-right + position of the StageVideo.viewPort rectangle. +
  • + A pan value of (-1.0, 1.0) places the lower-left pixel of the video at the lower-left + position of the StageVideo.viewPort rectangle. +
+

+ +

Values between -1.0 and 1.0 pan according to scale.

+ +

If you set the pan property to a value outside the valid range, + a RangeError exception is thrown. + The runtime resets the value to the last valid value.

+ +

Also, consider that to use a StageVideo object, you assign an element + of the Stage.stageVideos Vector object to a StageVideo variable. When you set + the pan property of the StageVideo variable, the underlying Stage.stageVideos Vector + element also changes. If you later assign that element to another StageVideo variable to play + another video, reset the pan property.

+ +
zoom
videoHeight + An integer specifying the height of the video stream, in pixels.int + An integer specifying the height of the video stream, in pixels. + +

You may want to use this property, for example, to ensure that the user is seeing the + video at the same height at which it was captured, + regardless of the size of the StageVideo.viewPort rectangle.

+ +
videoWidth + An integer specifying the width of the video stream, in pixels.int + An integer specifying the width of the video stream, in pixels. + +

You may want to use this property, for example, to ensure that the user is seeing the + video at the same width at which it was captured, + regardless of the size of the StageVideo.viewPort rectangle.

+ +
viewPort + The absolute position and size of the video surface in pixels.flash.geom:RectangleThe Rectangle value is not valid. + RangeErrorRangeError + The absolute position and size of the video surface in pixels. + +

The position of the video is relative to the upper left corner of the stage.

+ +

+ The valid range of the x and y properties of the viewPort + Rectangle object are -8192 to 8191. Therefore, you can position the video + completely or partially off the stage. You can also make the video larger than the stage if you + make the width and height properties of the viewPort + property larger than the stage.

+ +
zoom + The zoom setting of the video, specified as a Point object.flash.geom:PointThe Point value is not valid. + + RangeErrorRangeErrorThe zoom setting of the video. + + The zoom setting of the video, specified as a Point object. + +

The zoom point is a scale factor. By default, the value of zoom is (1.0, 1.0). + This default value displays the entire video in the StageVideo.viewPort rectangle.

+ +

The valid values of the zoom property range from (1.0, 1.0) to (16.0, 16.0). + The x property of the zoom Point object specifies the zoom value for the horizontal pixels, and + the y property specifies the zoom value for the vertical pixels.

+ +

For example, a zoom value of (2.0, 2.0) displays only half the horizontal pixels + and half the vertical pixels in the StageVideo.viewPort rectangle. That is, the video still fills the + StageVideo.viewPort rectangle, but only half the video is visible, creating a 2x zoom effect. + Similarly, a zoom value of (16.0, 16.0) displays only 1/16 of the horizontal pixels + and 1/16 of the vertical pixels in the StageVideo.viewPort rectangle, + zooming in the maximum amount of 16x.

+ +

When you set the zoom property, set the pan property so that the StageVideo.viewPort rectangle + shows the appropriate subrectangle of the video.

+ +

Consider the following situation where it is useful to set a different value for the + x and y properties of the zoom Point object. + First, note that when a video displays in the StageVideo.viewPort rectangle + with the default zoom value, the platform sizes the video to fit exactly into the rectangle. + If the video's rectangle does not scale evenly to the StageVideo.viewPort rectangle, + the video display can be distorted. + That is, the aspect ratios of the video and the StageVideo.viewPort are not equal. + This case can occur, for example, if the video has a different width than height, but the StageVideo.viewPort + property specifies a square. + To resolve the distortion, set different values for the + x and y properties of the zoom Point object. + Then set the pan property to make sure the StageVideo.viewPort rectangle + shows the appropriate subrectangle of the video.

+ +

If you set the zoom property to a value outside the valid range, + a RangeError exception is thrown. + The runtime resets the value to the last valid value.

+ +

Also, consider that to use a StageVideo object, you assign an element + of the Stage.stageVideos Vector object to a StageVideo variable. When you set + the zoom property of the StageVideo variable, the underlying Stage.stageVideos Vector + element also changes. If you later assign that element to another StageVideo variable to play + another video, reset the zoom property.

+ + +
pan
MicrophoneEnhancedOptions + The MicrophoneEnhancedOptions class provides configuration options for enhanced audio (acoustic echo cancellation).Object + The MicrophoneEnhancedOptions class provides configuration options for enhanced audio (acoustic echo cancellation). + Acoustic echo cancellation allows multiple parties to communicate in an audio/video chat application without + using headsets. + +

To use acoustic echo cancellation, call Microphone.getEnhancedMicrophone() to get a reference to + an enhanced Microphone object. Set the Microphone.enhancedOptions + property to an instance of the MicrophoneEnhancedOptions class. +

+ +
flash.media.Microphone.enhancedOptionsflash.media.Microphone.getEnhancedMicrophone()autoGain + Enable automatic gain control.Boolean + Enable automatic gain control. A time-domain automatic gain control algorithm is used + with noise gating. The default value is off. + + echoPath + Specifies the echo path (in milliseconds) used for acoustic echo cancellation.int + Specifies the echo path (in milliseconds) used for acoustic echo cancellation. A longer + echo path results in better echo cancellation. A longer echo path also causes a longer delay + and requires more computational complexity. The default value is 128 (recommended). The other + possible value is 256. + + isVoiceDetected + Indicates whether the Microphone input detected a voice.int + Indicates whether the Microphone input detected a voice. + +

Possible values are: -1, not enabled; 0, a voice is not detected; 1, a voice is detected. +

+ +
mode + Controls enhanced microphone mode.String + Controls enhanced microphone mode. The default value is FULL_DUPLEX for all microphones that aren't USB. + The default value for USB microphones is HALF_DUPLEX. + See MicrophoneEnhancedMode for possible values and descriptions. + + flash.media.MicrophoneEnhancedModenonLinearProcessing + Enable non-linear processing.Boolean + Enable non-linear processing. Non-linear processing + suppresses the residual echo when one person is talking. The time-domain non-linear + processing technique is used. Turn off non-linear + processing for music sources. The default value is true which turns on non-linear processing. + +
Sound + The Sound class lets you work with sound in an application.flash.events:EventDispatcher + The Sound class lets you work with sound in an application. The Sound class + lets you create a Sound object, load and play an external MP3 file into that object, + close the sound stream, and access + data about the sound, such as information about the number of bytes in the stream and + ID3 metadata. More detailed control of the sound is performed through the sound source — + the SoundChannel or Microphone object for the sound — and through the properties + in the SoundTransform class that control the output of the sound to the computer's speakers. + +

In Flash Player 10 and later and AIR 1.5 and later, you can also use this + class to work with sound that is generated dynamically. + In this case, the Sound object uses the function you assign to a sampleData event handler to + poll for sound data. The sound is played as it is retrieved from a ByteArray object that + you populate with sound data. You can use Sound.extract() to extract sound data from a + Sound object, + after which you can manipulate it before writing it back to the stream for playback.

+ +

To control sounds that are embedded in a SWF file, use the properties in the SoundMixer class.

+ +

Note: The ActionScript 3.0 Sound API differs from ActionScript 2.0. + In ActionScript 3.0, you cannot take sound objects and arrange them in a hierarchy + to control their properties.

+ +

When you use this class, consider the following security model:

+ +
  • Loading and playing a sound is not allowed if the calling file is in a network sandbox + and the sound file to be loaded is local.
  • By default, loading and playing a sound is not allowed if the calling file is local and + tries to load and play a remote sound. A user must grant explicit permission to allow this type of access.
  • Certain operations dealing with sound are restricted. The data in a loaded sound cannot + be accessed by a file in a different domain unless you implement a cross-domain policy file. + Sound-related APIs that fall under this restriction are Sound.id3, + SoundMixer.computeSpectrum(), SoundMixer.bufferTime, + and the SoundTransform class.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example displays + information about sound events that take place as an MP3 file is opened and played. To run this example, + place a file named MySound.mp3 in the same directory as your SWF file. + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.net.URLRequest; + + public class SoundExample extends Sprite { + private var url:String = "MySound.mp3"; + private var song:SoundChannel; + + public function SoundExample() { + var request:URLRequest = new URLRequest(url); + var soundFactory:Sound = new Sound(); + soundFactory.addEventListener(Event.COMPLETE, completeHandler); + soundFactory.addEventListener(Event.ID3, id3Handler); + soundFactory.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + soundFactory.addEventListener(ProgressEvent.PROGRESS, progressHandler); + soundFactory.load(request); + song = soundFactory.play(); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function id3Handler(event:Event):void { + trace("id3Handler: " + event); + } + + private function ioErrorHandler(event:Event):void { + trace("ioErrorHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler: " + event); + } + } +} +
flash.net.NetStreamMicrophoneSoundChannelSoundMixerSoundTransformprogress + Dispatched when data is received as a load operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched when data is received as a load operation progresses. + load()open + Dispatched when a load operation starts.flash.events.Event.OPENflash.events.Event + Dispatched when a load operation starts. + load()ioError + Dispatched when an input/output error occurs that causes a load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input/output error occurs that causes a load operation to fail. + load()id3 + Dispatched by a Sound object when ID3 data is available for an MP3 sound.flash.events.Event.ID3flash.events.Event + Dispatched by a Sound object when ID3 data is available for an MP3 sound. + Sound.id3complete + Dispatched when data has loaded successfully.flash.events.Event.COMPLETEflash.events.Event + Dispatched when data has loaded successfully. + load()sampleData + Dispatched when the runtime requests new audio data.flash.events.SampleDataEvent.SAMPLE_DATAflash.events.SampleDataEvent + Dispatched when the runtime requests new audio data. + + The following example plays a simple sine wave. + + +var mySound:Sound = new Sound(); +function sineWaveGenerator(event:SampleDataEvent):void { + for ( var c:int=0; c<8192; c++ ) { + event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25); + event.data.writeFloat(Math.sin((Number(c+event.position)/Math.PI/2))*0.25); + } +} + +mySound.addEventListener(SampleDataEvent.SAMPLE_DATA,sineWaveGenerator); +mySound.play(); +extract()play()flash.events.SampleDataEventSound + Creates a new Sound object.streamflash.net:URLRequestnull The URL that points to an external MP3 file. + + contextflash.media:SoundLoaderContextnull An optional SoundLoader context object, which can define the buffer time + (the minimum number of milliseconds of MP3 data to hold in the Sound object's + buffer) and can specify whether the application should check for a cross-domain + policy file prior to loading the sound. + + + Creates a new Sound object. If you pass a valid URLRequest object to the + Sound constructor, the constructor automatically calls the load() function + for the Sound object. + If you do not pass a valid URLRequest object to the Sound constructor, + you must call the load() function for the Sound object yourself, + or the stream will not load. + +

Once load() is called on a Sound object, you can't later load + a different sound file into that Sound object. To load a different sound file, + create a new Sound object.

+ + In Flash Player 10 and later and AIR 1.5 and later, instead of using load(), + you can use the sampleData event handler to load sound dynamically into the Sound object. + +
close + Closes the stream, causing any download of data to cease.The stream could not be closed, or + the stream was not open. + + IOErrorflash.errors:IOError + Closes the stream, causing any download of data to cease. + No data may be read from the stream after the close() + method is called. + + In the following example, when the user clicks on the Stop button, + the Sound.close() method will be called and the sound will stop streaming. + +

In the constructor, a text field is created for the Start and Stop button. + When the user clicks on the text field, the clickHandler() method is invoked. + It handles the starting and stopping of the sound file. Note that depending on + the network connection or when the user clicks the Stop button, much of the file could + already have been loaded and it may take a while for the sound file to stop playing. + A try...catch block is used to catch any IO error that may occur while + closing the stream. For example, if the sound is loaded from a local directory and + not streamed, error 2029 is caught, stating, "This URLStream object does not have an open stream."

+ + +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.MouseEvent; + import flash.errors.IOError; + import flash.events.IOErrorEvent; + + public class Sound_closeExample extends Sprite { + private var snd:Sound = new Sound(); + private var button:TextField = new TextField(); + private var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); + + public function Sound_closeExample() { + button.x = 10; + button.y = 10; + button.text = "START"; + button.border = true; + button.background = true; + button.selectable = false; + button.autoSize = TextFieldAutoSize.LEFT; + + button.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(button); + } + + private function clickHandler(e:MouseEvent):void { + + if(button.text == "START") { + + snd.load(req); + snd.play(); + + snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + + button.text = "STOP"; + } + else if(button.text == "STOP") { + + try { + snd.close(); + button.text = "Wait for loaded stream to finish."; + } + catch (error:IOError) { + button.text = "Couldn't close stream " + error.message; + } + } + } + + private function errorHandler(event:IOErrorEvent):void { + button.text = "Couldn't load the file " + event.text; + } + } +} + + +
extract + Extracts raw sound data from a Sound object.The number of samples written to the ByteArray specified in the target parameter. + + Numbertargetflash.utils:ByteArrayA ByteArray object in which the extracted sound samples are placed. + lengthNumberThe number of sound samples to extract. + A sample contains both the left and right channels — that is, two 32-bit floating-point values. + + startPositionNumber-1The sample at which extraction begins. + If you don't specify a value, the first call to Sound.extract() starts at the beginning + of the sound; subsequent calls without a value for startPosition + progress sequentially through the file. + + + Extracts raw sound data from a Sound object. + +

This method is designed to be used when you are working + with dynamically generated audio, using a function you assign + to the sampleData event for a different Sound object. + That is, you can use this method to extract sound data from a Sound object. + Then you can write the data to the byte array that another Sound object is using + to stream dynamic audio.

+ +

The audio data is placed in the target byte array starting from the current position of the byte array. + The audio data is always exposed as 44100 Hz Stereo. The sample type is a 32-bit floating-point value, + which can be converted to a Number using ByteArray.readFloat().

+ +
The following example loads an mp3 file and uses the + extract() method of the Sound class to access the audio data. +

The mp3 data is loaded into the sourceSnd Sound object. When the + application loads the mp3 data, it calls the loaded() function + (the event handler for the complete event of the sourceSnd + object). A second Sound object, outputSound, is used to play the + modified audio. The outputSound object has a sampleData + event listener; so the object dispatches periodical sampleData events + once you call the play() method of the object. + The upOctave() method returns a byte array of modified audio data + based on the source audio data. It returns audio that is one octave higher by + skipping over every other audio sample in the source data. The event handler for + the sampleData event writes the returned byte array to the data + property of the outputSound object. The data byte array is + appended to the output audio data for the outputSound object.

+

To test this example, add a test.mp3 file to the same directory as the SWF file.

+ + +var sourceSnd:Sound = new Sound(); +var outputSnd:Sound = new Sound(); +var urlReq:URLRequest = new URLRequest("test.mp3"); + +sourceSnd.load(urlReq); +sourceSnd.addEventListener(Event.COMPLETE, loaded); + +function loaded(event:Event):void +{ + outputSnd.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound); + outputSnd.play(); +} + +function processSound(event:SampleDataEvent):void +{ + var bytes:ByteArray = new ByteArray(); + sourceSnd.extract(bytes, 4096); + event.data.writeBytes(upOctave(bytes)); +} + +function upOctave(bytes:ByteArray):ByteArray +{ + var returnBytes:ByteArray = new ByteArray(); + bytes.position = 0; + while(bytes.bytesAvailable > 0) + { + returnBytes.writeFloat(bytes.readFloat()); + returnBytes.writeFloat(bytes.readFloat()); + if (bytes.bytesAvailable > 0) + { + bytes.position += 8; + } + } + return returnBytes; +} +
play()sampleData
load + Initiates loading of an external MP3 file from the specified URL.A network error caused the load to fail. + + IOErrorflash.errors:IOErrorLocal untrusted files may not communicate with + the Internet. You can work around this by reclassifying this file + as local-with-networking or trusted. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThe digest property of the stream object is not + null. You should only set the digest property of a URLRequest object + when calling the URLLoader.load() method when loading a SWZ file (an Adobe + platform component). + + IOErrorflash.errors:IOErrorstreamflash.net:URLRequest A URL that points to an external MP3 file. + + contextflash.media:SoundLoaderContextnull An optional SoundLoader context object, which can define the buffer time + (the minimum number of milliseconds of MP3 data to hold in the Sound object's + buffer) and can specify whether the application should check for a cross-domain + policy file prior to loading the sound. + + Initiates loading of an external MP3 file from the specified URL. If you provide + a valid URLRequest object to the Sound constructor, the constructor calls + Sound.load() for you. You only need to call Sound.load() + yourself if you + don't pass a valid URLRequest object to the Sound constructor or you pass a null + value. + +

Once load() is called on a Sound object, you can't later load + a different sound file into that Sound object. To load a different sound file, + create a new Sound object.

+ +

When using this method, consider the following security model:

+ +
  • Calling Sound.load() is not allowed if the calling file is in the + local-with-file-system sandbox and the sound is in a network sandbox.
  • Access from the local-trusted or local-with-networking sandbox requires permission + from a website through a URL policy file.
  • You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.
  • You can prevent a SWF file from using this method by setting the + allowNetworking parameter of the object and embed + tags in the HTML page that contains the SWF content.
+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+

In Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example displays the loading progress of a sound file. + +

In the constructor a URLRequest object is created to identify the location + of the sound file, which is a podcast from Adobe. The file is loaded in a try...catch + block in order to catch any error that may occur while loading the file. If an IO error + occurred, the errorHandler() method also is invoked and the error message + is written in the text field intended for the progress report. While a load operation is in + progress, a ProgressEvent.PROGRESS event is dispatched and the progressHandler() + method is called. Here, ProgressEvent.PROGRESS event is used as a timer for + calculating the load progress.

+ +

The progressHandler() method divides the bytesLoaded value + passed with the ProgressEvent object by the bytesTotal value to + arrive at a percentage of the sound data that is being loaded. It then displays these values + in the text field. (Note that if the file is small, cached, or the file is in the local directory, + the progress may not be noticeable.)

+ +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.ProgressEvent; + import flash.events.IOErrorEvent; + + public class Sound_loadExample extends Sprite { + private var snd:Sound = new Sound(); + private var statusTextField:TextField = new TextField(); + + public function Sound_loadExample(){ + + statusTextField.autoSize = TextFieldAutoSize.LEFT; + var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); + + try { + snd.load(req); + + snd.play(); + } + catch (err:Error) { + trace(err.message); + } + + snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + snd.addEventListener(ProgressEvent.PROGRESS, progressHandler); + + this.addChild(statusTextField); + } + + private function progressHandler(event:ProgressEvent):void { + var loadTime:Number = event.bytesLoaded / event.bytesTotal; + var LoadPercent:uint = Math.round(100 * loadTime); + + statusTextField.text = "Sound file's size in bytes: " + event.bytesTotal + "\n" + + "Bytes being loaded: " + event.bytesLoaded + "\n" + + "Percentage of sound file that is loaded " + LoadPercent + "%.\n"; + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + statusTextField.text = "The sound could not be loaded: " + errorEvent.text; + } + } +} +
play + Generates a new SoundChannel object to play back the sound.A SoundChannel object, which you use to control the sound. + This method returns null if you have no sound card + or if you run out of available sound channels. The maximum number of + sound channels available at once is 32. + + flash.media:SoundChannelstartTimeNumber0The initial position in milliseconds at which playback should + start. + loopsint0Defines the number of times a sound loops back to the startTime value + before the sound channel stops playback. + sndTransformflash.media:SoundTransformnullThe initial SoundTransform object assigned to the sound channel. + + + Generates a new SoundChannel object to play back the sound. This method + returns a SoundChannel object, which you access to stop the sound and to monitor volume. + (To control the volume, panning, and balance, access the SoundTransform object assigned + to the sound channel.) + + In the following example, once the file is loaded, the user using a + graphic bar can select the starting position (starting time) of the sound file. + +

The constructor calls the Sound.load() method to start loading the sound data. + Next it calls the Sound.play() method which will start playing the sound as soon + as enough data has loaded. The Sound.play() method returns a SoundChannel object + that can be used to control the playback of the sound. The text field displays the instructions. + To make sure the content of where the user wants the sound to start, has already been loaded, + the bar Sprite object is created and displayed after the file has finished loading. + An Event.COMPLETE event is dispatched when the file is successfully loaded, which + triggers the completeHandler() method. The completeHandler() method + then creates the bar and adds it to the display list. (A sprite object is used instead of a shape + object to support interactivity.) When the user clicks on the bar, the clickHandler() + method is triggered.

+ +

In the clickHandler() method, the position of x coordinate of the user's click, + event.localX, is used to determine where the user wants the file to start. + Since the bar is 100 pixels and it starts at x coordinate 100 pixels, it is easy to determine + the percentage of the position. Also, since the file is loaded, the length + property of the sound file will have the length of the complete file in milliseconds. + Using the length of the sound file and the position in the line, a starting position + for the sound file is determined. After stopping the sound from playing, the sound file + restarts at the selected starting position, which is past as the startTime + parameter to the play() method.

+ + +package { + import flash.display.Sprite; + import flash.display.Graphics; + import flash.events.MouseEvent; + import flash.media.Sound;; + import flash.net.URLRequest; + import flash.media.SoundChannel; + import flash.events.ProgressEvent; + import flash.events.Event; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.IOErrorEvent; + + public class Sound_playExample1 extends Sprite { + private var snd:Sound = new Sound(); + private var channel:SoundChannel = new SoundChannel(); + private var infoTextField:TextField = new TextField(); + + public function Sound_playExample1() { + + var req:URLRequest = new URLRequest("MySound.mp3"); + + infoTextField.autoSize = TextFieldAutoSize.LEFT; + infoTextField.text = "Please wait for the file to be loaded.\n" + + "Then select from the bar to decide where the file should start."; + + snd.load(req); + channel = snd.play(); + + snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + snd.addEventListener(Event.COMPLETE, completeHandler); + + + this.addChild(infoTextField); + } + + private function completeHandler(event:Event):void { + infoTextField.text = "File is ready."; + + var bar:Sprite = new Sprite(); + + bar.graphics.lineStyle(5, 0xFF0000); + bar.graphics.moveTo(100, 100); + bar.graphics.lineTo(200, 100); + + bar.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(bar); + } + + private function clickHandler(event:MouseEvent):void { + + var position:uint = event.localX; + var percent:uint = Math.round(position) - 100; + var cue:uint = (percent / 100) * snd.length; + + channel.stop(); + channel = snd.play(cue); + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + infoTextField.text = "The sound could not be loaded: " + errorEvent.text; + } + } +} +
In the following example, depending on whether the user single or double clicks on + a button the sound will play once or twice. + +

In the constructor, the sound is loaded and a simple rectangle button sprite object + is created. (A sprite object is used instead of a shape object to support interactivity.) + Here, it is assumed that the sound file is in the same directory as the SWF file. (There + is no error handling code for this example.)

+ +

Two event listeners are set up to respond to single mouse clicks and double clicks. + If the user clicks once, the clickHandler() method is invoked, which plays the sound. + If the user double clicks on the button, the doubleClickHandler() method is invoked, + which will play the sound file twice. The second argument of the play() method is set + to 1, which means the sound will loop back once to the starting time of the + sound and play again. The starting time, first argument, is set to 0, meaning + the file will play from the beginning.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.media.Sound; + import flash.net.URLRequest; + + public class Sound_playExample2 extends Sprite { + private var button:Sprite = new Sprite(); + private var snd:Sound = new Sound(); + + public function Sound_playExample2() { + + var req:URLRequest = new URLRequest("click.mp3"); + snd.load(req); + + button.graphics.beginFill(0x00FF00); + button.graphics.drawRect(10, 10, 50, 30); + button.graphics.endFill(); + + button.addEventListener(MouseEvent.CLICK, clickHandler); + button.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler); + + this.addChild(button); + } + + private function clickHandler(event:MouseEvent):void { + snd.play(); + } + + private function doubleClickHandler(event:MouseEvent):void { + snd.play(0, 2); + } + } +} +
The following example displays the loading and playing progress of a sound file. + +

In the constructor, the file is loaded in a try...catch block in order to catch + any error that may occur while loading the file. A listener is added to the sound object that + will respond to an IOErrorEvent event by calling the errorHandler() method. + Another listener is added for the main application that will respond to an Event.ENTER_FRAME + event, which is used as the timing mechanism for showing playback progress. Finally, a third listener + is added for the sound channel that will respond to an Event.SOUND_COMPLETE event (when + the sound has finished playing), by calling the soundCompleteHandler() method. + The soundCompleteHandler() method also removes the event listener for the + Event.ENTER_FRAME event.

+ +

The enterFrameHandler() method divides the bytesLoaded value + passed with the ProgressEvent object by the bytesTotal value to + arrive at a percentage of the sound data that is being loaded. The percentage of sound data that is + being played could be determined by dividing the value of sound channel's position property + by the length of the sound data. However, if the sound data is not fully loaded, the length + property of the sound object shows only the size of the sound data that is currently loaded. + An estimate of the eventual size of the full sound file is calculated by dividing the value + of the current sound object's length by the value of the bytesLoaded + property divided by the value of the bytesTotal property.

+ +

Note that if the file is small, cached, or the file is in the local directory, the load progress + may not be noticeable. Also the lag time between when the sound data starts loading and the loaded + data starts playing is determined by the value of the SoundLoaderContext.buffertime + property, which is by default 1000 milliseconds and can be reset.

+ +package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.Event; + import flash.events.IOErrorEvent; + + public class Sound_playExample3 extends Sprite { + private var snd:Sound = new Sound(); + private var channel:SoundChannel; + private var statusTextField:TextField = new TextField(); + + public function Sound_playExample3(){ + + statusTextField.autoSize = TextFieldAutoSize.LEFT; + + var req:URLRequest = new URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3"); + + try { + snd.load(req); + + channel = snd.play(); + } + catch (err:Error) { + trace(err.message); + } + + snd.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + addEventListener(Event.ENTER_FRAME, enterFrameHandler); + channel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler); + + this.addChild(statusTextField); + } + + private function enterFrameHandler(event:Event):void { + var loadTime:Number = snd.bytesLoaded / snd.bytesTotal; + var loadPercent:uint = Math.round(100 * loadTime); + var estimatedLength:int = Math.ceil(snd.length / (loadTime)); + var playbackPercent:uint = Math.round(100 * (channel.position / estimatedLength)); + + statusTextField.text = "Sound file's size is " + snd.bytesTotal + " bytes.\n" + + "Bytes being loaded: " + snd.bytesLoaded + "\n" + + "Percentage of sound file that is loaded " + loadPercent + "%.\n" + + "Sound playback is " + playbackPercent + "% complete."; + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + statusTextField.text = "The sound could not be loaded: " + errorEvent.text; + } + + private function soundCompleteHandler(event:Event):void { + statusTextField.text = "The sound has finished playing."; + removeEventListener(Event.ENTER_FRAME, enterFrameHandler); + } + } +} +
SoundChannel.stop()SoundMixer.stopAll()
bytesLoaded + Returns the currently available number of bytes in this sound object.uint + Returns the currently available number of bytes in this sound object. This property is + usually useful only for externally loaded files. + + bytesTotal + Returns the total number of bytes in this sound object.int + Returns the total number of bytes in this sound object. + + id3 + Provides access to the metadata that is part of an MP3 file.flash.media:ID3Info + Provides access to the metadata that is part of an MP3 file. + +

MP3 sound files can contain ID3 tags, which provide metadata about the + file. If an MP3 sound that you load using the Sound.load() + method contains ID3 tags, you can query these properties. Only ID3 tags + that use the UTF-8 character set are supported.

+ +

Flash Player 9 and later and AIR support + ID3 2.0 tags, + specifically 2.3 and 2.4. The following tables list the standard ID3 2.0 tags + and the type of content the tags represent. The Sound.id3 property provides + access to these tags through the format + my_sound.id3.COMM, my_sound.id3.TIME, and so on. The first + table describes tags that can be accessed either through the ID3 2.0 property name or + the ActionScript property name. The second table describes ID3 tags that are supported but do not have + predefined properties in ActionScript.

+ + ID3 2.0 tagCorresponding Sound class propertyCOMMSound.id3.commentTALBSound.id3.album TCONSound.id3.genreTIT2Sound.id3.songName TPE1Sound.id3.artistTRCKSound.id3.track TYERSound.id3.year + +

The following table describes ID3 tags that are supported but do not have + predefined properties in the Sound class. You access them by calling + mySound.id3.TFLT, mySound.id3.TIME, and so on. NOTE: None of + these tags are supported in Flash Lite 4.

+ PropertyDescriptionTFLTFile typeTIMETimeTIT1Content group descriptionTIT2Title/song name/content descriptionTIT3Subtitle/description refinementTKEYInitial keyTLANLanguagesTLENLengthTMEDMedia typeTOALOriginal album/movie/show titleTOFNOriginal filenameTOLYOriginal lyricists/text writersTOPEOriginal artists/performersTORYOriginal release yearTOWNFile owner/licenseeTPE1Lead performers/soloistsTPE2Band/orchestra/accompanimentTPE3Conductor/performer refinementTPE4Interpreted, remixed, or otherwise modified byTPOSPart of a setTPUBPublisherTRCKTrack number/position in setTRDARecording datesTRSNInternet radio station nameTRSOInternet radio station ownerTSIZSizeTSRCISRC (international standard recording code)TSSESoftware/hardware and settings used for encodingTYERYearWXXXURL link frame + + +

When using this property, consider the Flash Player security model:

+ +
  • The id3 property of a Sound object is always permitted for SWF files + that are in the same security sandbox as the sound file. For files in other sandboxes, there + are security checks.
  • When you load the sound, using the load() method of the Sound class, you can + specify a context parameter, which is a SoundLoaderContext object. If you set the + checkPolicyFile property of the SoundLoaderContext object to true, Flash Player + checks for a URL policy file on the server from which the sound is loaded. If a + policy file exists and permits access from the domain of the loading SWF file, then the file is allowed + to access the id3 property of the Sound object; otherwise it is not.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example reads the ID3 information from a sound file and displays + it in a text field. + +

In the constructor, the sound file is loaded but it is not set to play. Here, it is + assumed that the file is in the SWF directory. The system must have permission + in order to read the ID3 tags of a loaded sound file. If there is ID3 information in + the file and the program is permitted to read it, an Event.ID3 event will + be fired and the id3 property of the sound file will be populated. + The id3 property contains an ID3Info object with all + of the ID3 information.

+ +

In the id3Handler() method, the file's ID3 tags + are stored in id3, an ID3Info class object. A text field is + instantiated to display the list of the ID3 tags. The for loop iterates + through all the ID3 2.0 tags and appends the name and value to the content of + the text field. Using ID3 info (ID3Info) properties, the artist, + song name, and album are also appended. ActionScript 3.0 + and Flash Player 9 and later support ID3 2.0 tags, specifically 2.3 and 2.4. + If you iterate through properties like in the for loop, only ID3 2.0 tags will appear. + However, the data from the earlier versions are also stored in the song's id3 + property and can be accessed using ID3 info class properties. + The tags for the ID3 1.0 are at the end of the file while the ID3 2.0 tags are in + the beginning of the file. (Sometimes, the files may have both earlier and later version + tags in the same place.) If a file encoded with both version 1.0 and 2.0 tags at the + beginning and the end of the file, the method id3Handler() will be invoked twice. + It first reads the 2.0 version and then the version 1.0. If only ID3 1.0 tag is available, + then the information is accessible via the ID3 info properties, like id3.songname. + For ID3 2.0, id3.TITS property will retrieve the song name using the new tag (TITS).

+ +

Note that no error handling is written for this example and if the ID3 content is long, + the result may go beyond the viewable area.

+ + +package { + import flash.display.Sprite; + import flash.media.Sound; + import flash.net.URLRequest; + import flash.media.ID3Info; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.Event; + + public class Sound_id3Example extends Sprite { + private var snd:Sound = new Sound(); + private var myTextField:TextField = new TextField(); + + public function Sound_id3Example() { + snd.addEventListener(Event.ID3, id3Handler); + snd.load(new URLRequest("mySound.mp3")); + } + + private function id3Handler(event:Event):void { + var id3:ID3Info = snd.id3; + + myTextField.autoSize = TextFieldAutoSize.LEFT; + myTextField.border = true; + + myTextField.appendText("Received ID3 Info: \n"); + + for (var propName:String in id3) { + myTextField.appendText(propName + " = " + id3[propName] + "\n"); + } + + myTextField.appendText("\n" + "Artist: " + id3.artist + "\n"); + myTextField.appendText("Song name: " + id3.songName + "\n"); + myTextField.appendText("Album: " + id3.album + "\n\n"); + + this.addChild(myTextField); + } + } +} +
SoundLoaderContext.checkPolicyFile
isBuffering + Returns the buffering state of external MP3 files.Boolean + Returns the buffering state of external MP3 files. If the value is true, + any playback is + currently suspended while the object waits for more data. + + isURLInaccessible + Indicates if the Sound.url property has been + truncated.Boolean + Indicates if the Sound.url property has been + truncated. When the isURLInaccessible value is true the + Sound.url value is only the domain of the final URL from which the sound loaded. + For example, the property is truncated if the sound is loaded from http://www.adobe.com/assets/hello.mp3, + and the Sound.url property has the value http://www.adobe.com. + The isURLInaccessible value is true only when all of the following are also true: + +
  • An HTTP redirect occurred while loading the sound file.
  • The SWF file calling Sound.load() is from a different domain than + the sound file's final URL.
  • The SWF file calling Sound.load() does not have permission to access + the sound file. Permission is granted to access the sound file the same way permission is granted + for the Sound.id3 property: establish a policy file and use the SoundLoaderContext.checkPolicyFile + property.
+ +

Note: The isURLInaccessible property was added for Flash Player 10.1 and AIR 2.0. + However, this property is made available to SWF files of all versions when the + Flash runtime supports it. So, using some authoring tools in "strict mode" causes a compilation error. To work around the error + use the indirect syntax mySound["isURLInaccessible"], or disable strict mode. If you are using Flash Professional CS5 + or Flex SDK 4.1, you can use and compile this API for runtimes released before Flash Player 10.1 and AIR 2.

+ +

For application content in AIR, the value of this property is always false.

+ +
urlid3flash.media.SoundLoaderContext.checkPolicyFile
length + The length of the current sound in milliseconds.Number + The length of the current sound in milliseconds. + + url + The URL from which this sound was loaded.String + The URL from which this sound was loaded. This property is applicable only to Sound + objects that were loaded using the Sound.load() method. For + Sound objects that are associated with a sound asset from a SWF file's library, the + value of the url property is null. + +

When you first call Sound.load(), the url property + initially has a value of null, because the final URL is not yet known. + The url property will have a non-null value as soon as an + open event is dispatched from the Sound object.

+ +

The url property contains the final, absolute URL from which a sound was + loaded. The value of url is usually the same as the value passed to the + stream parameter of Sound.load(). + However, if you passed a relative URL to Sound.load() + the value of the url property represents the absolute URL. + Additionally, if the original URL request is redirected by an HTTP server, the value + of the url property reflects the final URL from which the sound file was actually + downloaded. This reporting of an absolute, final URL is equivalent to the behavior of + LoaderInfo.url.

+

In some cases, the value of the url property is truncated; see the + isURLInaccessible property for details.

+ + +
load()flash.display.LoaderInfo.urlisURLInaccessible
MicrophoneEnhancedMode + The MicrophoneEnhancedMode class is an enumeration of constant values used in setting the mode property + of MicrophoneEnhancedOptions class.Object + The MicrophoneEnhancedMode class is an enumeration of constant values used in setting the mode property + of MicrophoneEnhancedOptions class. + + flash.media.MicrophoneEnhancedOptionsFULL_DUPLEX + Use this mode to allow both parties to talk at the same time.fullDuplexString + Use this mode to allow both parties to talk at the same time. Acoustic echo cancellation operates in full-duplex mode. + Full-duplex mode is the highest quality echo cancellation. This mode requires + high-quality microphones and speakers and the most computing power. Do not use this mode with a USB microphone. + + HALF_DUPLEX + Use this mode for older and lower-quality speakers and microphones.halfDuplexString + Use this mode for older and lower-quality speakers and microphones. Acoustic echo cancellation operates in half-duplex mode. + In half-duplex mode, only one party can speak at a time. Half-duplex mode requires simpler + processing than full-duplex mode. Half-duplex mode is the default mode for USB microphone devices. + +

If the application uses the default enhancedOptions setting and a USB mic, Flash Player automatically switches to halfDuplex mode. + If the application uses the default enhancedOptions setting and the built-in microphone, Flash Player uses fullDuplex mode.

+ +
HEADSET + Use this mode when both parties are using headsets.headsetString + Use this mode when both parties are using headsets. Acoustic echo cancellation operates in low-echo mode. This mode requires the least amount + of computing power. + + OFF + All enhanced audio functionality is turned off.offString + All enhanced audio functionality is turned off. + + SPEAKER_MUTE + Use this mode when the speaker is muted.speakerMuteString + Use this mode when the speaker is muted. Acoustic echo cancellation is turned off. Enhanced audio performs + noise suppression or automatic gain control (if enabled). + + flash.media.MicrophoneEnhancedOptions.autoGain
Video + + The Video class displays live or recorded video in an application + without embedding the video in your SWF file.flash.display:DisplayObject + + The Video class displays live or recorded video in an application + without embedding the video in your SWF file. + This class creates a Video object that plays + either of the following kinds of video: recorded video files stored on a server or locally, + or live video captured by the user. + A Video object is a display object on the application's display list and represents + the visual space in which the video runs in a user interface. + +

+ When used with Flash Media Server, the Video object allows you to + send live video captured by a user to the server and then + broadcast it from the server to other users. + Using these features, you can develop media applications such as + a simple video player, a video player with multipoint publishing from + one server to another, or a video sharing application for a user community. +

+ +

+ Flash Player 9 and later supports publishing and playback of FLV files encoded + with either the Sorenson Spark or On2 VP6 codec and also supports an alpha channel. The On2 + VP6 video codec uses less bandwidth than older technologies and offers additional deblocking + and deringing filters. See the flash.net.NetStream class for more information about video playback and supported + formats.

+ + +

+ Flash Player 9.0.115.0 and later supports mipmapping to optimize runtime rendering quality and performance. + For video playback, Flash Player uses mipmapping optimization if you set the Video object's smoothing + property to true. +

+ +

+ As with other display objects on the display list, + you can control various properties of Video objects. For example, + you can move the Video object around on the Stage by using its x and + y properties, you can change its size using its height + and width properties, and so on. +

+ +

+ To play a video stream, use attachCamera() or attachNetStream() + to attach the video to the Video object. Then, add the Video object + to the display list using addChild(). +

+ +

+ If you are using Flash Professional, you can also place the Video object on the Stage + rather than adding it with addChild(), like this: +

+ +
  1. If the Library panel isn't visible, select Window > Library to display it.
  2. Add an embedded Video object to the library by clicking the Options menu on + the right side of the Library panel title bar and selecting New Video.
  3. In the Video Properties dialog box, name the embedded Video object for use in the library + and click OK.
  4. Drag the Video object to the Stage and use the Property Inspector to give it + a unique instance name, such as my_video. (Do not name it Video.)
+ +

In AIR applications on the desktop, playing video in fullscreen mode disables any power and screen saving + features (when allowed by the operating system).

+ +

Note: + The Video class is not a subclass of the InteractiveObject class, so + it cannot dispatch mouse events. However, you can call the addEventListener() method + on the display object container that contains the Video object. +

+ +
The following example uses a Video object with the NetConnection and + NetStream classes to load and play an FLV file. To run this example, you need an FLV file + whose name and location match the variable passed to videoURL, + in this case, an FLV file called Video.flv that is in the same directory as the SWF file. +

In this example, the code that creates the Video and NetStream objects and calls + Video.attachNetStream() and NetStream.play() is placed + in a handler function. The handler is called only if the + attempt to connect to the NetConnection object is successful, which is + when the netStatus event returns an info object with a code + property that indicates success. + It is recommended that you wait for a successful connection before calling + NetStream.play().

+ + + package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + + public class VideoExample extends Sprite { + private var videoURL:String = "Video.flv"; + private var connection:NetConnection; + private var stream:NetStream; + + public function VideoExample() { + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Unable to locate video: " + videoURL); + break; + } + } + + private function connectStream():void { + stream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + var video:Video = new Video(); + video.attachNetStream(stream); + stream.play(videoURL); + addChild(video); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function asyncErrorHandler(event:AsyncErrorEvent):void { + // ignore AsyncErrorEvent events. + } + } + } +
attachCamera()attachNetStream()flash.media.Camera.getCamera()flash.net.NetConnectionflash.net.NetStreamflash.display.DisplayObjectContainer.addChild()flash.display.Stage.addChild()Working with VideoVideo + Creates a new Video instance.widthint320The width of the video, in pixels. + heightint240The height of the video, in pixels. + + + Creates a new Video instance. If no values for the width and + height parameters are supplied, + the default values are used. You can also set the width and height properties of the + Video object after the initial construction, using Video.width and + Video.height. + When a new Video object is created, values of zero for width or height are not allowed; + if you pass zero, the defaults will be applied. + +

After creating the Video, call the + DisplayObjectContainer.addChild() or DisplayObjectContainer.addChildAt() + method to add the Video object to a parent DisplayObjectContainer object.

+ +
The following example shows how to load an external FLV file: + +var MyVideo:Video = new Video(); +addChild(MyVideo); + +var MyNC:NetConnection = new NetConnection(); +MyNC.connect(null); + +var MyNS:NetStream = new NetStream(MyNC); +MyNS.play("http://www.helpexamples.com/flash/video/clouds.flv"); + +MyVideo.attachNetStream(MyNS); + +//the clouds.flv video has metadata we're not using, so create +//an error handler to ignore the message generated by the runtime +//about the metadata +MyNS.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + +function asyncErrorHandler(event:AsyncErrorEvent):void +{ + //ignore metadata error message +} +
attachCamera + Specifies a video stream from a camera to be displayed + within the boundaries of the Video object in the application.cameraflash.media:CameraA Camera object that is capturing video data. + To drop the connection to the Video object, pass null. + + + Specifies a video stream from a camera to be displayed + within the boundaries of the Video object in the application. + +

+ Use this method to attach live video captured by the user + to the Video object. You can play the live video locally on the same computer + or device on which it is being captured, or you can send it to Flash Media Server and + use the server to stream it to other users. +

+ +

Note: In an iOS AIR application, camera video cannot be displayed when the application + uses GPU rendering mode.

+ +
Please see the Camera.getCamera() method example for an + illustration of how to use this method. +
Video.attachNetStream()flash.media.Camera
attachNetStream + Specifies a video stream to be displayed within the boundaries of the Video object + in the application.netStreamflash.net:NetStreamA NetStream object. To drop the connection to the Video object, pass + null. + + + Specifies a video stream to be displayed within the boundaries of the Video object + in the application. + The video stream is either a video file played + with NetStream.play(), a Camera object, or null. + If you use a video file, it can be stored on the local file system or on + Flash Media Server. + If the value of the netStream argument is + null, the video is no longer played in the Video object. + +

+ You do not need to use this method if a video file contains only audio; the audio + portion of video files is played automatically + when you call NetStream.play(). To control the audio + associated with a video file, use the soundTransform property + of the NetStream object that plays the video file. +

+ +
Please see the example at the end of this + class for an illustration of how to use this method. + +
Video.attachCamera()flash.net.NetStream.soundTransformflash.net.NetStream.play()SoundTransform
clear + Clears the image currently displayed in the Video object (not the video stream). + Clears the image currently displayed in the Video object (not the video stream). This method is useful for + handling the current image. For example, you can clear the last image or display standby information + without hiding the Video object. + + Video.attachCamera()deblocking + Indicates the type of filter applied to decoded video as part of post-processing.int + Indicates the type of filter applied to decoded video as part of post-processing. + The default value is 0, which lets the video compressor apply a deblocking filter as needed. + +

Compression of video can result in undesired artifacts. You can use the + deblocking property to set filters that reduce blocking and, + for video compressed using the On2 codec, ringing.

+ +

Blocking refers to visible imperfections between the boundaries + of the blocks that compose each video frame. Ringing refers to distorted + edges around elements within a video image.

+ +

Two deblocking filters are available: one in the Sorenson codec and one in the On2 VP6 codec. + In addition, a deringing filter is available when you use the On2 VP6 codec. + To set a filter, use one of the following values:

+ +
  • 0—Lets the video compressor apply the deblocking filter as needed.
  • 1—Does not use a deblocking filter.
  • 2—Uses the Sorenson deblocking filter.
  • 3—For On2 video only, uses the On2 deblocking filter but no deringing filter.
  • 4—For On2 video only, uses the On2 deblocking and deringing filter.
  • 5—For On2 video only, uses the On2 deblocking and a higher-performance + On2 deringing filter.
+ +

If a value greater than 2 is selected for video when you are using + the Sorenson codec, the Sorenson decoder defaults to 2.

+ +

Using a deblocking filter has an effect on overall playback performance, and it is usually + not necessary for high-bandwidth video. If a user's system is not powerful enough, + the user may experience difficulties playing back video with a deblocking filter enabled.

+ +
smoothing + Specifies whether the video should be smoothed (interpolated) when it is scaled.Boolean + Specifies whether the video should be smoothed (interpolated) when it is scaled. For + smoothing to work, the runtime must be in high-quality mode (the default). The default value + is false (no smoothing). +

For video playback using Flash Player 9.0.115.0 and later versions, set this property to + true to take advantage of mipmapping image optimization.

+ +
videoHeight + An integer specifying the height of the video stream, in pixels.int + An integer specifying the height of the video stream, in pixels. For live streams, this + value is the same as the Camera.height + property of the Camera object that is capturing the video stream. For recorded video files, this + value is the height of the video. +

You may want to use this property, for example, to ensure that the user is seeing the + video at the same size at which it was captured, + regardless of the actual size of the Video object on the Stage.

+ +
flash.media.Camera.height
videoWidth + An integer specifying the width of the video stream, in pixels.int + An integer specifying the width of the video stream, in pixels. For live streams, this + value is the same as the Camera.width + property of the Camera object that is capturing the video stream. For recorded video files, this + value is the width of the video. + +

You may want to use this property, for example, to ensure that the user is seeing the + video at the same size at which it was captured, + regardless of the actual size of the Video object on the Stage.

+ +
flash.media.Camera.width
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.net.dns.xml b/language-server/playerglobal_docs/flash.net.dns.xml new file mode 100644 index 0000000..293c325 --- /dev/null +++ b/language-server/playerglobal_docs/flash.net.dns.xml @@ -0,0 +1,270 @@ +flash.net.dnsAAAARecord + + The AAAARecord class represents a Domain Name System (DNS) AAAA resource record containing an IPv6 address.flash.net.dns:ResourceRecord + The AAAARecord class represents a Domain Name System (DNS) AAAA resource record containing an IPv6 address. + +

AAAA resource records are returned by a DNSResolver object as a result of a DNS lookup of a domain name.

+ +
DNSResolver classARecord classSRVRecord classMXRecord classPTRRecord classAAAARecord + Creates an AAAA resource record. + Creates an AAAA resource record. + +

AAAA records are obtained from a DNS lookup using the DNSResolver class. Application code should not create + AAAARecord objects.

+ +
address + The IPv6 address.String + The IPv6 address. + +
PTRRecord + The PTRRecord class represents a Domain Name System (DNS) PTR resource record containing a canonical domain name.flash.net.dns:ResourceRecord + The PTRRecord class represents a Domain Name System (DNS) PTR resource record containing a canonical domain name. + +

PTR resource records are returned by a DNSResolver object as a result of a DNS lookup of an IP address.

+ +
DNSResolver classARecord classAAAARecord classMXRecord classSRVRecord classPTRRecord + Creates a PTR resource record. + Creates a PTR resource record. + +

PTR records are obtained from a DNS lookup using the DNSResolver class. Application code should not create + PTRRecord objects.

+ +
ptrdName + The canonical domain name assigned to the query IP address.String + The canonical domain name assigned to the query IP address. + +
ResourceRecord + The ResourceRecord class is the base class for Domain Name System (DNS) resource record classes.Object + The ResourceRecord class is the base class for Domain Name System (DNS) resource record classes. + +

DNS resource records are returned by a DNSResolver object as a result of a DNS lookup.

+ +
DNSResolver classname + The query string used to look up this resource record.String + The query string used to look up this resource record. + + ttl + The resource time-to-live (ttl) value.int + The resource time-to-live (ttl) value. + +

The length of time (in seconds) that the resource record is valid. Records should not be cached + for longer than this value. A ttl of zero means the record is volatile and must not be cached. A ttl + less than zero means that the resource record is not valid.

+ +
DNSResolver + The DNSResolver class lets you lookup Domain Name System (DNS) resource records.flash.events:EventDispatcher + The DNSResolver class lets you lookup Domain Name System (DNS) resource records. + +

AIR profile support: This feature is supported on + all desktop operating systems, but is not supported on mobile devices. It is partially supported + on AIR for TV devices. You can test for + support at run time using the DNSResolver.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

You can look up the following types of resource records:

+
  • ARecord: IPv4 address for a host.
  • AAAARecord: IPv6 address for a host.
  • MXRecord: mail exchange record for a host.
  • PTRRecord: host name for an IP address.
  • SRVRecord: service record for a service
+ +

The following table indicates DNS lookup support on AIR for TV devices. + Unsupported requests result in the DNSResolver object dispatching an flash.events.ErrorEvent object.

+ + Record type specified in DNSResolver.lookup()SupportARecordFull supportAAAARecordFull supportMXRecordNot supportedPTRRecordSupported only for IPv4 addresses, not for IPv6 addressesSRVRecordNot supported + + +
The following example shows how to look up the supported types of DNS records: + +package +{ + import flash.desktop.NativeApplication; + import flash.display.Sprite; + import flash.events.DNSResolverEvent; + import flash.events.ErrorEvent; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.net.dns.AAAARecord; + import flash.net.dns.ARecord; + import flash.net.dns.DNSResolver; + import flash.net.dns.MXRecord; + import flash.net.dns.PTRRecord; + import flash.net.dns.SRVRecord; + import flash.utils.getQualifiedClassName; + + public class DNSResolverExample extends Sprite + { + private var resolver:DNSResolver = new DNSResolver(); + + public function DNSResolverExample() + { + resolver.addEventListener( DNSResolverEvent.LOOKUP, lookupComplete ); + resolver.addEventListener( ErrorEvent.ERROR, lookupError ); + + //Look up records + resolver.lookup( "www.example.com", ARecord ); + resolver.lookup( "example.com", AAAARecord ); + resolver.lookup( "example.com", MXRecord ); + resolver.lookup( "208.77.188.166", PTRRecord ); + resolver.lookup( "127.0.0.1", PTRRecord ); + resolver.lookup( "2001:1890:110b:1e19:f06b:72db:7026:3d7a", PTRRecord ); + resolver.lookup( "_sip._tcp.example.com.", SRVRecord ); + resolver.lookup( "www.example.com", ARecord ); + + this.stage.nativeWindow.activate(); + } + + private function lookupComplete( event:DNSResolverEvent ):void + { + trace( "Query string: " + event.host ); + trace( "Record type: " + flash.utils.getQualifiedClassName( event.resourceRecords[0] ) + + ", count: " + event.resourceRecords.length ); + for each( var record in event.resourceRecords ) + { + if( record is ARecord ) trace( record.name + " : " + record.address ); + if( record is AAAARecord ) trace( record.name + " : " + record.address ); + if( record is MXRecord ) trace( record.name + " : " + record.exchange + ", " + record.preference ); + if( record is PTRRecord ) trace( record.name + " : " + record.ptrdName ); + if( record is SRVRecord ) trace( record.name + " : " + record.target + ", " + record.port + + ", " + record.priority + ", " + record.weight ); + } + } + + private function lookupError( error:ErrorEvent ):void + { + trace("Error: " + error.text ); + } + } +} +
ARecordAAAARecordMXRecordPTRRecordSRVRecorderror + Dispatched when an error occurred during a DNS lookup.flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + Dispatched when an error occurred during a DNS lookup. + + lookup + Dispatched when a DNS look-up is complete.flash.events.DNSResolverEvent.LOOKUPflash.events.DNSResolverEvent + Dispatched when a DNS look-up is complete. + + DNSResolver + Creates a DNSResolver object. + Creates a DNSResolver object. + + lookup + Looks up a DNS resource record based on a query string.The host parameter value is not an appropriate query string or the recordType class is not recognized. + + ArgumentErrorArgumentErrorhostStringthe query string, such as a host name, IP address, or service locator. + recordTypeClassThe class representing the type of DNS resource record to look up. + + + Looks up a DNS resource record based on a query string. + +

The lookup() method performs a DNS lookup asynchronously. + Listen for the lookup event to get the results of the lookup. Listen for + the error event to receive errors. Results are dispatched in a DNSResolverEvent + object.

+ +

To specify the type of resource record to look up, pass the corresponding class + in the recordType parameter. (Pass the class name itself and not a string + containing the class name.)

+ +

The content of the query string passed to the method depends on the type of + resource record being looked up. The following list illustrates the query string to use for + each record type.

+ + Record typeQuery stringExampleARecordhost name"example.com"AAAARecordhost name"example.com"MXRecordhost name"example.com"PTRRecordIP address"208.77.188.166"SRVRecord_service._protocol.host."_sip._tcp.example.com." + +
DNSResolverEventlookupflash.events:DNSResolverEventdispatched when the lookup is completed successfully. + dispatched when the lookup is completed successfully.errorflash.events:ErrorEventdispatched when the lookup fails (including when no records exist). + + dispatched when the lookup fails (including when no records exist).
isSupported + Indicates whether DNS lookups are supported on the client system.Boolean + Indicates whether DNS lookups are supported on the client system. + +
MXRecord + The MXRecord class represents a Domain Name System (DNS) MX resource record containing a mail exchange server address.flash.net.dns:ResourceRecord + The MXRecord class represents a Domain Name System (DNS) MX resource record containing a mail exchange server address. + +

MX resource records are returned by a DNSResolver object as a result of a DNS lookup on a domain name. + More than one record can be returned by a single lookup if more than one mail exchange is available.

+ +
DNSResolver classARecord classAAAARecord classPTRRecord classSRVRecord classMXRecord + Creates an MX resource record. + Creates an MX resource record. + +

MX records are obtained from a DNS lookup using the DNSResolver class. Application code should not create + MXRecord objects.

+ +
exchange + The host name of a mail exchange service.String + The host name of a mail exchange service. + + preference + The priority of the mail exchange identified by this record.int + The priority of the mail exchange identified by this record. + +

Lower values are higher priority.

+ +
ARecord + The ARecord class represents a Domain Name System (DNS) A resource record containing an IPv4 address.flash.net.dns:ResourceRecord + The ARecord class represents a Domain Name System (DNS) A resource record containing an IPv4 address. + +

A resource records are returned by a DNSResolver object as a result of a DNS lookup of a domain name.

+ +
DNSResolver classAAAARecord classMXRecord classPTRRecord classSRVRecord classARecord + Creates an A resource record. + Creates an A resource record. + +

A records are obtained from a DNS lookup using the DNSResolver class. Application code should not create + ARecord objects.

+ +
address + The IPv4 address.String + The IPv4 address. + +
SRVRecord + The SRVRecord class represents a Domain Name System (DNS) SRV resource record containing a service host.flash.net.dns:ResourceRecord + The SRVRecord class represents a Domain Name System (DNS) SRV resource record containing a service host. + +

SRV resource records are returned by a DNSResolver object as a result of a DNS lookup on a service locator. + More than one record can be returned by a single lookup if more than one service host is available.

+ +
DNSResolver classARecord classAAAARecord classMXRecord classPTRRecord classSRVRecord + Creates an SRV resource record. + Creates an SRV resource record. + +

SRV records are obtained from a DNS lookup using the DNSResolver class. Application code should not create + SRVRecord objects.

+ +
port + The port the service is using on the server.int + The port the service is using on the server. + + priority + The priority of the service host identified by this record.int + The priority of the service host identified by this record. + +

Lower values are higher priority.

+ +
target + The canonical host name of the server providing the service.String + The canonical host name of the server providing the service. + + weight + The relative weight to use when selecting from service hosts that have the same priority.int + The relative weight to use when selecting from service hosts that have the same priority. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.net.drm.xml b/language-server/playerglobal_docs/flash.net.drm.xml new file mode 100644 index 0000000..0571d25 --- /dev/null +++ b/language-server/playerglobal_docs/flash.net.drm.xml @@ -0,0 +1,423 @@ +flash.net.drmVoucherAccessInfo + + A VoucherAccessInfo object presents the information that is required + to successfully retrieve and consume a voucher, such as the type + of authentication and the content domain of the media rights server.Object + A VoucherAccessInfo object presents the information that is required + to successfully retrieve and consume a voucher, such as the type + of authentication and the content domain of the media rights server. + + + authenticationMethod + The type of authentication required to obtain a voucher for the associated content.String + The type of authentication required to obtain a voucher for the associated content. + +

The supported types of authentication are:

+
  • AuthenticationMethod.ANONYMOUS — anyone can obtain a voucher.
  • AuthenticationMethod.USERNAME_AND_PASSWORD — the user must supply a valid + username and password of an account that is authorized to view the associated content.
+ +

The AuthenticationMethod class provides string constants to use with the + authenticationMethod property.

+ +
displayName A user-friendly string that you can use to refer to the specified + VoucherAccessInfo object in the user interface.String A user-friendly string that you can use to refer to the specified + VoucherAccessInfo object in the user interface. + +

If the metadata file for a piece of media content has multiple vouchers, + each with its own VoucherAccessInfo object, the user might need to decide + which voucher to authenticate to. For example, you might have + a subscription-level voucher with high privileges for viewing content, + as well as a basic-level voucher with lower privileges. To distinguish + between these two vouchers, use the descriptive string in the + displayName property. The string is set by the media + packager tool (the tool that packages and encrypts media in preparation + for distribution with a media rights server, such as Flash Access).

+ +

For applications that are localized, you can use this property as an identifier. + The application can detect the locale and localize the strings accordingly.

+ + +
domain + The content domain of the media rights server to which the user must be authenticated + to obtain the voucher for the associated content.String + The content domain of the media rights server to which the user must be authenticated + to obtain the voucher for the associated content. + +

If authentication is to the default domain or no authentication is required, + the value of domainName is null.

+ +

Note: The domain returned by this property has nothing to do with + network or Internet domain names. In this case, a domain is a group + of content or user accounts. For example, a single server could support several + domains, each with its own set of content channels and subscribers.

+ +
DRMContentData + The DRMContentData class provides the information required to + obtain the voucher necessary to view DRM-protected content.Object + The DRMContentData class provides the information required to + obtain the voucher necessary to view DRM-protected content. + +

(AIR only) A DRMContentData object can be obtained from a NetStream instance by calling + the NetStream preloadEmbeddedContent() method and providing an + onDRMContentData callback function on the NetStream client object. + Use the DRMContentData object passed to the callback function as a parameter + for the DRMManager loadVoucher() method.

+ +

When you package content with Flash Access, you have the option of saving the content's metadata + as a separate file. To create a new DRMContentData object, get this metadata with a URLLoader object + and pass it to the DRMContentData constructor.

+ +
flash.net.NetStreamflash.net.drm.DRMManagerflash.net.drm.DRMVoucherDRMContentData + Constructor.rawDataflash.utils:ByteArraynull + Constructor. + + getVoucherAccessInfo + Retrieves an array of VoucherAccessInfo objects. + Retrieves an array of VoucherAccessInfo objects. The array contains at least 1 + VoucherAccessInfo object, the default. + +

Each VoucherAccessInfo object represents a policy, which contains + the requirements for retrieving a voucher from the media rights server. + For example, if the server requires the user to authenticate, the VoucherAccessInfo object + contains the authentication method. If the server requires the computer to be registered + with a Realm server, the object contains the URL to the Realm server.

+ +
authenticationMethod + The type of authentication required to obtain a voucher for the associated content.String + The type of authentication required to obtain a voucher for the associated content. + +

The supported types of authentication are:

+
  • AuthenticationMethod.ANONYMOUS — anyone can obtain a voucher.
  • AuthenticationMethod.USERNAME_AND_PASSWORD — the user must supply a valid + username and password of an account that is authorized to view the associated content.
+ +

The AuthenticationMethod class provides string constants to use with the + authenticationMethod property.

+ +
domain + The content domain of the media rights server to which the user must be authenticated + to obtain the voucher for the associated content.String + The content domain of the media rights server to which the user must be authenticated + to obtain the voucher for the associated content. + +

If authentication is to the default domain or no authentication is required, + the value of domainName is null.

+ +

Note: The domain returned by this property has nothing to do with + network or Internet domain names. In this case, a domain is a group + of content or user accounts. For example, a single server could support several + domains, each with its own set of content channels and subscribers.

+ +
licenseID + A unique id identifying the content associated with this metadata on + the media rights server.String + A unique id identifying the content associated with this metadata on + the media rights server. + + serverURL + The URL of a media rights server that + provides the voucher that is required to view the associated content.String + The URL of a media rights server that + provides the voucher that is required to view the associated content. + +
DRMVoucher + The DRMVoucher class is a handle to the license token that allows a user to view DRM-protected content.Object + The DRMVoucher class is a handle to the license token that allows a user to view DRM-protected content. + +

The DRMVoucher properties describe the viewing rights conferred by the voucher. You can get a voucher + using the loadVoucher() method of the DRMManager object. This method + requires a DRMContentData object, obtained with the preloadEmbeddedMetadata() + method of the NetStream class (AIR only) or by using the DRMContentData() constructor. + When using a media rights server such as Flash Access, you can get a DRMContentData object + from the metadata generated by the media packager tool.

+ +
flash.net.drm.DRMContentDataflash.net.drm.DRMManager.loadVoucher()flash.net.NetStream.preloadEmbeddedData()offlineLeaseEndDate + The date and time at which this voucher expires for offline playback.Date + The date and time at which this voucher expires for offline playback. + +

If a voucher is only valid for the current online session, + offlineLeaseStartDate is null.

+ +
offlineLeaseStartDate + The date and time at which this voucher becomes valid for offline playback.Date + The date and time at which this voucher becomes valid for offline playback. + +

If a voucher is only valid for the current online session, + offlineLeaseStartDate is null.

+ +
playbackTimeWindow + The time period, after the first viewing, during which + the associated content can be viewed or reviewed.flash.net.drm:DRMPlaybackTimeWindow + The time period, after the first viewing, during which + the associated content can be viewed or reviewed. + +

The time period allotted for viewing begins when the user first views the content + and ends after the allotted amount of time has elapsed. If no time is allotted, + the value of the playbackTimeWindow property is null.

+ +
policies + A dynamic object that reports policies defined by the application.Object + A dynamic object that reports policies defined by the application. + +

The policy object contains a name-value pair for each policy in effect.

+ +
voucherEndDate + The date on which this voucher expires.Date + The date on which this voucher expires. + + voucherStartDate + The beginning of this voucher's validity period.Date + The beginning of this voucher's validity period. + +
DRMPlaybackTimeWindow + The DRMPlaybackTimeWindow class represents the period of time during which a + DRM voucher is valid.Object + The DRMPlaybackTimeWindow class represents the period of time during which a + DRM voucher is valid. + +

The startDate and endDate properties are + null until the first time that the user views the content.

+ +
flash.net.drm.DRMVoucherendDate + The end date for the period of time during which a DRM voucher is valid + (the playback window).Date + The end date for the period of time during which a DRM voucher is valid + (the playback window). + +

The endDate is null if the + playback window has not started.

+ +
period + The period of time during which a DRM voucher is valid + (the playback window), in seconds.uint + The period of time during which a DRM voucher is valid + (the playback window), in seconds. + + startDate + The start date for the period of time during which a DRM voucher is valid + (the playback window).Date + The start date for the period of time during which a DRM voucher is valid + (the playback window). + +

The startDate is null if the + playback window has not started.

+ +
LoadVoucherSetting + The LoadVoucherSetting class provides string constants for use + with the settings parameter of the DRMManager loadVoucher() method.Defines constants for setting the DRMManager voucher loading options. + Object + The LoadVoucherSetting class provides string constants for use + with the settings parameter of the DRMManager loadVoucher() method. + + ALLOW_SERVER + Loads the voucher from the local cache, if possible; downloads the voucher from a media rights server + only if a locally cached copy does not exist.allowServerString + Loads the voucher from the local cache, if possible; downloads the voucher from a media rights server + only if a locally cached copy does not exist. + + FORCE_REFRESH + Downloads the voucher from the media rights server only.forceRefreshString + Downloads the voucher from the media rights server only. Does not load the voucher from the local cache. + + LOCAL_ONLY + Loads the voucher from the local cache only.localOnlyString + Loads the voucher from the local cache only. Does not download the voucher from a media rights server. + + AuthenticationMethod + The AuthenticationMethod class provides string constants enumerating the + different types of authentication used by the authenticationMethod + property of the DRMContentData class.Object + The AuthenticationMethod class provides string constants enumerating the + different types of authentication used by the authenticationMethod + property of the DRMContentData class. + + flash.net.drm.DRMContentDataANONYMOUS + Indicates that no authentication is required.anonymousString + Indicates that no authentication is required. + + USERNAME_AND_PASSWORD + Indicates that a valid user name and password are required.usernameAndPasswordString + Indicates that a valid user name and password are required. + + DRMManager + The DRMManager manages the retrieval and storage of the vouchers needed to view + DRM-protected content.flash.events:EventDispatcher + The DRMManager manages the retrieval and storage of the vouchers needed to view + DRM-protected content. With the static DRMManager.getDRMManager() method, you can + access the existing DRMManager object to perform the following DRM-management tasks: + +
  • Preload vouchers from a media rights server, using a DRMContentData object.
  • Query the local cache for an individual voucher, using a DRMContentData object.
  • Reset all vouchers (AIR only)
+ +

No method is provided for enumerating all the vouchers in the local cache.

+ +

Do not create an instance of the DRMManager class. Use the static + DRMManager.getDRMManager() to access the existing DRMManager object.

+ +

AIR profile support: This feature is supported + on all desktop operating systems and AIR for TV devices, but it is not supported on mobile devices. You can test + for support at run time using the DRMManager.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +
flash.net.NetStreamflash.net.drm.DRMVoucherflash.net.drm.DRMContentDatadrmError + The DRMManager dispatches a DRMErrorEvent object when a requested voucher + cannot be obtained from the media rights server.flash.events.DRMErrorEvent.DRM_ERRORflash.events.DRMErrorEvent + The DRMManager dispatches a DRMErrorEvent object when a requested voucher + cannot be obtained from the media rights server. + +

Note: When an attempt to load a voucher from the local voucher cache + (using the localOnly as the source parameter) fails, + a DRMErrorEvent object is not dispatched. Instead, a DRMStatusEvent object with a + voucher property set to null is dispatched.

+ +
drmStatus + The DRMManager dispatches a DRMStatusEvent object when a requested voucher + is obtained from the media rights server.flash.events.DRMStatusEvent.DRM_STATUSflash.events.DRMStatusEvent + The DRMManager dispatches a DRMStatusEvent object when a requested voucher + is obtained from the media rights server. + + authenticationError + The DRMManager dispatches a DRMAuthenticationErrorEvent object when the user is not authenticated + by the media rights server after a call to the authenticate() method.flash.events.DRMAuthenticationErrorEvent.AUTHENTICATION_ERRORflash.events.DRMAuthenticationErrorEventDispatched by the DRMManager object when user authentication fails. + + + The DRMManager dispatches a DRMAuthenticationErrorEvent object when the user is not authenticated + by the media rights server after a call to the authenticate() method. + authenticationComplete + The DRMManager dispatches a DRMAuthenticationCompleteEvent object when the user is authenticated + by the media rights server after a call to the authenticate() method.flash.events.DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETEflash.events.DRMAuthenticationCompleteEventDispatched by the DRMManager object when user authentication is complete. + + + The DRMManager dispatches a DRMAuthenticationCompleteEvent object when the user is authenticated + by the media rights server after a call to the authenticate() method. + + authenticate + Authenticates a user.serverURLStringThe URL of a media rights server that can provide a voucher for viewing protected content + domainStringA domain on the server (not a network or Internet domain name) + usernameStringThe user name + passwordStringThe user password + + + Authenticates a user. + +

Listen for the authenticationComplete and authenticationError events to determine the + outcome of the authentication attempt. Multiple authenticate() calls are queued. The + AuthenticationCompleteEvent object dispatched for the authenticationComplete event + contains contains an authentication token that your application can save.

+ +

You can use a saved authentication token, or a token downloaded by another means, + to establish an authenticated session with the media rights server in the future. To establish a + session using a token, call the DRMManager setAuthenticationToken() method. The properties + of the token, such as expiration date, are determined by the settings of the server that generates the + token.

+ +

Important (AIR only): The authenticate() method will not succeed when a user's Internet connection passes + through a proxy server requiring authentication. Although such users are not able to preload a DRM voucher that requires + authentication, your application can obtain the voucher by beginning playback and using the NetStream + setAuthenticationCredentials() method to log the user into both the proxy and the media rights servers. + Once the voucher has been obtained, the user can view the content offline (as long as the license represented by the + voucher allows offline playback).

+ +
flash.net.NetStream.setAuthenticationCredentials()setAuthenticationToken()
getDRMManager + Returns an instance of the singleton DRMManager object.flash.net.drm:DRMManager + Returns an instance of the singleton DRMManager object. + +

One DRMManager instance exists for each security domain.

+ +
flash.system.SecurityDomain
loadPreviewVoucher + Gets a preview voucher from the license server, which you can use to let a user verify + that they can play content on particular computer.contentDataflash.net.drm:DRMContentData + Gets a preview voucher from the license server, which you can use to let a user verify + that they can play content on particular computer. This capability lets users + verify that they can play content on their computer before buying and downloading the content. It is + useful when the user's computer doesn't have the necessary output protection + capabilities or necessary software to play content. + +

Like loadVoucher(), this method is an asynchronous call + and issues a DRMStatusEvent on completion or a DRMErrorEvent in case of errors.

+ +
loadVoucher + Loads a voucher from a media rights server or the local voucher cache.contentDataflash.net.drm:DRMContentDataThe DRMContentData object from a DRM-protected media file + settingStringDetermines whether the voucher is retrieved from the local cache or the media rights server + + + Loads a voucher from a media rights server or the local voucher cache. + +

The voucher is loaded according to the setting parameter:

+
  • LoadVoucherSetting.FORCE_REFRESH: The voucher is always downloaded from the media rights server.
  • LoadVoucherSetting.LOCAL_ONLY: The voucher is only loaded from the local cache.
  • LoadVoucherSetting.ALLOW_SERVER: The voucher is loaded from the local cache, if possible, but + otherwise is downloaded from the server.
+

The LoadVoucherSetting class defines string constants to use as values for the setting + parameter.

+ +

When the voucher is successfully loaded, the DRMManager dispatches a DRM status event. Your application can + begin playback as soon as the voucher is loaded. The loaded voucher is available in the voucher + property of the dispatched DRMStatusEvent object. You can use this voucher object to display the associated media + rights information to the user.

+ +

If a voucher cannot be loaded from the media rights server, a DRM error event is dispatched. The errorID property + of the dispatched DRMErrorEvent object indicates the reason for the failure. Common causes of failure include + attempting to connect to the media rights server when the user is offline and attempting to load a + voucher when the user is not logged in. Your application can respond to these errors and take corrective action. + For example, if authentication credentials are required to download the voucher, you can prompt the user + for their account user name and password, call the DRMManager authenticate() method, and then attempt + to load the voucher again.

+ +

If a voucher cannot be obtained from the local cache and the localOnly setting is used, a + DRMErrorEvent is not dispatched. Instead, a DRM status event is dispatched. The detail property of + this DRMStatusEvent object is still DRM.voucherObtained, but the voucher property + is null.

+ +
resetDRMVouchers + Deletes all locally cached digital rights management (DRM) voucher data.The voucher data cannot be deleted. + + IOErrorflash.errors:IOError + Deletes all locally cached digital rights management (DRM) voucher data. +

+ The application must download the required vouchers again for the user to be able to access encrypted content. + Calling this function is equivalent to calling Netstream.resetDRMVouchers().

+ +
flash.net.NetStream.resetDRMVouchers()
setAuthenticationToken + Sets the authentication token to use for communication with the specified server and domain.serverUrlStringThe URL of the media rights server + domainStringThe domain on the media rights server + tokenflash.utils:ByteArrayThe authentication token + + + Sets the authentication token to use for communication with the specified server and domain. + +

Authentication tokens are available from the token property of the + DRMAuthenticationCompleteEvent object dispatched after a successful call to the authenticate() + method. The token is cached automatically for the session, but you can use the + setAuthenticationToken() method to manage tokens directly.

+ +

Setting a token overwrites any existing cached token for the server and domain. + Set the token parameter to null to clear the cached token.

+ +
isSupported + The isSupported property is set to true if the + DRMManager class is supported on the current platform, otherwise it is + set to false.BooleanReports whether the DRMManager class is supported on the client system. + + + The isSupported property is set to true if the + DRMManager class is supported on the current platform, otherwise it is + set to false. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.net.xml b/language-server/playerglobal_docs/flash.net.xml new file mode 100644 index 0000000..2e852f4 --- /dev/null +++ b/language-server/playerglobal_docs/flash.net.xml @@ -0,0 +1,12848 @@ +flash.netXMLSocket + + + The XMLSocket class implements client sockets that let the + Flash Player or AIR application communicate + with a server computer identified by an IP address or domain name.flash.events:EventDispatcher + + The XMLSocket class implements client sockets that let the + Flash Player or AIR application communicate + with a server computer identified by an IP address or domain name. The XMLSocket class is useful for + client-server applications that require low latency, such as real-time chat systems. A traditional + HTTP-based chat solution frequently polls the server and downloads new messages using an HTTP + request. In contrast, an XMLSocket chat solution maintains an open connection to the server, which + lets the server immediately send incoming messages without a request from the client. + To use the XMLSocket class, the server computer must run a daemon that understands the protocol used + by the XMLSocket class. The protocol is described in the following list: +
  • XML messages are sent over a full-duplex TCP/IP stream socket connection.
  • Each XML message is a complete XML document, terminated by a zero (0) byte.
  • An unlimited number of XML messages can be sent and received over a single XMLSocket + connection.
+ +

Setting up a server to communicate with the XMLSocket object can be challenging. If your application + does not require real-time interactivity, use the URLLoader class instead of the XMLSocket class.

+ +

To use the methods of the XMLSocket class, first use the constructor, new XMLSocket, + to create an XMLSocket object.

+ +

SWF files in the local-with-filesystem sandbox may not use sockets.

+ +

Socket policy files on the target host specify the hosts from which SWF files + can make socket connections, and the ports to which those connections can be made. + The security requirements with regard to socket policy files have become more stringent + in the last several releases of Flash Player. + In all versions of Flash Player, Adobe recommends the use of a socket policy file; + in some circumstances, a socket policy file is required. Therefore, if you + are using XMLSocket objects, make sure that the target host provides a socket policy file + if necessary.

+ +

The following list summarizes the requirements for socket policy files + in different versions of Flash Player:

+ +
  • In Flash Player 9.0.124.0 and later, a socket policy file is required for any XMLSocket connection. + That is, a socket policy file on the target host is required no matter what port + you are connecting to, and is required even if you are connecting + to a port on the same host that is serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, if you want to connect to a port number below 1024, + or if you want to connect to a host other than the one serving the SWF file, + a socket policy file on the target host is required.
  • In Flash Player 9.0.115.0, even if a socket policy file isn't required, + a warning is displayed when using the Flash Debug Player if the target host + doesn't serve a socket policy file.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example uses the class XMLSocketExample class to send data using + an XMLSocket and print information during XMLSocket events. This is accomplished using + the following steps: +
  1. The XMLSocketExample constructor creates a XMLSocket instance named socket and + passes socket to ConfigureListeners() (described below) and then calls the + connect() method of XMLSocket using the host name "localhost" and port + number of 8080.
  2. The configureListeners() method is then called, which adds listeners for each of the + supported XMLSocket events: +
    • closeHandler(): listens for the close event, which is dispatched + after the network connection has been closed.
    • connectHandler(): listens for the connect event, dispatched when the network + connection has been established.
    • dataHandler(): listens for the data events, dispatched every time + the XMLSocket receives new data.
    • progressHandler(): listens for the progress events, dispatched when a call to + send() has been made and while the send is ongoing.
    • securityErrorHandler(): listens for securityError events, which would be + dispatched if an attempt was made to access the XMLSocket with the wrong local playback security setting or + using a port lower than 1024.
    • ioErrorHandler(): listens for ioError events, which would happen only + if an operation to send or receive data failed.
+

Notes: +

  • You need to compile the SWF file with "Local playback security" set to "Access network only".
  • You need a server running on your domain using port 8080 for this example to work.
  • If you are running Flash Player 9.0.124.0 or later, you need to place a socket policy file on your server + that permits socket connections from your domain to port 8080. For information on serving socket policy files, + see the Flash Player Developer Center Topic: + + Setting up a socket policy file server.
+

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.XMLSocket; + + public class XMLSocketExample extends Sprite { + private var hostName:String = "localhost"; + private var port:uint = 8080; + private var socket:XMLSocket; + + public function XMLSocketExample() { + socket = new XMLSocket(); + configureListeners(socket); + if (hostName && port) { + socket.connect(hostName, port); + } + } + + public function send(data:Object):void { + socket.send(data); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CLOSE, closeHandler); + dispatcher.addEventListener(Event.CONNECT, connectHandler); + dispatcher.addEventListener(DataEvent.DATA, dataHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + } + + private function closeHandler(event:Event):void { + trace("closeHandler: " + event); + } + + private function connectHandler(event:Event):void { + trace("connectHandler: " + event); + } + + private function dataHandler(event:DataEvent):void { + trace("dataHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + } +} +
flash.net.URLLoader.load()flash.net.URLLoadersecurityError + Dispatched if a call to the XMLSocket.connect() method + attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched if a call to the XMLSocket.connect() method + attempts to connect either to a server outside the caller's security sandbox or to a port lower than 1024. + XMLSocket.connect()ioError + Dispatched when an input/output error occurs that causes a send or receive operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input/output error occurs that causes a send or receive operation to fail. + data + Dispatched after raw data is sent or received.flash.events.DataEvent.DATAflash.events.DataEvent + Dispatched after raw data is sent or received. + connect + Dispatched after a successful call to the XMLSocket.connect() method.flash.events.Event.CONNECTflash.events.Event + Dispatched after a successful call to the XMLSocket.connect() method. + close + Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event + Dispatched when the server closes the socket connection. + The close event is dispatched only when the server + closes the connection; it is not dispatched when you call the XMLSocket.close() method. + XMLSocket + Creates a new XMLSocket object.hostStringnullA fully qualified DNS domain name or an IP address in the form + .222.333.444. In Flash Player 9.0.115.0 and AIR 1.0 and later, + you can specify IPv6 addresses, such as rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]. + You can also specify null to connect to the host server + on which the SWF file resides. If the SWF file issuing this call is running in a web browser, + host must be in the same domain as the SWF file. + + portint0The TCP port number on the target host used to establish a connection. + In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file + specifying that socket connections are permitted from the host serving the SWF file + to the specified port. In earlier versions of Flash Player, a socket policy file is required + only if you want to connect to a port number below 1024, + or if you want to connect to a host other than the one serving the SWF file. + + + + Creates a new XMLSocket object. If no parameters are specified, an initially disconnected socket + is created. If parameters are specified, a connection is attempted to the specified host and port. + +

Note: It is strongly advised to use the constructor form without parameters, then + add any event listeners, then call the connect method with host + and port parameters. This sequence guarantees that all event listeners will work + properly.

+ +
connect()
close + Closes the connection specified by the XMLSocket object. + Closes the connection specified by the XMLSocket object. + The close event is dispatched only when the server + closes the connection; it is not dispatched when you call the close() method. + + connect()connect + Establishes a connection to the specified Internet host using the specified TCP port.Local untrusted files may not communicate with + the Internet. Work around this limitation by reclassifying the file + as local-with-networking or trusted. + SecurityErrorSecurityErrorYou may not specify a socket port higher than + 65535. + SecurityErrorSecurityErrorhostStringA fully qualified DNS domain name or an IP address in the form + 111.222.333.444. You can also specify null to connect to the host server + on which the SWF file resides. If the calling file is a SWF file running in a web browser, + host must be in the same domain as the file. + + portintThe TCP port number on the target host used to establish a connection. + In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file + specifying that socket connections are permitted from the host serving the SWF file + to the specified port. In earlier versions of Flash Player, a socket policy file is required + only if you want to connect to a port number below 1024, + or if you want to connect to a host other than the one serving the SWF file. + + + + Establishes a connection to the specified Internet host using the specified TCP port. + +

If you specify null for the host parameter, the host + contacted is the one where the file calling XMLSocket.connect() resides. + For example, if the calling file was downloaded from www.adobe.com, specifying null + for the host parameter means you are connecting to www.adobe.com.

+ + +

You can prevent a file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content.

+ +

For more information, see the Flash Player Developer Center Topic: + Security.

+ +
flash.events.Event.CONNECTsecurityErrorflash.events:SecurityErrorEventA connect operation attempted + to connect to a host outside the caller's security sandbox, or + to a port that requires a socket policy file. Work around either problem by using + a socket policy file on the target host. + A connect operation attempted + to connect to a host outside the caller's security sandbox, or + to a port that requires a socket policy file.dataflash.events:DataEventDispatched when raw data has been received. + Dispatched when raw data has been received.connectflash.events:EventDispatched when network connection has been established. + + Dispatched when network connection has been established.
send + Converts the XML object or data specified in the object parameter + to a string and transmits it to the server, followed by a zero (0) byte.The XMLSocket object is not connected to the server. + + + IOErrorflash.errors:IOErrorobjectAn XML object or other data to transmit to the server. + + + Converts the XML object or data specified in the object parameter + to a string and transmits it to the server, followed by a zero (0) byte. If object + is an XML object, the string is the XML textual representation of the XML object. The + send operation is asynchronous; it returns immediately, but the data may be transmitted at a + later time. The XMLSocket.send() method does not return a value indicating whether + the data was successfully transmitted. + +

If you do not connect the XMLSocket object to the server using + XMLSocket.connect()), the XMLSocket.send() + operation fails.

+ +
connect()
connected + Indicates whether this XMLSocket object is currently connected.Boolean + Indicates whether this XMLSocket object is currently connected. You can also check + whether the connection succeeded by registering for the connect + event and ioError event. + + connectioErrortimeout + Indicates the number of milliseconds to wait for a connection.int + Indicates the number of milliseconds to wait for a connection. + +

If the connection doesn't succeed within the specified time, the connection fails. + The default value is 20,000 (twenty seconds).

+ +
IPVersion + The IPVersion class defines constants representing the different families of IP addresses.Object + The IPVersion class defines constants representing the different families of IP addresses. + + IPV4 + An Internet Protocol version 4 (IPv4) address.IPv4String + An Internet Protocol version 4 (IPv4) address. + +

IPv4 addresses are expressed in ActionScript as a string in dot-decimal notation, such as: "192.0.2.0".

+ +
IPV6 + An Internet Protocol version 6 (IPv6) address.IPv6String + An Internet Protocol version 6 (IPv6) address. + +

IPv6 addresses are expressed in ActionScript as a string in hexadecimal-colon notation and enclosed in + brackets, such as: "[2001:db8:ccc3:ffff:0:444d:555e:666f]".

+ +
Socket + The Socket class enables code to establish Transport Control Protocol (TCP) socket + connections for sending and receiving binary data.flash.utils:IDataInputflash.utils:IDataOutputflash.events:EventDispatcher + The Socket class enables code to establish Transport Control Protocol (TCP) socket + connections for sending and receiving binary data. + +

The Socket class is useful for working with servers that use binary protocols.

+ +

To use the methods of the Socket class, first use the constructor, new Socket, + to create a Socket object.

+ +

A socket transmits and receives data asynchronously.

+ +

On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such + as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably + across all operating systems, it is a good practice to call the flush() method after writing each message + (or related group of data) to the socket.

+ +

In Adobe AIR, Socket objects are also created when a listening ServerSocket receives a connection from an external process. + The Socket representing the connection is dispatched in a ServerSocketConnectEvent. Your application is responsible for + maintaining a reference to this Socket object. If you don't, the Socket object is eligible for garbage collection and may be + destroyed by the runtime without warning.

+ +

SWF content running in the local-with-filesystem security sandbox cannot use sockets.

+ +

Socket policy files on the target host specify the hosts from which SWF files + can make socket connections, and the ports to which those connections can be made. + The security requirements with regard to socket policy files have become more stringent + in the last several releases of Flash Player. + In all versions of Flash Player, Adobe recommends the use of a socket policy file; + in some circumstances, a socket policy file is required. Therefore, if you + are using Socket objects, make sure that the target host provides a socket policy file + if necessary.

+ +

The following list summarizes the requirements for socket policy files + in different versions of Flash Player:

+ +
  • In Flash Player 9.0.124.0 and later, a socket policy file is required for any socket connection. + That is, a socket policy file on the target host is required no matter what port + you are connecting to, and is required even if you are connecting + to a port on the same host that is serving the SWF file.
  • In Flash Player versions 9.0.115.0 and earlier, if you want to connect to a port number below 1024, + or if you want to connect to a host other than the one serving the SWF file, + a socket policy file on the target host is required.
  • In Flash Player 9.0.115.0, even if a socket policy file isn't required, + a warning is displayed when using the Flash Debug Player if the target host + doesn't serve a socket policy file.
  • In AIR, a socket policy file is not required for content running in the application + security sandbox. Socket policy files are required for any socket connection established + by content running outside the AIR application security sandbox.
+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security +

+ +
The following example reads from and writes to a socket and outputs information + transmitted during socket events. Highlights of the example follow: +
  1. The constructor creates a CustomSocket instance named socket and passes the + host name localhost and port 80 as arguments. Since CustomSocket extends + Socket, a call to super() calls Socket's constructor.
  2. The example then calls the configureListeners() method, which adds listeners for + Socket events.
  3. Finally, the socket connect() method is called with localhost as the + host name and 80 as the port number.
+ +

Note: To run the example, you need a server running on the same domain + where the SWF resides (in the example, localhost) and listening on port 80.

+ + +package { + import flash.display.Sprite; + + public class SocketExample extends Sprite { + + public function SocketExample() { + var socket:CustomSocket = new CustomSocket("localhost", 80); + } + } +} + +import flash.errors.*; +import flash.events.*; +import flash.net.Socket; + +class CustomSocket extends Socket { + private var response:String; + + public function CustomSocket(host:String = null, port:uint = 0) { + super(); + configureListeners(); + if (host && port) { + super.connect(host, port); + } + } + + private function configureListeners():void { + addEventListener(Event.CLOSE, closeHandler); + addEventListener(Event.CONNECT, connectHandler); + addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler); + } + + private function writeln(str:String):void { + str += "\n"; + try { + writeUTFBytes(str); + } + catch(e:IOError) { + trace(e); + } + } + + private function sendRequest():void { + trace("sendRequest"); + response = ""; + writeln("GET /"); + flush(); + } + + private function readResponse():void { + var str:String = readUTFBytes(bytesAvailable); + response += str; + } + + private function closeHandler(event:Event):void { + trace("closeHandler: " + event); + trace(response.toString()); + } + + private function connectHandler(event:Event):void { + trace("connectHandler: " + event); + sendRequest(); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function socketDataHandler(event:ProgressEvent):void { + trace("socketDataHandler: " + event); + readResponse(); + } +} +
ServerSocketDatagramSocketsecurityError + Dispatched if a call to Socket.connect() attempts to connect to a server + prohibited by the caller's security sandbox or to a port lower than 1024 and no socket policy file + exists to permit such a connection.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEventDispatched when a security error occurs. + + + Dispatched if a call to Socket.connect() attempts to connect to a server + prohibited by the caller's security sandbox or to a port lower than 1024 and no socket policy file + exists to permit such a connection. + +

Note: In an AIR application, content running in the application security sandbox is permitted to + connect to any server and port number without a socket policy file.

+ +
Socket.connect()
socketData + Dispatched when a socket has received data.flash.events.ProgressEvent.SOCKET_DATAflash.events.ProgressEvent + Dispatched when a socket has received data. + +

The data received by the socket remains in the socket until it is read. You do not have to read + all the available data during the handler for this event.

+ +

Events of type socketData do not use the ProgressEvent.bytesTotal + property.

+ +
ioError + Dispatched when an input/output error occurs that causes a send or load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input/output error occurs that causes a send or load operation to fail. + + connect + Dispatched when a network connection has been established.flash.events.Event.CONNECTflash.events.Event + Dispatched when a network connection has been established. + + close + Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event + Dispatched when the server closes the socket connection. + +

The close event is dispatched only when the server + closes the connection; it is not dispatched when you call the Socket.close() method.

+ +
Socket + Creates a new Socket object.This error occurs in SWF content + for the following reasons: + +
  • Local-with-filesystem files cannot communicate with the Internet. You can + work around this problem by reclassifying this SWF file as local-with-networking or trusted. + This limitation is not set for AIR application content in the application security sandbox.
  • You cannot specify a socket port higher than 65535.
+ +
SecurityErrorSecurityError
hostStringnullA fully qualified DNS domain name or an IP address. IPv4 addresses are specified in + dot-decimal notation, such as 192.0.2.0. In Flash Player 9.0.115.0 and AIR 1.0 and later, + you can specify IPv6 addresses using hexadecimal-colon notation, such as 2001:db8:ccc3:ffff:0:444d:555e:666f. + You can also specify null to connect to the host server + on which the SWF file resides. If the SWF file issuing this call is running in a web browser, + host must be in the domain from which the SWF file originated. + + portint0The TCP port number on the target host used to establish a connection. + In Flash Player 9.0.124.0 and later, the target host must serve a socket policy file + specifying that socket connections are permitted from the host serving the SWF file + to the specified port. In earlier versions of Flash Player, a socket policy file is required + only if you want to connect to a port number below 1024, + or if you want to connect to a host other than the one serving the SWF file. + + +
+ Creates a new Socket object. If no parameters are specified, an initially disconnected socket + is created. If parameters are specified, a connection is attempted to the specified host and port. + +

Note: It is strongly advised to use the constructor form without parameters, then + add any event listeners, then call the connect method with host + and port parameters. This sequence guarantees that all event listeners will work + properly.

+ +
connectflash.events:EventDispatched when a network connection has been established. + Dispatched when a network connection has been established.ioErrorflash.events:IOErrorEventDispatched when an input/output error + occurs that causes the connection to fail. + Dispatched when an input/output error + occurs that causes the connection to fail.securityErrorflash.events:SecurityErrorEvent + Dispatched if a call to Socket.connect() attempts + to connect either to a server that doesn't serve a socket policy file, + or to a server whose policy file doesn't grant the calling host access to the specified port. + For more information on policy files, see "Website controls (policy files)" in + the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: + Security. + + This error occurs in SWF content. + Dispatched if a call to Socket.connect() attempts + to connect either to a server that doesn't serve a socket policy file, + or to a server whose policy file doesn't grant the calling host access to the specified port.
close + Closes the socket.The socket could not be closed, or the socket was not open. + + IOErrorflash.errors:IOError + Closes the socket. You cannot read or write any data after the close() method + has been called. + +

The close event is dispatched only when the server + closes the connection; it is not dispatched when you call the close() method.

+ +

You can reuse the Socket object by calling the connect() method on it again.

+ +
connect + Connects the socket to the specified host and port.No host was specified and the connection failed. + + IOErrorflash.errors:IOErrorThis error occurs in SWF content + for the following reasons: + +
  • Local untrusted SWF files may not communicate with + the Internet. You can work around this limitation by reclassifying the + file as local-with-networking or as trusted.
  • You cannot specify a socket port higher than 65535.
  • In the HTML page that contains the SWF content, the + allowNetworking parameter of the object + and embed tags is set to "none".
+ +
SecurityErrorSecurityError
hostStringThe name or IP address of the host to connect to. If no host is specified, + the host that is contacted is the host where the calling file + resides. If you do not specify a host, use an event listener to + determine whether the connection was successful. + portintThe port number to connect to. + +
+ Connects the socket to the specified host and port. + +

If the connection fails immediately, either an event is dispatched + or an exception is thrown: an error event is dispatched if a host was + specified, and an exception is thrown if no host was specified. + Otherwise, the status of the connection is reported by an event. + If the socket is already connected, the existing connection is closed first.

+ +
connectflash.events:EventDispatched when a network connection has been + established. + Dispatched when a network connection has been + established.ioErrorflash.events:IOErrorEventDispatched if a host is specified and an + input/output error occurs that causes the connection to fail. + Dispatched if a host is specified and an + input/output error occurs that causes the connection to fail.securityErrorflash.events:SecurityErrorEventDispatched if a call to + Socket.connect() attempts to connect + either to a server that doesn't serve a socket policy file, + or to a server whose policy file doesn't grant the calling host access to the specified port. + For more information on policy files, see "Website controls (policy files)" in + the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: + Security. + + Dispatched if a call to + Socket.connect() attempts to connect + either to a server that doesn't serve a socket policy file, + or to a server whose policy file doesn't grant the calling host access to the specified port.
flush + Flushes any accumulated data in the socket's output buffer.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOError + Flushes any accumulated data in the socket's output buffer. + +

On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such + as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably + across all operating systems, it is a good practice to call the flush() method after writing each message + (or related group of data) to the socket.

+ +
readBoolean + Reads a Boolean value from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value of true if the byte read is nonzero, + otherwise false. + + Boolean + Reads a Boolean value from the socket. After reading a single byte, the + method returns true if the byte is nonzero, and + false otherwise. + + readByte + Reads a signed byte from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from -128 to 127. + + int + Reads a signed byte from the socket. + + readBytes + Reads the number of data bytes specified by the length + parameter from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is + not open. + + IOErrorflash.errors:IOErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. + offsetuint0The offset at which data reading should begin in the byte + array. + lengthuint0The number of bytes to read. The default value of 0 causes + all available data to be read. + + + Reads the number of data bytes specified by the length + parameter from the socket. The bytes are read into the specified byte + array, starting at the position indicated by offset. + + readDouble + Reads an IEEE 754 double-precision floating-point number from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorAn IEEE 754 double-precision floating-point number. + + Number + Reads an IEEE 754 double-precision floating-point number from the socket. + + readFloat + Reads an IEEE 754 single-precision floating-point number from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorAn IEEE 754 single-precision floating-point number. + Number + Reads an IEEE 754 single-precision floating-point number from the socket. + + readInt + Reads a signed 32-bit integer from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from -2147483648 to 2147483647. + + int + Reads a signed 32-bit integer from the socket. + + readMultiByte + Reads a multibyte string from the byte stream, using the specified character set.There is insufficient data available to read. + + EOFErrorflash.errors:EOFErrorA UTF-8 encoded string. + + StringlengthuintThe number of bytes from the byte stream to read. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift_jis", "CN-GB", and + "iso-8859-1". + For a complete list, see Supported Character Sets. + +

Note: If the value for the charSet parameter is not recognized + by the current system, then the application uses the system's default code page as the character set. + For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01") + that uses 01 instead of 1 might work on your development machine, but not on another machine. + On the other machine, the application will use the system's default code page.

+ +
+ Reads a multibyte string from the byte stream, using the specified character set. + +
readObject + Reads an object from the socket, encoded in AMF serialized format.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + IOErrorflash.errors:IOErrorThe deserialized object + + + Reads an object from the socket, encoded in AMF serialized format. + + ObjectEncodingflash.net.registerClassAlias()readShort + Reads a signed 16-bit integer from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from -32768 to 32767. + + int + Reads a signed 16-bit integer from the socket. + + readUTFBytes + Reads the number of UTF-8 data bytes specified by the length + parameter from the socket, and returns a string.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA UTF-8 string. + StringlengthuintThe number of bytes to read. + + + Reads the number of UTF-8 data bytes specified by the length + parameter from the socket, and returns a string. + + readUTF + Reads a UTF-8 string from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA UTF-8 string. + String + Reads a UTF-8 string from the socket. The string is assumed to be prefixed + with an unsigned short integer that indicates the length in bytes. + + readUnsignedByte + Reads an unsigned byte from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from 0 to 255. + + uint + Reads an unsigned byte from the socket. + + readUnsignedInt + Reads an unsigned 32-bit integer from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from 0 to 4294967295. + + uint + Reads an unsigned 32-bit integer from the socket. + + readUnsignedShort + Reads an unsigned 16-bit integer from the socket.There is insufficient data available to read. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorA value from 0 to 65535. + + uint + Reads an unsigned 16-bit integer from the socket. + + writeBoolean + Writes a Boolean value to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueBooleanThe value to write to the socket: 1 (true) or 0 (false). + + + Writes a Boolean value to the socket. This method writes a single byte, + with either a value of 1 (true) or 0 (false). + + flush()writeByte + Writes a byte to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. The low 8 bits of the + value are used; the high 24 bits are ignored. + + + Writes a byte to the socket. + + flush()writeBytes + Writes a sequence of bytes from the specified byte array.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorIf offset is greater than the length of the ByteArray specified in + bytes or if the amount of data specified to be written by offset plus + length exceeds the data available. + + RangeErrorRangeErrorbytesflash.utils:ByteArrayThe ByteArray object to write data from. + offsetuint0The zero-based offset into the bytes ByteArray + object at which data writing should begin. + lengthuint0The number of bytes to write. The default value of 0 causes + the entire buffer to be written, starting at the value specified by + the offset parameter. + + + Writes a sequence of bytes from the specified byte array. The write + operation starts at the position specified by offset. + +

If you omit the length parameter the default + length of 0 causes the method to write the entire buffer starting at + offset.

+ +

If you also omit the offset parameter, the entire buffer is written.

+ +
flush()
writeDouble + Writes an IEEE 754 double-precision floating-point number to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueNumberThe value to write to the socket. + + + Writes an IEEE 754 double-precision floating-point number to the socket. + + + flush()writeFloat + Writes an IEEE 754 single-precision floating-point number to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueNumberThe value to write to the socket. + + + Writes an IEEE 754 single-precision floating-point number to the socket. + + + flush()writeInt + Writes a 32-bit signed integer to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. + + + Writes a 32-bit signed integer to the socket. + + + flush()writeMultiByte + Writes a multibyte string from the byte stream, using the specified character set.valueStringThe string value to be written. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift_jis", "CN-GB", + and "iso-8859-1". For a complete list, see + Supported Character Sets. + + + Writes a multibyte string from the byte stream, using the specified character set. + + + flush()writeObject + Write an object to the socket in AMF serialized format.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorobjectThe object to be serialized. + + + Write an object to the socket in AMF serialized format. + + + flush()ObjectEncodingflash.net.registerClassAlias()writeShort + Writes a 16-bit integer to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueintThe value to write to the socket. + + + Writes a 16-bit integer to the socket. The bytes written are as follows: + +
(v >> 8) & 0xff v & 0xff
+ +

The low 16 bits of the parameter are used; the high 16 bits + are ignored.

+ +
flush()
writeUTFBytes + Writes a UTF-8 string to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueStringThe string to write to the socket. + + + Writes a UTF-8 string to the socket. + + + flush()writeUTF + Writes the following data to the socket: a 16-bit unsigned integer, which + indicates the length of the specified UTF-8 string in bytes, followed by + the string itself.The length is larger than 65535. + RangeErrorRangeErrorAn I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueStringThe string to write to the socket. + + Writes the following data to the socket: a 16-bit unsigned integer, which + indicates the length of the specified UTF-8 string in bytes, followed by + the string itself. + +

Before writing the string, the method calculates the number of bytes + that are needed to represent all characters of the string.

+ + +
flush()
writeUnsignedInt + Writes a 32-bit unsigned integer to the socket.An I/O error occurred on the socket, or the socket is not open. + + IOErrorflash.errors:IOErrorvalueuintThe value to write to the socket. + + + Writes a 32-bit unsigned integer to the socket. + + + flush()bytesAvailable + The number of bytes of data available for reading in the input buffer.uint + The number of bytes of data available for reading in the input buffer. + +

Your code must access bytesAvailable to ensure + that sufficient data is available before trying to read + it with one of the read methods.

+ +
connected + Indicates whether this Socket object is currently connected.Boolean + Indicates whether this Socket object is currently connected. + A call to this property returns a value of true if the socket + is currently connected, or false otherwise. + + endian + Indicates the byte order for the data.StringEndian.BIG_ENDIAN + + Indicates the byte order for the data. Possible values are + constants from the flash.utils.Endian class, + Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN. + flash.utils.EndianlocalAddress + The IP address this socket is bound to on the local machine.String + The IP address this socket is bound to on the local machine. + + + bind()localPort + The port this socket is bound to on the local machine.int + The port this socket is bound to on the local machine. + + bind()objectEncoding + Controls the version of AMF used when writing or reading an object.uint + Controls the version of AMF used when writing or reading an object. + + ObjectEncoding classreadObject()writeObject()remoteAddress + The IP address of the remote machine to which this socket is connected.String + The IP address of the remote machine to which this socket is connected. + +

You can use this property to determine the IP address of a client socket + dispatched in a ServerSocketConnectEvent by a ServerSocket object. Use the DNSResolver class to + convert an IP address to a domain name, if desired.

+ +
connect()ServerSocketServerSocketConnectEventDNSResolver
remotePort + The port on the remote machine to which this socket is connected.int + The port on the remote machine to which this socket is connected. + +

You can use this property to determine the port number of a client socket + dispatched in a ServerSocketConnectEvent by a ServerSocket object.

+ +
connect()ServerSocketServerSocketConnectEvent
timeout + Indicates the number of milliseconds to wait for a connection.uint + Indicates the number of milliseconds to wait for a connection. + +

If the connection doesn't succeed within the specified time, the connection fails. + The default value is 20,000 (twenty seconds).

+ +
ObjectEncoding + The ObjectEncoding class is used in defining serialization settings in classes + that serialize objects (such as FileStream, NetStream, NetConnection, SharedObject, + and ByteArray) to work with prior versions of ActionScript.Object + The ObjectEncoding class is used in defining serialization settings in classes + that serialize objects (such as FileStream, NetStream, NetConnection, SharedObject, + and ByteArray) to work with prior versions of ActionScript. + +

Object encoding controls + how objects are represented in Action Message Format (AMF). Flash Player uses + AMF to enable efficient communication between an application and a remote server. + AMF encodes remote procedure calls into a compact binary representation that can + be transferred over HTTP/HTTPS or the RTMP/RTMPS protocol used by Flash Media Server. + Objects and data values are serialized into this binary format, + which is generally more compact than other representations, such as XML.

+ +

Adobe AIR and Flash Player 9 can serialize in two different formats: AMF3 and AMF0. + AMF3, the default serialization developed for ActionScript 3.0, provides various advantages + over AMF0, which is used for ActionScript 1.0 and 2.0. AMF3 sends data over + the network more efficiently than AMF0. AMF3 supports + sending int and uint + objects as integers and supports data types that are available only in ActionScript 3.0, such as ByteArray, + XML, and IExternalizable. It is available only in ActionScript 3.0 and with servers + that use AMF3 encoding, such as Flex 2.

+ +

The ByteArray, FileStream, NetConnection, NetStream, SharedObject, + Socket, and URLStream classes contain an objectEncoding property that is assigned + a constant from the ObjectEncoding class. + The behavior of the objectEncoding property differs depending + on the object; each class's objectEncoding property + description explains the behavior more thoroughly.

+ + +
AMF0 + Specifies that objects are serialized using the Action Message Format for ActionScript 1.0 and 2.0.0uint + Specifies that objects are serialized using the Action Message Format for ActionScript 1.0 and 2.0. + AMF3 + Specifies that objects are serialized using the Action Message Format for ActionScript 3.0.3uint + Specifies that objects are serialized using the Action Message Format for ActionScript 3.0. + DEFAULT + Specifies the default (latest) format for the current runtime (either Flash + Player or AIR).3uint + Specifies the default (latest) format for the current runtime (either Flash + Player or AIR). Because object encoding control is only + available in Flash Player 9 and later and Adobe AIR, the earliest format used will be + the Action Message Format for ActionScript 3.0. + +

For example, if an object has the objectEncoding property set to + ObjectEncoding.DEFAULT, AMF3 encoding is used. + If, in the future, a later version of Flash Player or Adobe AIR introduces a new AMF version + and you republish your content, the application will use that new AMF version. + You can use this constant only if you're not concerned at all about interoperability + with previous versions.

+ +
dynamicPropertyWriter + Allows greater control over the serialization of dynamic properties of dynamic objects.flash.net:IDynamicPropertyWriter + Allows greater control over the serialization of dynamic properties of dynamic objects. + When this property is set to null, + the default value, dynamic properties are serialized using native code, which writes + all dynamic properties excluding those whose value is a function. +

This value is called only for properties of a dynamic object (objects declared + within a dynamic class) or for objects declared using the + new operator.

+ +

You can use this property to exclude properties of dynamic objects from + serialization; to write values to properties of dynamic objects; or to + create new properties for dynamic objects. To do so, set this property to an object that + implements the IDynamicPropertyWriter interface. For more information, see the + IDynamicPropertyWriter interface.

+ +
IDynamicPropertyWriter
NetStreamAppendBytesAction + +The NetStreamAppendBytesAction class is an enumeration of the constants you can pass to the NetStream.appendBytesAction() method.Object + +The NetStreamAppendBytesAction class is an enumeration of the constants you can pass to the NetStream.appendBytesAction() method. + +

Two of the constants indicate a timescale discontinuity. Every FLV tag has a timestamp indicating its position in the timescale. +Timestamps are used to synchronize video, audio, and script data playback. Timestamps for FLV tags of the same type +(video, audio, script data) must not decrease as the FLV progresses.

+ +
flash.net.NetStream.appendBytesAction()flash.net.NetStream.appendBytes()END_SEQUENCE + Indicates that the media stream data is complete.endSequenceString + Indicates that the media stream data is complete. For some codecs, such as H.264, the byte parser waits for + the buffer to fill to a certain point before beginning playback. Pass END_SEQUENCE to tell the byte parser to + begin playback immediately. + + + RESET_BEGIN + + Indicates a timescale discontinuity.resetBeginString + + Indicates a timescale discontinuity. Flushes the FIFO (composed of an incomplete FLV tag) and resets the timescale to begin at the timestamp of the next appended message. + On the next call to appendBytes(), the byte parser expects a file header and starts at the beginning of a file. + + + RESET_SEEK + Indicates a timescale discontinuity.resetSeekString + Indicates a timescale discontinuity. Flushes the FIFO (composed of an incomplete FLV tag) and resets the timescale to begin at the timestamp of the next appended message. + On the next call to appendBytes(), the byte parser expects the beginning of an FLV tag, as though you’ve just done a seek to + a location in the same FLV, on a tag boundary. + + +
NetGroupReplicationStrategy +The NetGroupReplicationStrategy class is an enumeration of constant values used in setting the replicationStrategy property +of the NetGroup class.An enumeration of constant values used in setting the replicationStrategy property of the NetGroup class. +Object +The NetGroupReplicationStrategy class is an enumeration of constant values used in setting the replicationStrategy property +of the NetGroup class. + +flash.net.NetGroup.addWantObjects()flash.net.NetGroup.replicationStrategyLOWEST_FIRST + Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the + lowest index numbers are requested first.lowestFirstString + Specifies that when fetching objects from a neighbor to satisfy a want, the objects with the + lowest index numbers are requested first. + + flash.net.NetGroup.addWantObjects()RAREST_FIRST + Specifies that when fetching objects from a neighbor to satisfy a want, the objects with + the fewest replicas among all the neighbors are requested first.rarestFirstString + Specifies that when fetching objects from a neighbor to satisfy a want, the objects with + the fewest replicas among all the neighbors are requested first. + + NetGroup.addWantObjects()URLLoader + The URLLoader class downloads data from a URL + as text, binary data, or URL-encoded variables.flash.events:EventDispatcher + The URLLoader class downloads data from a URL + as text, binary data, or URL-encoded variables. It is useful for downloading + text files, XML, or other information to be used in a + dynamic, data-driven application. + +

A URLLoader object downloads all of the data from a URL before + making it available to code in the applications. It sends out + notifications about the progress of the download, which you can monitor + through the bytesLoaded and bytesTotal properties, + as well as through dispatched events.

+ +

When loading very large video files, such as FLV's, out-of-memory errors may occur. +

+ + + +

When you use this class in Flash Player and in + AIR application content in security sandboxes other than then application security sandbox, + consider the following security model:

+ +
  • A SWF file in the local-with-filesystem sandbox may not load data from, + or provide data to, a resource that is in the network sandbox.
  • By default, the calling SWF file and the URL you load must be in exactly the same domain. + For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. + To load data from a different domain, place a URL policy file on the server hosting the data.
+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ + +
The following example loads and displays the + data found in a local text file. It also traces event handling information. + +

Note: To run this example, put a file named urlLoaderExample.txt + in the same directory as your SWF file. That file should only contain the following line of text: + answer=42&question=unknown +

+

The example code does the following:

+
  1. The constructor function creates a URLLoader instance named loader and a URLRequest + instance named request, which contains the location and name of the file to be loaded.
  2. The loader object is passed to the configureListeners() method, + which adds listeners for each of the supported URLLoader events.
  3. The request object is then passed to loader.load(), which loads the text file.
  4. When the URLLoader has finished loading the text file the Event.COMPLETE event fires, + triggering the completeHandler() method. The completeHandler() method creates a + URLVariables object from the text loaded from the file. The URLVariables object converts URL-encoded + name/value pairs into ActionScript properties to make it easier to manipulate the loaded data.
+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.*; + + public class URLLoaderExample extends Sprite { + public function URLLoaderExample() { + var loader:URLLoader = new URLLoader(); + configureListeners(loader); + + var request:URLRequest = new URLRequest("urlLoaderExample.txt"); + try { + loader.load(request); + } catch (error:Error) { + trace("Unable to load requested document."); + } + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + var loader:URLLoader = URLLoader(event.target); + trace("completeHandler: " + loader.data); + + var vars:URLVariables = new URLVariables(loader.data); + trace("The answer is " + vars.answer); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
URLRequestURLVariablesURLStreamhttpResponseStatus + Dispatched if a call to the load() method attempts to access data over HTTP, + and Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent + Dispatched if a call to the load() method attempts to access data over HTTP, + and Adobe AIR is able to detect and return the status code for the request. + + load()httpStatus + Dispatched if a call to URLLoader.load() + attempts to access data over HTTP.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent + Dispatched if a call to URLLoader.load() + attempts to access data over HTTP. For content running in + Flash Player, this event is only dispatched if the current Flash Player environment + is able to detect and return the status code for the request. (Some browser environments + may not be able to provide this information.) Note that the httpStatus event + (if any) is sent before (and in addition to) any complete + or error event. + + URLLoader.load()securityError + Dispatched if a call to URLLoader.load() + attempts to load data from a server outside the security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched if a call to URLLoader.load() + attempts to load data from a server outside the security sandbox. + Also dispatched if a call to URLLoader.load() attempts + to load a SWZ file and the certificate is invalid or the digest string + does not match the component. + URLLoader.load()ioError + Dispatched if a call to URLLoader.load() + results in a fatal error that terminates the download.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched if a call to URLLoader.load() + results in a fatal error that terminates the download. + URLLoader.load()progress + Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched when data is received as the download operation progresses. + +

Note that with a URLLoader object, it is not possible to access the data until it has + been received completely. + So, the progress event only serves as a notification of how far the download has progressed. + To access the data before it's entirely downloaded, use a URLStream object.

+
URLLoader.load()
complete + Dispatched after all the received data is decoded and + placed in the data property of the URLLoader object.flash.events.Event.COMPLETEflash.events.Event + Dispatched after all the received data is decoded and + placed in the data property of the URLLoader object. + The received data may be accessed once this event has been dispatched. + + URLLoader.load()open + Dispatched when the download operation commences following + a call to the URLLoader.load() method.flash.events.Event.OPENflash.events.EventDispatched when the download operation begins. + + Dispatched when the download operation commences following + a call to the URLLoader.load() method. + + URLLoader.load()URLLoader + Creates a URLLoader object.requestflash.net:URLRequestnullA URLRequest object specifying + the URL to download. If this parameter is omitted, + no load operation begins. If + specified, the load operation begins + immediately (see the load entry for more information). + + + Creates a URLLoader object. + + URLLoader.load()addEventListener + + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event.typeStringThe type of event. + + listenerFunctionThe listener function that processes the event. This function must accept + an Event object as its only parameter and must return nothing, as this example shows: + + + function(evt:Event):void + +

The function can have any name.

+ +
useCaptureBooleanfalse + + Determines whether the listener works in the capture phase or the + target and bubbling phases. If useCapture is set to true, + the listener processes the event only during the capture phase and not in the + target or bubbling phase. If useCapture is false, the + listener processes the event only during the target or bubbling phase. To listen for + the event in all three phases, call addEventListener twice, once with + useCapture set to true, then again with + useCapture set to false. + + priorityint0The priority level of the event listener. The priority is designated by + a signed 32-bit integer. The higher the number, the higher the priority. All listeners + with priority n are processed before listeners of priority n-1. If two + or more listeners share the same priority, they are processed in the order in which they + were added. The default priority is 0. + + useWeakReferenceBooleanfalseDetermines whether the reference to the listener is strong or + weak. A strong reference (the default) prevents your listener from being garbage-collected. + A weak reference does not.

Class-level member functions are not subject to garbage + collection, so you can set useWeakReference to true for + class-level member functions without subjecting them to garbage collection. If you set + useWeakReference to true for a listener that is a nested inner + function, the function will be garbage-collected and no longer persistent. If you create + references to the inner function (save it in another variable) then it is not + garbage-collected and stays persistent.

+ +
+ + Registers an event listener object with an EventDispatcher object so that the listener + receives notification of an event. You can register event listeners on all nodes in the + display list for a specific type of event, phase, and priority. + + + +

After you successfully register an event listener, you cannot change its priority + through additional calls to addEventListener(). To change a listener's + priority, you must first call removeListener(). Then you can register the + listener again with the new priority level.

+ +

Keep in mind that after the listener is registered, subsequent calls to + addEventListener() with a different type or + useCapture value result in the creation of a separate listener registration. + For example, if you first register a listener with useCapture set to + true, it listens only during the capture phase. If you call + addEventListener() again using the same listener object, but with + useCapture set to false, you have two separate listeners: one + that listens during the capture phase and another that listens during the target and + bubbling phases. +

+ +

You cannot register an event listener for only the target phase or the bubbling + phase. Those phases are coupled during registration because bubbling + applies only to the ancestors of the target node.

+ +

If you no longer need an event listener, remove it by calling + removeEventListener(), or memory problems could result. Event listeners are not automatically + removed from memory because the garbage + collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference + parameter is set to true).

+ +

Copying an EventDispatcher instance does not copy the event listeners attached to it. + (If your newly created node needs an event listener, you must attach the listener after + creating the node.) However, if you move an EventDispatcher instance, the event listeners + attached to it move along with it.

+ + +

If the event listener is being registered on a node while an event is being processed + on this node, the event listener is not triggered during the current phase but can be + triggered during a later phase in the event flow, such as the bubbling phase.

+ +

If an event listener is removed from a node while an event is being processed on the node, + it is still triggered by the current actions. After it is removed, the event listener is + never invoked again (unless registered again for future processing).

+ +
close + Closes the load operation in progress. + Closes the load operation in progress. Any load + operation in progress is immediately terminated. + If no URL is currently being streamed, an invalid stream error is thrown. + + load + Sends and loads data from the specified URL.URLRequest.requestHeader objects may not + contain certain prohibited HTTP request headers. For more information, + see the URLRequestHeader class description. + + ArgumentErrorArgumentErrorThis error can occur for the following reasons: + 1) Flash Player or AIR cannot + convert the URLRequest.data + parameter from UTF8 to MBCS. This error is applicable if the URLRequest object + passed to load() is set to perform a GET operation and + if System.useCodePage is set to true. + 2) Flash Player or AIR cannot + allocate memory for the POST data. This error is + + applicable if the URLRequest object passed to load is set + to perform a POST operation. + + MemoryErrorflash.errors:MemoryErrorLocal untrusted files may not communicate with + the Internet. This may be worked around by reclassifying this file + as local-with-networking or trusted. + + SecurityErrorSecurityErrorYou are trying to connect to a commonly reserved port. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThe value of the request parameter + or the URLRequest.url property of the URLRequest object passed are + null. + + TypeErrorTypeErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to download. + + + Sends and loads data from the specified URL. The data can be received as + text, raw binary data, or URL-encoded variables, depending on the + value you set for the dataFormat property. Note that + the default value of the dataFormat property is text. + If you want to send data to the specified URL, you can set the data + property in the URLRequest object. + +

Note: If a file being loaded contains non-ASCII characters (as found + in many non-English languages), it is recommended that you save the + file with UTF-8 or UTF-16 encoding as opposed to a non-Unicode format + like ASCII.

+ +

A SWF file in the local-with-filesystem sandbox may not load data from, + or provide data to, a resource that is in the network sandbox.

+ +

By default, the calling SWF file and the URL you load must be in exactly the same domain. + For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. + To load data from a different domain, place a URL policy file on the server hosting the data.

+ +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ + +
In the following example, an XML files is loaded and the content + of its elements' first arguments are displayed in a text field. + +

A URLRequest object is created to identify the location of the + XML file, which for this example is in the same directory as the SWF file. + The file is loaded in a try...catch block in order to catch any + error that may occur. (Here we catch the SecurityError errors.) + If an IO_ERROR event occurs, the errorHandler() method + is invoked, which writes an error message in the xmlTextField text field. + Once the XML file data is received and place in the data property of the loader + URLLoader object, the Event.COMPLETE event is dispatched and the + loaderCompleteHandler() method is invoked.

+ +

In the loaderCompleteHandler() method, a try...catch + block is used to catch any parsing error that may occur while converting the loaded + data from the file into an XML object. The readNodes() method then + recursively goes through all the elements in the nodes of the XML document and + appends the xmlTextField text field with a list of the first attributes + of all the elements.

+ +package { + import flash.display.Sprite; + import flash.events.Event; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.xml.*; + import flash.events.IOErrorEvent; + + public class URLLoader_loadExample extends Sprite { + private var xmlTextField:TextField = new TextField(); + private var externalXML:XML; + private var loader:URLLoader; + + public function URLLoader_loadExample() { + var request:URLRequest = new URLRequest("xmlFile.xml"); + + loader = new URLLoader(); + + try { + loader.load(request); + } + catch (error:SecurityError) + { + trace("A SecurityError has occurred."); + } + + loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + loader.addEventListener(Event.COMPLETE, loaderCompleteHandler); + + xmlTextField.x = 10; + xmlTextField.y = 10; + xmlTextField.background = true; + xmlTextField.autoSize = TextFieldAutoSize.LEFT; + + addChild(xmlTextField); + } + + private function loaderCompleteHandler(event:Event):void { + + try { + externalXML = new XML(loader.data); + readNodes(externalXML); + } catch (e:TypeError) { + trace("Could not parse the XML file."); + } + } + + private function readNodes(node:XML):void { + + for each (var element:XML in node.elements()) { + xmlTextField.appendText(element.attributes()[0] + "\n"); + + readNodes(element); + } + } + + private function errorHandler(e:IOErrorEvent):void { + xmlTextField.text = "Had problem loading the XML File."; + } + } +} +
URLRequestHeaderURLRequest.requestHeadersURLRequest.dataURLRequest.digestcompleteflash.events:EventDispatched after data has loaded successfully. + + Dispatched after data has loaded successfully.httpStatusflash.events:HTTPStatusEventIf access is over HTTP, and the current + Flash Player environment supports obtaining status codes, you may + receive these events in addition to any complete + or error event. + + If access is over HTTP, and the current + Flash Player environment supports obtaining status codes, you may + receive these events in addition to any complete + or error event.ioErrorflash.events:IOErrorEventThe load operation could not be + completed. + + The load operation could not be + completed.progressflash.events:ProgressEventDispatched when data is received as the download + operation progresses. + + Dispatched when data is received as the download + operation progresses.securityErrorflash.events:SecurityErrorEventA load operation attempted + to retrieve data from a server outside the caller's security sandbox. + This may be worked around using a policy file on the server. + A load operation attempted + to retrieve data from a server outside the caller's security sandbox.securityErrorflash.events:SecurityErrorEventA load operation attempted + to load a SWZ file (a Adobe platform component), but the certificate is invalid + or the digest does not match the component. + A load operation attempted + to load a SWZ file (a Adobe platform component), but the certificate is invalid + or the digest does not match the component.openflash.events:EventDispatched when a load operation commences. + + Dispatched when a load operation commences.httpResponseStatusflash.events:HTTPStatusEventDispatched if a call to the load() + method attempts to access data over HTTP and Adobe AIR is able to detect and return the + status code for the request. + + Dispatched if a call to the load() + method attempts to access data over HTTP and Adobe AIR is able to detect and return the + status code for the request.
bytesLoaded + Indicates the number of bytes that have been loaded thus far + during the load operation.0uint + Indicates the number of bytes that have been loaded thus far + during the load operation. + + bytesTotal + Indicates the total number of bytes in the downloaded data.0uint + Indicates the total number of bytes in the downloaded data. + This property contains 0 while the load operation is in progress + and is populated when the operation is complete. + Also, a missing Content-Length header will result in bytesTotal being indeterminate. + + dataFormat + Controls whether the downloaded data is received as + text (URLLoaderDataFormat.TEXT), raw binary data + (URLLoaderDataFormat.BINARY), or URL-encoded variables + (URLLoaderDataFormat.VARIABLES).textStringURLLoaderDataFormat.TEXT + Controls how the downloaded data is received. + + + Controls whether the downloaded data is received as + text (URLLoaderDataFormat.TEXT), raw binary data + (URLLoaderDataFormat.BINARY), or URL-encoded variables + (URLLoaderDataFormat.VARIABLES). + +

If the value of the dataFormat property is URLLoaderDataFormat.TEXT, + the received data is a string containing the text of the loaded file.

+ +

If the value of the dataFormat property is URLLoaderDataFormat.BINARY, + the received data is a ByteArray object containing the raw binary data.

+ +

If the value of the dataFormat property is URLLoaderDataFormat.VARIABLES, + the received data is a URLVariables object containing the URL-encoded variables.

+ +
The following example shows how you can load external text files. Use the URLRequest and URLLoader classes, and then listen for the complete event. + Example provided by + ActionScriptExamples.com. + +var PATH:String = "lorem.txt"; +var urlRequest:URLRequest = new URLRequest(PATH); +var urlLoader:URLLoader = new URLLoader(); +urlLoader.dataFormat = URLLoaderDataFormat.TEXT; // default +urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); +urlLoader.load(urlRequest); + +function urlLoader_complete(evt:Event):void { + textArea.text = urlLoader.data; +} +
URLLoaderDataFormat
data + The data received from the load operation. + The data received from the load operation. This property + is populated only when the load operation is complete. + The format of the data depends on the setting of the + dataFormat property: + +

If the dataFormat property is URLLoaderDataFormat.TEXT, + the received data is a string containing the text of the loaded file.

+ +

If the dataFormat property is URLLoaderDataFormat.BINARY, + the received data is a ByteArray object containing the raw binary data.

+ +

If the dataFormat property is URLLoaderDataFormat.VARIABLES, + the received data is a URLVariables object containing the URL-encoded variables.

+ +
The following example shows how you can load an external text file with URL encoded variables into an ActionScript 3.0 document using the URLLoader class and setting the dataFormat property to the URLLoaderDataFormat.VARIABLES constant ("variables"). + Example provided by + ActionScriptExamples.com. + +//params.txt is a local file that includes: firstName=Tom&lastName=Jones +var lbl:TextField = new TextField(); +var urlRequest:URLRequest = new URLRequest("params.txt"); +var urlLoader:URLLoader = new URLLoader(); +urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES; +urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); +urlLoader.load(urlRequest); + +function urlLoader_complete(evt:Event):void { + lbl.text = urlLoader.data.lastName + "," + urlLoader.data.firstName; + addChild(lbl); +} +
URLLoaderDataFormatURLLoader.dataFormat
IDynamicPropertyOutput + This interface controls the serialization of dynamic properties of dynamic objects. + This interface controls the serialization of dynamic properties of dynamic objects. + You use this interface with the IDynamicPropertyWriter interface + and the ObjectEncoding.dynamicPropertyWriter property. + + IDynamicPropertyWriterObjectEncoding.dynamicPropertyWriterwriteDynamicProperty + Adds a dynamic property to the binary output of a serialized object.nameStringThe name of the property. You can use this parameter either to specify + the name of an existing property of the dynamic object or to create a + new property. + + valueThe value to write to the specified property. + + + Adds a dynamic property to the binary output of a serialized object. + When the object is subsequently read (using a method such as + readObject), it contains the new property. + You can use this method + to exclude properties of dynamic objects from serialization; to write values + to properties of dynamic objects; or to create new properties + for dynamic objects. + + IDynamicPropertyWriterObjectEncoding.dynamicPropertyWriterNetStreamPlayOptions + + The NetStreamPlayOptions class specifies the various options that can be passed + to the NetStream.play2() method.The NetStreamPlayOptions class specifies the various options that can be passed + to the NetStream.play2() method. + + flash.events:EventDispatcher + + The NetStreamPlayOptions class specifies the various options that can be passed + to the NetStream.play2() method. You pass a NetStreamPlayOptions object + to play2(), and the properties of the class specify the various options. + The primary use case for this class is to implement transitions between streams dynamically, + either to switch to streams of different bit rates and sizes or to swap to different content + in a playlist. + + NetStreamPlayOptions + + Creates a NetStreamPlayOptions object to specify the options that are passed to the NetStream.play2() method. + + Creates a NetStreamPlayOptions object to specify the options that are passed to the NetStream.play2() method. + + NetStream.play2()len + The duration of playback, in seconds, for the stream specified in streamName.NumberThe duration of playback, in seconds, for the stream specified in streamName. + + The duration of playback, in seconds, for the stream specified in streamName. + The default value is -1, which means that Flash Player plays a live stream until it is no longer available or plays a recorded stream until it ends. + If you pass 0 for len, Flash Player plays the single frame that is start seconds from the beginning of a recorded stream + (assuming that start is equal to or greater than 0). +

If you pass a positive number for len, Flash Player plays a live stream for len seconds after it becomes available, + or plays a recorded stream for len seconds. (If a stream ends before len seconds, playback ends when the stream ends.)

+

If you pass a negative number other than -1 for len, Flash Player interprets the value as if it were -1.

+ +
NetStream.play()NetStream.play2()start
offset + The time in seconds in the stream playback at which the switch to a new stream should be made.Number + The time in seconds in the stream playback at which the switch to a new stream should be made. + The offset parameter is used when a NetStream.play2() call is made with the + NetStreamPlayTransitions.SWITCH transition mode. Flash Media Server looks for the nearest switch point + after the specified offset time and starts streaming the new stream from that point onwards. + +

Fast switch

+ +

When this property is specified, Flash Media Server pre-empts the current stream and starts streaming the new stream + from the specified index position immediately, without waiting to + find a keyframe. Any data after the offset already buffered from a previous stream is flushed. + This technique can switch to a new stream more quickly than standard switching, because the buffered data from an older stream + doesn't have to play out.

+ +

The default value of offset is -1, which is fast switch mode. In this mode, switching occurs at the first available keyframe after netstream.time + 3, + which is about 3 seconds later than the playback point.

+ +

The offset value must be higher than the current playback time (Netstream.time) + If the value is less, a NetStream.Play.Failed status event is sent.

+ +

For more information, see "Fast switching between streams" + in the Adobe Flash Media Server Developer's Guide.

+ +
startNetStream.play()NetStream.play2()NetStream.timeNetStreamPlayTransitions.SWITCH
oldStreamName + The name of the old stream or the stream to transition from.String + The name of the old stream or the stream to transition from. + When NetStream.play2() is used to simply play a stream (not perform a transition), the value of this property + should be either null or undefined. Otherwise, specify the stream to transition from. + + streamNameNetStream.play()NetStream.play2()start + The start time, in seconds, for streamName.NumberThe start time, in seconds, for streamName. + + The start time, in seconds, for streamName. Valid values are -2, -1, and 0. + +

The default value for start is -2, which means that Flash Player first tries to play the live stream specified in streamName. + If a live stream of that name is not found, Flash Player plays the recorded stream specified in streamName. + If neither a live nor a recorded stream is found, Flash Player opens a live stream named streamName, even though no one is + publishing on it. When someone does begin publishing on that stream, Flash Player begins playing it.

+ +

If you pass -1 for start, Flash Player plays only the live stream specified in streamName. If no live stream is found, + Flash Player waits for it indefinitely if len is set to -1; if len is set to a different value, + Flash Player waits for len seconds before it begins playing the next item in the playlist.

+ +

If you pass 0 or a positive number for start, Flash Player plays only a recorded stream named streamName, + beginning start seconds from the beginning of the stream. If no recorded stream is found, Flash Player begins playing the next item + in the playlist immediately.

+ +

If you pass a negative number other than -1 or -2 for start, Flash Player interprets the value as if it were -2.

+ +
NetStream.play()NetStream.play2()len
streamName + The name of the new stream to transition to or to play.String + The name of the new stream to transition to or to play. When oldStreamName is null or undefined, calling + NetStream.play2() simply starts playback of streamName. If oldStreamName is specified, calling NetStream.play2() + transitions oldStreamName to streamName using the transition mode specified in the transition property. + + oldStreamNameNetStream.play()NetStream.play2()transition + The mode in which streamName is played or transitioned to.StringThe mode in which streamName is played or transitioned to. + + The mode in which streamName is played or transitioned to. Possible values are constants from the NetStreamPlayTransitions class. + Depending on whether Netstream.play2() is called to play or transition a stream, the transition mode results in different behaviors. + For more information on the transition modes, see the NetStreamPlayTransitions class. + + NetStreamPlayTransitionsNetStream.play2()
NetStreamMulticastInfo +The NetStreamMulticastInfo class specifies various Quality of Service (QoS) statistics +related to a NetStream object's underlying RTMFP Peer-to-Peer and IP Multicast stream transport.Object +The NetStreamMulticastInfo class specifies various Quality of Service (QoS) statistics +related to a NetStream object's underlying RTMFP Peer-to-Peer and IP Multicast stream transport. +A NetStreamMulticastInfo object is returned by the NetStream.multicastInfo property. + +

Properties that return numbers represent totals computed from the beginning of the multicast stream. +These types of properties include the number of media bytes sent or the number of media fragment messages received. +Properties that are rates represent a snapshot of the current rate averaged over a few seconds. +These types of properties include the rate at which a local node is receiving data.

+ +

To see a list of values contained in the NetStreamMulticastInfo object, use the +NetStreamMulticastInfo.toString() method.

+ +
toString()flash.net.NetStream.multicastInfotoString + Returns a string listing the properties of the NetStreamMulticastInfo object.A string containing the values of the properties of the NetStreamMulticastInfo object + + String + Returns a string listing the properties of the NetStreamMulticastInfo object. + + bytesPushedFromPeers + Specifies the number of media bytes that were proactively pushed from peers and received by the local node.Number + Specifies the number of media bytes that were proactively pushed from peers and received by the local node. + + bytesRequestedFromPeersfragmentsPushedFromPeersfragmentsRequestedFromPeersbytesPushedToPeers + Specifies the number of media bytes that the local node has proactively pushed to peers.Number + Specifies the number of media bytes that the local node has proactively pushed to peers. + + bytesRequestedByPeersfragmentsPushedToPeersfragmentsRequestedByPeersbytesReceivedFromIPMulticast + Specifies the number of media bytes that the local node has received from IP Multicast.Number + Specifies the number of media bytes that the local node has received from IP Multicast. + + bytesReceivedFromServerfragmentsReceivedFromIPMulticastfragmentsReceivedFromServerreceiveDataBytesPerSecondFromIPMulticastbytesReceivedFromServer + Specifies the number of media bytes that the local node has received from the server.Number + Specifies the number of media bytes that the local node has received from the server. + + bytesReceivedFromIPMulticastfragmentsReceivedFromIPMulticastfragmentsReceivedFromServerreceiveDataBytesPerSecondFromServerbytesRequestedByPeers + Specifies the number of media bytes that the local node has sent to peers in response to requests from those peers for specific fragments.Number + Specifies the number of media bytes that the local node has sent to peers in response to requests from those peers for specific fragments. + + bytesPushedToPeersfragmentsPushedToPeersfragmentsRequestedByPeersbytesRequestedFromPeers + Specifies the number of media bytes that the local node requested and received from peers.Number + Specifies the number of media bytes that the local node requested and received from peers. + + bytesPushedFromPeersfragmentsPushedFromPeersfragmentsRequestedFromPeersfragmentsPushedFromPeers + Specifies the number of media fragment messages that were proactively pushed from peers and received by the local node.Number + Specifies the number of media fragment messages that were proactively pushed from peers and received by the local node. + + bytesPushedFromPeersbytesRequestedFromPeersfragmentsRequestedFromPeersfragmentsPushedToPeers + Specifies the number of media fragment messages that the local node has proactively pushed to peers.Number + Specifies the number of media fragment messages that the local node has proactively pushed to peers. + + bytesPushedToPeersbytesRequestedByPeersfragmentsRequestedByPeersfragmentsReceivedFromIPMulticast + Specifies the number of media fragment messages that the local node has received from IP Multicast.Number + Specifies the number of media fragment messages that the local node has received from IP Multicast. + + bytesReceivedFromIPMulticastbytesReceivedFromServerfragmentsReceivedFromServerreceiveDataBytesPerSecondFromIPMulticastfragmentsReceivedFromServer + Specifies the number of media fragment messages that the local node has received from the server.Number + Specifies the number of media fragment messages that the local node has received from the server. + + bytesReceivedFromIPMulticastbytesReceivedFromServerfragmentsReceivedFromIPMulticastreceiveDataBytesPerSecondFromServerfragmentsRequestedByPeers + Specifies the number of media fragment messages that the local node has sent to peers in response to requests from those peers for specific fragments.Number + Specifies the number of media fragment messages that the local node has sent to peers in response to requests from those peers for specific fragments. + + bytesPushedToPeersbytesRequestedByPeersfragmentsPushedToPeersfragmentsRequestedFromPeers + Specifies the number of media fragment messages that the local node requested and received from peers.Number + Specifies the number of media fragment messages that the local node requested and received from peers. + + bytesPushedFromPeersbytesRequestedFromPeersfragmentsPushedFromPeersreceiveControlBytesPerSecond + Specifies the rate at which the local node is receiving control overhead messages from peers, in bytes per second.Number + Specifies the rate at which the local node is receiving control overhead messages from peers, in bytes per second. + + receiveDataBytesPerSecondreceiveDataBytesPerSecondFromServerreceiveDataBytesPerSecondFromIPMulticastsendControlBytesPerSecondreceiveDataBytesPerSecondFromIPMulticast + Specifies the rate at which the local node is receiving data from IP Multicast, in bytes per second.Number + Specifies the rate at which the local node is receiving data from IP Multicast, in bytes per second. + + receiveControlBytesPerSecondreceiveDataBytesPerSecondreceiveDataBytesPerSecondFromServersendDataBytesPerSecondreceiveDataBytesPerSecondFromServer + Specifies the rate at which the local node is receiving media data from the server, in bytes per second.Number + Specifies the rate at which the local node is receiving media data from the server, in bytes per second. + + receiveControlBytesPerSecondreceiveDataBytesPerSecondreceiveDataBytesPerSecondFromIPMulticastsendDataBytesPerSecondreceiveDataBytesPerSecond + Specifies the rate at which the local node is receiving media data from peers, from the server, and over IP multicast, in bytes per second.Number + Specifies the rate at which the local node is receiving media data from peers, from the server, and over IP multicast, in bytes per second. + + receiveControlBytesPerSecondreceiveDataBytesPerSecondFromIPMulticastreceiveDataBytesPerSecondFromServersendDataBytesPerSecondsendControlBytesPerSecondToServer + Specifies the rate at which the local node is sending control overhead messages to the server, in bytes per second.Number + Specifies the rate at which the local node is sending control overhead messages to the server, in bytes per second. + + receiveDataBytesPerSecondFromServersendControlBytesPerSecondsendDataBytesPerSecondsendControlBytesPerSecond + Specifies the rate at which the local node is sending control overhead messages to peers and the server, in bytes per second.Number + Specifies the rate at which the local node is sending control overhead messages to peers and the server, in bytes per second. + + receiveControlBytesPerSecondsendControlBytesPerSecondToServersendDataBytesPerSecondsendDataBytesPerSecond + Specifies the rate at which media data is being sent by the local node to peers, in bytes per second.Number + Specifies the rate at which media data is being sent by the local node to peers, in bytes per second. + + receiveDataBytesPerSecondsendControlBytesPerSecondsendControlBytesPerSecondToServer
NetworkInfo + The NetworkInfo class provides information about the network + interfaces on a computer.flash.events:EventDispatcher + The NetworkInfo class provides information about the network + interfaces on a computer. + +

AIR profile support: This feature is supported + on all desktop operating systems and AIR for TV devices, but is not supported on all mobile devices. + You can test for support at run time using the NetworkInfo.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

The NetworkInfo object is a singleton. To get the single NetworkInfo object, + use the static NetworkInfo.networkInfo property. Do not call the class + constructor, new NetworkInfo().

+ +

Most computers have one or more interfaces, such as + a wired and a wireless network interface. Additional interfaces such as + VPN, loopback, or virtual interfaces can also be present.

+ +

A NetworkInfo object dispatches a change event when the available + interfaces change. Call the findInterfaces() + method to determine the most current network information.

+ +

Note: The NativeApplication object also dispatches network change events.

+ +
NetworkInterface classInterfaceAddress classnetworkChange + Dispatched when the network interfaces have changed.flash.events.Event.NETWORK_CHANGEflash.events.Event + Dispatched when the network interfaces have changed. + + findInterfaces + Returns the list of network interfaces associated with this + machine.An array of NetworkInterface objects + + + Returns the list of network interfaces associated with this + machine. + + isSupported + Indicates whether access to network interface information is supported on the client system.Boolean + Indicates whether access to network interface information is supported on the client system. + + networkInfo + The singleton instance of the NetworkInfo object.flash.net:NetworkInfoIf content running outside the AIR application security + sandbox accesses this property. + + SecurityErrorSecurityError + The singleton instance of the NetworkInfo object. + +
URLVariables + + The URLVariables class allows you to transfer + variables between an application and a + server.Object + + The URLVariables class allows you to transfer + variables between an application and a + server. + Use URLVariables objects with methods of the URLLoader + class, with the data property + of the URLRequest class, and with flash.net package + functions. + + The following example opens the remote application hosted at + http://www.[yourDomain].com/application.jsp in a new browser window and passes + data about a user session, captured in a URLVariables object, to the application. + +

Highlights of the example follow:

+
  1. The constructor function creates a URLRequest + instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The example calls navigateToURL, which opens a new browser window + to the remote application's URL.
+

Note: To run the example, the remote application URL in the example must be replaced + with a working URL. Additionally, you would need server code + to process the information captured by Flash Player in the URLVariables object.

+ +package { + import flash.display.Sprite; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.net.URLVariables; + + public class URLVariablesExample extends Sprite { + + public function URLVariablesExample() { + var url:String = "http://www.[yourDomain].com/application.jsp"; + var request:URLRequest = new URLRequest(url); + var variables:URLVariables = new URLVariables(); + variables.exampleSessionId = new Date().getTime(); + variables.exampleUserLabel = "guest"; + request.data = variables; + navigateToURL(request); + } + } +} +
URLLoaderURLVariables + Creates a new URLVariables object.sourceStringnullA URL-encoded string containing name/value pairs. + + Creates a new URLVariables object. You pass URLVariables + objects to the data property of URLRequest objects. + +

If you call the URLVariables constructor with a string, + the decode() method is automatically called + to convert the string to properties of the URLVariables object.

+ +
decode + Converts the variable string to properties of the specified URLVariables object.The source parameter must be a URL-encoded query + string containing name/value pairs. + + ErrorErrorsourceStringA URL-encoded query string containing name/value pairs. + + + + Converts the variable string to properties of the specified URLVariables object. +

This method is used internally by the URLVariables events. + Most users do not need to call this method directly.

+ +
The following examples show how you can parse URL encoded strings. + Example provided by + ActionScriptExamples.com. + +// The first method passes the string to be decoded to the URLVariables class constructor: +var urlVariables:URLVariables = new URLVariables("firstName=Tom&lastName=Jones"); +lbl.text = urlVariables.lastName + "," + urlVariables.firstName; + +// The second method uses the decode() method to parse the URL encoded string: +var urlVariables:URLVariables = new URLVariables(); +urlVariables.decode("firstName=Tom&lastName=Jones"); +lbl.text = urlVariables.lastName + "," + urlVariables.firstName; +
toString + Returns a string containing all enumerable variables, + in the MIME content encoding application/x-www-form-urlencoded.A URL-encoded string containing name/value pairs. + + String + Returns a string containing all enumerable variables, + in the MIME content encoding application/x-www-form-urlencoded. + +
IDynamicPropertyWriter + This interface is used with the IDynamicPropertyOutput interface to control + the serialization of dynamic properties of dynamic objects. + This interface is used with the IDynamicPropertyOutput interface to control + the serialization of dynamic properties of dynamic objects. To use this interface, + assign an object that implements the IDynamicPropertyWriter interface to + the ObjectEncoding.dynamicPropertyWriter property. + + IDynamicPropertyOutputObjectEncoding.dynamicPropertyWriterwriteDynamicProperties + Writes the name and value of an IDynamicPropertyOutput object to an object with + dynamic properties.objObjectThe object to write to. + outputflash.net:IDynamicPropertyOutputThe IDynamicPropertyOutput object that contains the name and value + to dynamically write to the object. + + + Writes the name and value of an IDynamicPropertyOutput object to an object with + dynamic properties. If ObjectEncoding.dynamicPropertyWriter is set, + this method is invoked for each object with dynamic properties. + + IDynamicPropertyOutputObjectEncoding.dynamicPropertyWriterDatagramSocket + The DatagramSocket class enables code to send and receive + Universal Datagram Protocol (UDP) packets.flash.events:EventDispatcher + The DatagramSocket class enables code to send and receive + Universal Datagram Protocol (UDP) packets. + +

AIR profile support: This feature is supported on + all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test for + support at run time using the DatagramSocket.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

Datagram packets are individually transmitted between the source and destination. + Packets can arrive in a different order than they were sent. Packets lost in transmission are not retransmitted, or + even detected.

+ +

Data sent using a datagram socket is not automatically broken + up into packets of transmittable size. If you send a UDP packet that exceeds the maximum + transmission unit (MTU) size, network discards the packet (without warning). The limiting MTU is the + smallest MTU of any interface, switch, or router in the transmission path. + You can use the NetworkInterface class to determine the MTU of the local interface, but + other nodes in the network can have different MTU values.

+ +

The Socket class uses TCP which provides guaranteed packet delivery and automatically + divides and reassembles large packets. TCP also provides better network bandwidth + management. These features mean that data sent using a TCP socket incurs higher + latency, but for most uses, the benefits of TCP far outweigh the costs. Most network + communication should use the Socket class rather than the DatagramSocket class.

+ +

The DatagramSocket class is useful for working with + applications where a small transmission latency is important + and packet loss is tolerable. For example, network operations in voice-over-IP (VoIP) applications and + real-time, multiplayer games can often benefit from UDP. The + DatagramSocket class is also useful for some server-side + applications. Since UDP is a stateless protocol, a + server can handle more requests from more clients than it can with + TCP.

+ +

The DatagramSocket class can only be used in Adobe AIR + applications and only in the application security sandbox.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
+package +{ + import flash.display.Sprite; + import flash.events.DatagramSocketDataEvent; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.events.TimerEvent; + import flash.net.DatagramSocket; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFieldType; + import flash.utils.ByteArray; + import flash.utils.Timer; + + public class DatagramSocketExample extends Sprite + { + private var datagramSocket:DatagramSocket = new DatagramSocket();; + + private var localIP:TextField; + private var localPort:TextField; + private var logField:TextField; + private var targetIP:TextField; + private var targetPort:TextField; + private var message:TextField; + + public function DatagramSocketExample() + { + setupUI(); + } + + private function bind( event:Event ):void + { + if( datagramSocket.bound ) + { + datagramSocket.close(); + datagramSocket = new DatagramSocket(); + + } + datagramSocket.bind( parseInt( localPort.text ), localIP.text ); + datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived ); + datagramSocket.receive(); + log( "Bound to: " + datagramSocket.localAddress + ":" + datagramSocket.localPort ); + } + + private function dataReceived( event:DatagramSocketDataEvent ):void + { + //Read the data from the datagram + log("Received from " + event.srcAddress + ":" + event.srcPort + "> " + + event.data.readUTFBytes( event.data.bytesAvailable ) ); + } + + private function send( event:Event ):void + { + //Create a message in a ByteArray + var data:ByteArray = new ByteArray(); + data.writeUTFBytes( message.text ); + + //Send a datagram to the target + try + { + datagramSocket.send( data, 0, 0, targetIP.text, parseInt( targetPort.text )); + log( "Sent message to " + targetIP.text + ":" + targetPort.text ); + } + catch ( error:Error ) + { + log( error.message ); + } + } + + private function log( text:String ):void + { + logField.appendText( text + "\n" ); + logField.scrollV = logField.maxScrollV; + trace( text ); + } + private function setupUI():void + { + targetIP = createTextField( 10, 10, "Target IP:", "192.168.0.1" ); + targetPort = createTextField( 10, 35, "Target port:", "8989" ); + message = createTextField( 10, 60, "Message:", "Lucy can't drink milk." ); + localIP = createTextField( 10, 85, "Local IP", "0.0.0.0"); + localPort = createTextField( 10, 110, "Local port:", "0" ); + createTextButton( 250, 135, "Bind", bind ); + createTextButton( 300, 135, "Send", send ); + logField = createTextField( 10, 160, "Log:", "", false, 200 ) + + this.stage.nativeWindow.activate(); + } + + private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField + { + var labelField:TextField = new TextField(); + labelField.text = label; + labelField.type = TextFieldType.DYNAMIC; + labelField.width = 180; + labelField.x = x; + labelField.y = y; + + var input:TextField = new TextField(); + input.text = defaultValue; + input.type = TextFieldType.INPUT; + input.border = editable; + input.selectable = editable; + input.width = 280; + input.height = height; + input.x = x + labelField.width; + input.y = y; + + this.addChild( labelField ); + this.addChild( input ); + + return input; + } + + private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField + { + var button:TextField = new TextField(); + button.htmlText = "<u><b>" + label + "</b></u>"; + button.type = TextFieldType.DYNAMIC; + button.selectable = false; + button.width = 180; + button.x = x; + button.y = y; + button.addEventListener( MouseEvent.CLICK, clickHandler ); + + this.addChild( button ); + return button; + + } + } +} +
RFC 768Socket classXMLSocket classServerSocket classioError + Dispatched when this socket receives an I/O error.flash.events.IOErrorEvent.IOERRORflash.events.IOErrorEventDispatched when this socket receives an I/O error. + + Dispatched when this socket receives an I/O error. + + data + Dispatched when this socket receives a packet of data.flash.events.DatagramSocketDataEvent.DATAflash.events.DatagramSocketDataEvent + Dispatched when this socket receives a packet of data. + + close + Dispatched when the operating system closes this socket.flash.events.Event.CLOSEflash.events.Event + Dispatched when the operating system closes this socket. + +

The close event is not dispatched when the DatagramSocket close() + method is called.

+ +
DatagramSocket + Creates a DatagramSocket object.if content outside the AIR application security + sandbox attempts to create a DatagramSocket object. + + SecurityErrorSecurityError + Creates a DatagramSocket object. + + bind + Binds this socket to the specified local address and port.This error occurs when localPort is less than 0 or greater than 65535. + + RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically well-formed IP address. + + ArgumentErrorArgumentErrorThis error occurs if the socket cannot be bound, such as when: +
  1. localPort is already in use by another socket.
  2. the user account under which the application is running doesn't have sufficient + system privileges to bind to the specified port. (Privilege issues typically occur when localPort < 1024.)
  3. This DatagramSocket object is already bound.
  4. This DatagramSocket object has been closed.
+ +
IOErrorflash.errors:IOError
This error occurs when localAddress is not a valid local address. + + ErrorErrorlocalPortint0The number of the port to bind to on the local computer. If localPort, + is set to 0 (the default), the next available system port is bound. Permission to connect to a port + number below 1024 is subject to the system security policy. On Mac and Linux systems, for example, + the application must be running with root privileges to connect to ports below 1024. + localAddressString0.0.0.0The IP address on the local machine to bind to. This address can be an + IPv4 or IPv6 address. If localAddress is set to 0.0.0.0 (the default), + the socket listens on all available IPv4 addresses. + To listen on all available IPv6 addresses, you must specify "::" as the localAddress + argument. To use an IPv6 address, the computer and network must both be + configured to support IPv6. Furthermore, a socket bound to an IPv4 address + cannot connect to a socket with an IPv6 address. Likewise, a socket bound to an IPv6 + address cannot connect to a socket with an IPv4 address. The type of address must match. + +
+ Binds this socket to the specified local address and port. + +

The bind() method executes synchronously. The bind operation completes + before the next line of code is executed.

+ +
The following example illustrates various ways to bind a DatagramSocket object: + + +udpSocket.bind(); //bind to any available port, listen on all IPv4 addresses +udpSocket.bind( 0, "0.0.0.0" ); //same as above +udpSocket.bind( 0, "127.0.0.1" ); //any available port on the localhost address +udpSocket.bind( 8989, "192.168.0.1" ); //port 8989 on a particular IPv4 address +udpSocket.bind( 0, "::" ); //any available port on all IPv6 address +udpSocket.bind( 8989, "::1" ); //port 8989 on the IPv6 localhost address +udpSocket.bind( 8989, "2001:1890:110b:1e19:f06b:72db:7026:3d7a" ); //port 8989 on a particular IPv6 address +
close + Closes the socket.If the socket cannot be closed (because of an internal, networking, + or operating system error), or if the socket is not open. + + IOErrorflash.errors:IOError + Closes the socket. + +

The socket is disconnected from the remote machine + and unbound from the local machine. A closed socket cannot be reused.

+ +
connect + Connects the socket to a specified remote address and port.This error occurs when localPort is less than 1 or greater than 65535. + + RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically valid address. + Or when a default route address ('0.0.0.0' or '::') is used. + + ArgumentErrorArgumentErrorThis error occurs if the socket cannot be connected, such as when bind() has not + been called before the call to connect() and default binding to the remote address family is not possible. + + IOErrorflash.errors:IOErrorremoteAddressStringThe IP address of the remote machine with which to establish + a connection. This address can be an IPv4 or IPv6 address. If bind() has not + been called, the address family of the remoteAddress, IPv4 or IPv6, is used when calling the + default bind(). + + remotePortintThe port number on the remote machine used to establish a connection. + + + Connects the socket to a specified remote address and port. + +

When a datagram socket is "connected," datagram packets can only be sent to and received from + the specified target. Packets from other sources are ignored. Connecting a datagram socket is not + required. Establishing a connection can remove the need to filter out extraneous packets from + other sources. However, a UDP socket connection is not a persistent network connection (as it + is for a TCP connection). It is possible that the remote end of the socket does not even exist.

+ +

If the bind() method has not been called, the socket is + automatically bound to the default local address and port.

+ +
receive + Enables this DatagramSocket object to receive incoming packets on the bound IP address and port. + Enables this DatagramSocket object to receive incoming packets on the bound IP address and port. + +

The function returns immediately. The DatagramSocket object dispatches a data event + when a data packet is received.

+ +
dataflash.events:DatagramSocketDataEventwhen a UDP packet is received. + + when a UDP packet is received.
send + Sends packet containing the bytes in the ByteArray using UDP.This error occurs when port is less than 1 or greater than 65535. + + RangeErrorRangeErrorIf the socket is not connected and address is not a well-formed IP address. + + ArgumentErrorArgumentErrorThis error occurs: +
  1. If bind() has not been called, and when default binding to the + destination address family is not possible.
  2. On some operating systems, an IOError is thrown if the connect() method is + called when an ICMP "destination unreachable" message has already been + received from the target host. (Thus, the error is thrown on the second failed attempt to send data, not the first.) Other + operating systems, such as Windows, disregard these ICMP messages, so no error is thrown.
+ +
IOErrorflash.errors:IOError
when the bytes parameter is null. + + ErrorErrorIf offset is greater than the length of the ByteArray specified in + bytes or if the amount of data specified to be written by offset plus + length exceeds the data available. + + RangeErrorRangeErrorIf the address or port parameters are specified + when the socket has already been connected. + + IllegalOperationErrorflash.errors:IllegalOperationErrorbytesflash.utils:ByteArraya ByteArray containing the packet data. + + offsetuint0The zero-based offset into the bytes ByteArray + object at which the packet begins. + + lengthuint0The number of bytes in the packet. The default value of 0 causes + the entire ByteArray to be sent, starting at the value specified by + the offset parameter. + + addressStringnullThe IPv4 or IPv6 address of the remote machine. An address is required + if one has not already been specified using the connect() method. + + portint0The port number on the remote machine. A value greater than 0 and + less than 65536 is required if the port has not already been specified using the + connect() method. + + +
+ Sends packet containing the bytes in the ByteArray using UDP. + +

If the socket is connected, the packet + is sent to the remote address and port specified in the connect() + method and no destination IP address and port can be specified. If the socket is + not connected, the packet is sent to the specified address and port + and you must supply valid values for address and port. + If the bind() method has not been called, the socket is + automatically bound to the default local address and port.

+ +

Note: Sending data to a broadcast address is not supported.

+ +
bound + Indicates whether this socket object is currently bound to a local address + and port.Boolean + Indicates whether this socket object is currently bound to a local address + and port. + + bind()connected + Indicates whether this socket object is currently connected to a remote address + and port.Boolean + Indicates whether this socket object is currently connected to a remote address + and port. + +

Note: A value of true does not mean that a remote computer + is listening on the connected address and port. It only means that this DataGramSocket object + will only send data to or receive data from that address and port.

+ +
connect()
isSupported + Indicates whether or not DatagramSocket features are supported in the run-time environment.Boolean + Indicates whether or not DatagramSocket features are supported in the run-time environment. + + + localAddress + The IP address this socket is bound to on the local machine.String + The IP address this socket is bound to on the local machine. + + bind()localPort + The port this socket is bound to on the local machine.int + The port this socket is bound to on the local machine. + + bind()remoteAddress + The IP address of the remote machine to which this socket is connected.String + The IP address of the remote machine to which this socket is connected. + + connect()remotePort + The port on the remote machine to which this socket is connected.int + The port on the remote machine to which this socket is connected. + + connect()
NetGroupSendResult +The NetGroupSendResult class is an enumeration of constant values used for the return value of the +Directed Routing methods associated with a NetGroup instance.Object +The NetGroupSendResult class is an enumeration of constant values used for the return value of the +Directed Routing methods associated with a NetGroup instance. + +flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()ERROR + Indicates an error occurred (such as no permission) when using a Directed Routing method.errorString + Indicates an error occurred (such as no permission) when using a Directed Routing method. + + NO_ROUTE + Indicates no neighbor could be found to route the message toward its requested destination.no routeString + Indicates no neighbor could be found to route the message toward its requested destination. + + SENT + Indicates that a route was found for the message and it was forwarded toward its destination.sentString + Indicates that a route was found for the message and it was forwarded toward its destination. + + URLRequestDefaults + The URLRequestDefaults class includes static properties that you can set to define + default values for the properties of the URLRequest class.Object + The URLRequestDefaults class includes static properties that you can set to define + default values for the properties of the URLRequest class. It also includes a static + method, URLRequestDefaults.setLoginCredentialsForHost(), which lets you define + default authentication credentials for requests. The URLRequest class defines + the information to use in an HTTP request. + +

Any properties set in a URLRequest object override those static properties set for + the URLRequestDefaults class.

+ +

URLRequestDefault settings only apply to content in the caller's application domain, + with one exception: settings made by calling URLRequestDefaults.setLoginCredentialsForHost() + apply to all application domains in the currently running application.

+ +

Only Adobe® AIR® content running in the application security sandbox can + use the URLRequestDefaults class. Other content will result in a SecurityError being thrown when accessing the + members or properties of this class.

+ +
URLRequestsetLoginCredentialsForHost + Sets default user and password credentials for a selected host.The caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrorhostnameStringThe host name to which the user name and password are applied. This + can be a domain, such as "www.example.com" or a domain and a port number, + such as "www.example.com:80". Note that "example.com", + "www.example.com", and "sales.example.com" are each considered + unique hosts. + + userStringThe default user name to use in request authentication for the specified host. + + passwordStringThe default password to use in request authentication for the specified host. + + + Sets default user and password credentials for a selected host. These settings + apply for URLRequest objects in all application domains of the application, + not only those in the application domain of the object calling this method + (whereas the static properties of the URLRequest class apply to the caller's + application domain only). This allows content in the entire application + (regardless of the content's application domain) to be logged in when another + part of the application logs in. + +

Note for applications running on Mac OS: On Mac OS, when you call + this method, the application uses these credentials for the specified host + until the application is closed, even if you subsequently call + URLRequestDefaults.setLoginCredentialsForHost() for the same host. + However, if a server rejects the credentials specified by this method, + then a subsequent call to the URLRequestDefaults.setLoginCredentialsForHost() + method (for the same host) will be recognized.

+ +

Note: This method does not apply to URLRequest objects used in file upload or + RTMP requests.

+ +
authenticate + The default setting for the authenticate property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + The default setting for the authenticate property of URLRequest objects. + Setting the authenticate property in a URLRequest object overrides this default setting. + +

Note: This setting does not apply to URLRequest objects used in file upload or + RTMP requests.

+ +
URLRequest.authenticate
cacheResponse + The default setting for the cacheResponse property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + The default setting for the cacheResponse property of URLRequest objects. + Setting the cacheResponse property in a URLRequest object overrides this default setting. + When set to true, the default behavior for the AIR application is to use the operating system's + HTTP cache. This setting does not apply to URLRequest objects used in file upload or RTMP requests. + + URLRequest.cacheResponsefollowRedirects + The default setting for the followRedirects property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + The default setting for the followRedirects property of URLRequest objects. + Setting the followRedirects property in a URLRequest object overrides this default setting. + This setting does not apply to URLRequest objects used in file upload or RTMP requests. + + URLRequest.followRedirectsidleTimeout + The default setting for the idleTimeout property of URLRequest objects and HTMLLoader objects.NumberThe caller is not in the AIR application security sandbox. + SecurityErrorSecurityErrorThe idleTimeout value is negative. + + RangeErrorRangeError0 + + + The default setting for the idleTimeout property of URLRequest objects and HTMLLoader objects. + +

The idle timeout is the amount of time (in milliseconds) that the client waits for a response from the server, + after the connection is established, before abandoning the request.

+ +

This defines the default idle timeout used by the URLRequest or HTMLLoader object. Setting the idleTimeout + property in a URLRequest object or an HTMLLoader object overrides this default setting.

+ +

When this property is set to 0 (the default), the runtime uses the default idle timeout value defined by the operating system. + The default idle timeout value varies between operating systems (such as Mac OS, Linux, or Windows) and between + operating system versions.

+ +

This setting does not apply to URLRequest objects used in file upload or RTMP requests.

+ +
HTMLLoader.idleTimeoutURLRequest.idleTimeout
manageCookies + The default setting for the manageCookies property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + The default setting for the manageCookies property of URLRequest objects. + Setting the manageCookies property in a URLRequest object overrides this default setting. + +

Note: This setting does not apply to URLRequest objects used in file upload or + RTMP requests.

+ +
URLRequest.manageCookies
useCache + The default setting for the useCache property of URLRequest objects.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + The default setting for the useCache property of URLRequest objects. + Setting the useCache property in a URLRequest object overrides this default setting. + This setting does not apply to URLRequest objects used in file upload or RTMP requests. + + URLRequest.useCacheuserAgent + The default setting for the userAgent property of URLRequest objects.StringThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityError + The default setting for the userAgent property of URLRequest objects. + Setting the userAgent property in a URLRequest object overrides this + default setting. + +

This is also the default user agent string for all HTMLLoader objects (used + when you call the load() method of the HTMLLoader object). Setting + the userAgent property of the HTMLLoader object overrides the + URLRequestDefaults.userAgent setting.

+ +

This default value varies depending on the runtime operating system (such as Mac OS, Linux or Windows), + the runtime language, and the runtime version, as in the following examples:

+ +
  • "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (Windows; U; en) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
  • "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/526.9+ (KHTML, like Gecko) AdobeAIR/1.5"
+ +
flash.net.URLRequest.userAgentflash.html.HTMLLoader.userAgent
NetGroup +Instances of the NetGroup class represent membership in an RTMFP group.flash.events:EventDispatcher +Instances of the NetGroup class represent membership in an RTMFP group. Use this class +to do the following: + +
  • Monitor Quality of Service. The info property contains a NetGroupInfo object whose properties provide +QoS statistics for this group.
  • Posting. Call post() to broadcast ActionScript messages to all members of a group.
  • Direct routing. Call sendToNearest(), sendToNeighbor(), and +sendToAllNeighbors() to send a short data message to a specific member of a peer-to-peer group. +The source and the destination do not need to have a direct connection.
  • Object replication. Call addHaveObjects(), removeHaveObjects(), addWantObjects(), removeWantObjects(), +writeRequestedObject(), and denyRequestedObject() to break up large data into pieces and replicate it to all nodes in a peer-to-peer group.
+ +

In the client-side NetGroup class, the NetConnection dispatches the following events:

+ +
  • NetGroup.Connect.Success
  • NetGroup.Connect.Failed
  • NetGroup.Connect.Rejected
+ +

The info.group property of the event object contains a reference to the event source (the NetGroup). +The NetGroup dispatches all other events. In the server-side NetGroup class, the NetGroup dispatches all events.

+ +

For information about peer-assisted networking, see +Basics of P2P in Flash by Adobe Evangelist Tom Krcha. For information about using groups with peer-assisted networking, see +Social Media Experiences with Flash Media +and RTMFP, also by Tom Krcha.

+ +

For information about the technical details behind peer-assisted networking, see P2P on the Flash Platform with RTMFP by Adobe Computer Scientist Matthew Kaufman.

+ +
This is a simple video chat application that uses peer-to-peer networking. + The application connects over RTMFP to Flash Media Server. + The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- + data is not sent back to the server. +

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any + GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use + the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group + name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with + client A or anyone in the "firstmesh" group.

+ + + + +<?xml version="1.0" encoding="utf-8"?> +<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%" applicationComplete="OnApplicationComplete()"> + <mx:Script> + <![CDATA[ + private var netConnection:NetConnection = null; + private var netStream:NetStream = null; + private var netGroup:NetGroup = null; + private var video:Video = null; + private var sequenceNumber:uint = 0; + private var resizeTimer:Timer = null; + + private const SERVER:String = "rtmfp://fms.example.com/someapp"; + + [Bindable] private var connected:Boolean = false; + [Bindable] private var joinedGroup:Boolean = false; + + private function OnApplicationComplete():void + { + userName.text = "user " + int(Math.random() * 65536); + + groupName.text = "channel" + (int(Math.random() * 899) + 101); + + resizeTimer = new Timer(2000.0); + resizeTimer.addEventListener(TimerEvent.TIMER, DoResizeVideo); + resizeTimer.start(); + } + + private function StatusMessage(msg:Object):void + { + statusLog.text += msg; + statusLog.verticalScrollPosition = statusLog.textHeight; + statusLog.validateNow(); + } + + private function NetStatusHandler(e:NetStatusEvent):void + { + StatusMessage(e.info.code); + switch(e.info.code) + { + case "NetConnection.Connect.Success": + OnConnect(); + break; + + case "NetConnection.Connect.Closed": + case "NetConnection.Connect.Failed": + case "NetConnection.Connect.Rejected": + case "NetConnection.Connect.AppShutdown": + case "NetConnection.Connect.InvalidApp": + OnDisconnect(); + break; + + case "NetStream.Connect.Success": // e.info.stream + OnNetStreamConnect(); + break; + + case "NetStream.Connect.Rejected": // e.info.stream + case "NetStream.Connect.Failed": // e.info.stream + DoDisconnect(); + break; + + case "NetGroup.Connect.Success": // e.info.group + OnNetGroupConnect(); + break; + + case "NetGroup.Connect.Rejected": // e.info.group + case "NetGroup.Connect.Failed": // e.info.group + DoDisconnect(); + break; + + case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID + OnPosting(e.info.message); + break; + + + case "NetStream.MulticastStream.Reset": + case "NetStream.Buffer.Full": + DoResizeVideo(); + break; + + case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal + case "NetGroup.LocalCoverage.Notify": // + case "NetGroup.Neighbor.Connect": // e.info.neighbor + case "NetGroup.Neighbor.Disconnect": // e.info.neighbor + case "NetGroup.MulticastStream.PublishNotify": // e.info.name + case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name + case "NetGroup.Replication.Fetch.SendNotify": // e.info.index + case "NetGroup.Replication.Fetch.Failed": // e.info.index + case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object + case "NetGroup.Replication.Request": // e.info.index, e.info.requestID + default: + break; + } + } + + private function DoConnect():void + { + StatusMessage("Connecting to \"" + SERVER + "\" ...\n"); + netConnection = new NetConnection(); + netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); + netConnection.connect(SERVER); + } + + private function OnConnect():void + { + var groupSpecifier:GroupSpecifier; + + StatusMessage("Connected\n"); + connected = true; + + groupSpecifier = new GroupSpecifier("max2009lab/" + groupName.text); + groupSpecifier.multicastEnabled = true; + groupSpecifier.postingEnabled = true; + groupSpecifier.serverChannelEnabled = true; + + netStream = new NetStream(netConnection, groupSpecifier.groupspecWithAuthorizations()); + netStream.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); + + netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations()); + netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); + + StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n"); + } + + private function OnNetStreamConnect():void + { + netStream.client = this; + + var mic:Microphone = Microphone.getMicrophone(); + if(mic) + { + mic.codec = SoundCodec.SPEEX; + mic.setSilenceLevel(0); + + netStream.attachAudio(mic); + + StatusMessage("got microphone\n"); + } + + var camera:Camera = Camera.getCamera(); + if(camera) + { + camera.setMode(320, 240, 10); + camera.setQuality(30000, 0); + camera.setKeyFrameInterval(15); + + videoDisplay.attachCamera(camera); + videoDisplay.maintainAspectRatio = true; + + netStream.attachCamera(camera); + + StatusMessage("got camera\n"); + } + + netStream.publish("stream"); + } + + private function OnNetGroupConnect():void + { + joinedGroup = true; + } + + private function DoDisconnect():void + { + if(netConnection) + netConnection.close(); + videoDisplay.attachCamera(null); + } + + private function OnDisconnect():void + { + StatusMessage("Disconnected\n"); + netConnection = null; + netStream = null; + netGroup = null; + connected = false; + joinedGroup = false; + } + + private function ClearChatText():void + { + chatText.text = ""; + } + + private function DoPost():void + { + var message:Object = new Object; + + message.user = userName.text; + message.text = chatText.text; + message.sequence = sequenceNumber++; + message.sender = netConnection.nearID; + + netGroup.post(message); + + StatusMessage("==> " + chatText.text + "\n"); + + chatText.callLater(ClearChatText); + } + + private function OnPosting(message:Object):void + { + StatusMessage("<" + message.user + "> " + message.text + "\n"); + } + + private function DoResizeVideo(ignored:* = null):void + { + if(video) + { + if( (0 == video.videoHeight) + || (0 == video.videoWidth) + ) + { + video.height = videoDisplay.height; + video.width = videoDisplay.width; + video.x = 0; + video.y = 0; + } + else + { + var videoAspect:Number = Number(video.videoWidth) / Number(video.videoHeight); + var displayAspect:Number = Number(videoDisplay.width) / Number(videoDisplay.height); + var adjustFactor:Number; + + if(videoAspect >= displayAspect) // video is wider than display + { + adjustFactor = Number(video.videoWidth) / Number(videoDisplay.width); + video.width = videoDisplay.width; + video.height = int(Number(video.videoHeight) / adjustFactor); + video.x = 0; + video.y = int((videoDisplay.height - video.height) / 2); + } + else + { + adjustFactor = Number(video.videoHeight) / Number(videoDisplay.height); + video.height = videoDisplay.height; + video.width = int(Number(video.videoWidth) / adjustFactor); + video.x = int((videoDisplay.width - video.width) / 2); + video.y = 0; + } + } + } + } + + public function onPlayStatus(info:Object):void {} + public function onMetaData(info:Object):void {} + public function onCuePoint(info:Object):void {} + public function onTextData(info:Object):void {} + + public function ValidateConnectAllowed(isConnected:Boolean, groupNameText:String):Boolean + { + return (!isConnected) && (groupNameText.length > 0); + } + ]]> + </mx:Script> + + <mx:VBox top="10" right="10" left="10" bottom="10" verticalGap="6"> + <mx:HBox width="100%"> + <mx:Text text="Group:"/> + <mx:TextInput id="groupName" width="100%" text="default" enabled="{!connected}"/> + <mx:Button label="Connect" click="DoConnect()" enabled="{ValidateConnectAllowed(connected, groupName.text)}" /> + <mx:Button label="Disconnect" click="DoDisconnect()" enabled="{connected}" /> + </mx:HBox> + <mx:VideoDisplay id="videoDisplay" width="320" height="240" resize="DoResizeVideo()"/> + <mx:TextArea id="statusLog" width="100%" height="100%"/> + <mx:HBox width="100%"> + <mx:TextInput id="userName" width="160" /> + <mx:TextInput id="chatText" width="100%" enabled="{joinedGroup}" enter="DoPost()"/> + </mx:HBox> + </mx:VBox> + +</mx:Application> +
flash.net.GroupSpecifierflash.net.NetStreamflash.events.NetStatusEvent info.code values starting with "NetGroup."netStatus + Dispatched when a NetGroup object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent + Dispatched when a NetGroup object is reporting its status or error condition. + The netStatus event contains an info property. + The info property is an object that contains information about the event, + such as whether a connection attempt succeeded or failed. + flash.events.NetStatusEvent.infoNetGroup + Constructs a NetGroup on the specified NetConnection object and joins it to the group + specified by groupspec.The NetConnection instance is not connected. + ArgumentErrorArgumentErrorThe groupspec is invalid. + + ErrorErrorconnectionflash.net:NetConnectionA NetConnection object. + groupspecStringA string specifying the RTMFP peer-to-peer group to join, including its name, capabilities, + restrictions, and the authorizations of this member. + + + new NetGroup(myConnection, myGroupSpecifier.groupspecWithAuthorizations()); + + + Constructs a new NetGroup on the specified NetConnection object and joins it to the specified group. + + + Constructs a NetGroup on the specified NetConnection object and joins it to the group + specified by groupspec. + +

In most cases, a groupspec has the potential for using the network uplink on the local system. + When a NetStream or NetGroup object is constructed with a groupspec, Flash Player displays a Privacy Dialog. + The dialog asks whether Flash Player can use the connection to share data with a user's peers. + If the user clicks "Allow for this domain", the dialog is not displayed the next time the user connects to this application. + If a user does not allow peer-assisted networking, all peer features within the group (posting, directed routing, and object replication, and multicast) + are disabled. If permission is allowed, a NetStatusEvent is sent to the NetConnection's event listener + with NetGroup.Connect.Success in the code property of the info object. + If permission is denied, the code property is NetGroup.Connect.Rejected. + Until a NetGroup.Connect.Success event is received, an exception is thrown + if you try to call any method of the NetGroup object.

+ +

Note: When a client subscribes to a native-IP multicast stream, the security dialog is not displayed.

+ +
flash.events.NetStatusEvent.info.code="NetGroup.Connect.Success"flash.events.NetStatusEvent.info.code="NetGroup.Connect.Rejected"flash.net.NetConnectionflash.net.GroupSpecifier
addHaveObjects + Adds objects from startIndex through endIndex, to the set of objects this node + advertises to neighbors as objects for which it fulfills requests.A number passed to this method is less than 0 + or greater than 9007199254740992. + + RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to add to the Have set. + endIndexNumberThe end of the range of object indices to add to the Have set. + + Adds objects to the set of objects this node advertises to neighbors as objects for which it fulfills requests. + + + Adds objects from startIndex through endIndex, to the set of objects this node + advertises to neighbors as objects for which it fulfills requests. By default, + the Have set is empty. Indices must be whole numbers from 0 through 9007199254740992. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

This method sends a NetStatusEvent to the NetGroup's event listener with "NetGroup.Replication.Request" + in the code property of the info object.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
removeHaveObjects()writeRequestedObject()denyRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
addMemberHint + Manually adds a record specifying that peerID is a member of the group.TRUE for success, FALSE for failure. + + + BooleanpeerIDStringThe peerID to add to the set of potential neighbors. + Manually adds a record specifying that peerID is a member of the group, but doesn't necessarily connect immediately. + + Manually adds a record specifying that peerID is a member of the group. + An immediate connection to it is attempted only if it is needed for the topology. + + addNeighbor()addNeighbor + Manually adds a neighbor by immediately connecting directly to the specified peerID, which must already be + in this group.TRUE for success, FALSE for failure. + + BooleanpeerIDStringThe peerID to which to immediately connect. + Manually adds a neighbor by immediately connecting directly to the specified peerID. + + Manually adds a neighbor by immediately connecting directly to the specified peerID, which must already be + in this group. This direct connection may later be dropped if it is not needed for the topology. + + addMemberHint()addWantObjects + Adds objects from startIndex through endIndex, to the set of objects to retrieve.A number passed to this method is less than 0 + or greater than 9007199254740992. + + RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to add to the Want set. + endIndexNumberThe end of the range of object indices to add to the Want set. + + Adds objects to the set of objects to retrieve. + + + Adds objects from startIndex through endIndex, to the set of objects to retrieve. + Indices must be whole numbers from 0 through 9007199254740992. + By default, the Want set is empty. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

This method sends a NetStatusEvent to the NetGroup's event listener with + NetGroup.Replication.Fetch.SendNotify + in the info.code property. This event is followed by an NetGroup.Replication.Fetch.Failed + or NetGroup.Replication.Fetch.Result event.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
removeWantObjects()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.SendNotify"flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Failed"flash.events.NetStatusEvent.info.code="NetGroup.Replication.Fetch.Result"
close + Disconnect from the group and close this NetGroup. + Disconnect from the group and close this NetGroup. This NetGroup is not usable after calling this method. + + convertPeerIDToGroupAddress + Converts a peerID to a group address suitable for use with the sendToNearest() method.The group address for the peerID. + + StringpeerIDStringThe peerID to convert. + Converts a peerID to a group address suitable for use with the sendToNearest() method. + + Converts a peerID to a group address suitable for use with the sendToNearest() method. + + flash.net.NetConnection.farIDflash.net.NetConnection.nearIDflash.net.NetStream.farIDsendToNearest()denyRequestedObject + Denies a request received in a NetStatusEvent + NetGroup.Replication.Request for an object previously advertised with + addHaveObjects().requestIDintThe request identifier as given in the NetGroup.Replication.Request event. + + Denies a request for an object previously advertised. + + Denies a request received in a NetStatusEvent + NetGroup.Replication.Request for an object previously advertised with + addHaveObjects(). The requestor can request this object again unless + or until it is withdrawn from the Have set. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
addHaveObjects()writeRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
post + Sends a message to all members of a group.The messageID of the message if posted, or null on error. The messageID is the hexadecmial of the SHA256 of the raw + bytes of the serialization of the message. + + StringmessageObjectThe message to send to all other members of the group. + + Sends a message to all members of a group. To call this method, + the GroupSpecifier.postingEnabled property must be true in the groupspec passed to the + NetGroup constructor. For more information, see "Post messages to a group" + in Flash Media Server Developer’s Guide. + +

All messages must be unique. A message that is identical to one posted + earlier might not be propagated. Use a sequence number to make messages unique.

+ +

Message delivery is not ordered. Message delivery is not guaranteed.

+ +

Messages are serialized in AMF. The message can be one of the following types: + an Object, an int, a Number, or a String. The message cannot be a MovieClip.

+ +

This method sends a NetStatusEvent to the NetGroup's event listener + with "NetGroup.Posting.Notify" in the info.code property. The "NetGroup.Posting.Notify" event + is dispatched to the NetGroup on both the client and the server.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
This is a simple text chat application that uses peer-to-peer networking. + The application connects over RTMFP to Flash Media Server. + The server keeps the client applications' fingerprints and manages the peer group as clients connect. However, all data is sent between clients (peers) -- + data is not sent back to the server. +

When you run the application, you can enter any group name into the text input field. The GroupSpecifier class uses the name (along with any + GroupSpecifier properties you've set) to create a string which is the perpetually unique name of the group. To connect another client to the group, that client must use + the same group name. For example, if client A uses the group name "firstmesh", other clients that want to communicate with client A must also use the group + name "firstmesh". If client B uses the group name "kite", it will connect successfully, but it will create a new group and won't be able to communicate with + client A or anyone in the "firstmesh" group.

+

To run this example, add a Button, a Label, a TextInput, and a TextArea component to the Library in Flash Pro.

+ + + + + +package { + + import flash.display.Sprite; + import flash.events.TextEvent; + import flash.events.MouseEvent; + import flash.events.NetStatusEvent; + import fl.events.ComponentEvent; + import fl.controls.Label; + import fl.controls.Button; + import fl.controls.TextInput; + import fl.controls.TextArea; + import flash.text.TextFieldAutoSize; + import flash.net.*; + + public class NetGroupPostExample extends Sprite{ + + private var connectButton:Button; + private var disconnectButton:Button; + private var groupNameText:TextInput; + private var userNameText:TextInput; + private var chatText:TextInput; + private var statusLog:TextArea; + private var groupLabel:Label; + private var userLabel:Label; + + private var netConnection:NetConnection = null; + private var netGroup:NetGroup = null; + private var sequenceNumber:uint = 0; + private var connected:Boolean = false; + private var joinedGroup:Boolean = false; + + private const SERVER:String = "rtmfp://fms.example.com/someapp"; + + public function NetGroupPostExample() { + DoUI(); + } + + // Writes messages to the TextArea. + private function StatusMessage(msg:Object):void{ + statusLog.text += msg; + statusLog.verticalScrollPosition = statusLog.textHeight; + statusLog.validateNow(); + } + + // Handles all NetStatusEvents for the NetConnection and the NetGroup. + // This code includes cases it doesn't handle so you can see the cases + // and their info objects for learning purposes. + private function NetStatusHandler(e:NetStatusEvent):void{ + StatusMessage(e.info.code + "\n"); + switch(e.info.code){ + case "NetConnection.Connect.Success": + connectButton.enabled = false; + disconnectButton.enabled = true; + OnConnect(); + break; + + case "NetConnection.Connect.Closed": + OnDisconnect(); + break; + + case "NetGroup.Connect.Success": // e.info.group + OnNetGroupConnect(); + break; + + case "NetGroup.Connect.Rejected": // e.info.group + case "NetGroup.Connect.Failed": // e.info.group + break; + + case "NetGroup.Posting.Notify": // e.info.message, e.info.messageID + OnPosting(e.info.message); + break; + + case "NetStream.MulticastStream.Reset": + case "NetStream.Buffer.Full": + break; + + case "NetGroup.SendTo.Notify": // e.info.message, e.info.from, e.info.fromLocal + case "NetGroup.LocalCoverage.Notify": // + case "NetGroup.Neighbor.Connect": // e.info.neighbor + case "NetGroup.Neighbor.Disconnect": // e.info.neighbor + case "NetGroup.MulticastStream.PublishNotify": // e.info.name + case "NetGroup.MulticastStream.UnpublishNotify": // e.info.name + case "NetGroup.Replication.Fetch.SendNotify": // e.info.index + case "NetGroup.Replication.Fetch.Failed": // e.info.index + case "NetGroup.Replication.Fetch.Result": // e.info.index, e.info.object + case "NetGroup.Replication.Request": // e.info.index, e.info.requestID + default: + break; + } + } + // Creates a NetConnection to Flash Media Server if the app isn't already connected + // and if there's a group name in the TextInput field. + private function DoConnect(e:MouseEvent):void{ + if(!connected && (groupNameText.length > 0)){ + StatusMessage("Connecting to \"" + SERVER + "\" ...\n"); + netConnection = new NetConnection(); + netConnection.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); + // To connect to Flash Media Server, pass the server name. + netConnection.connect(SERVER); + } + else + { + StatusMessage("Enter a group name"); + } + } + + // Called in the "NetConnection.Connect.Success" case in the NetStatusEvent handler. + private function OnConnect():void{ + + StatusMessage("Connected\n"); + connected = true; + + // Create a GroupSpecifier object to pass to the NetGroup constructor. + // The GroupSpecifier determines the properties of the group + var groupSpecifier:GroupSpecifier; + groupSpecifier = new GroupSpecifier("aslrexample/" + groupNameText.text); + groupSpecifier.postingEnabled = true; + groupSpecifier.serverChannelEnabled = true; + + netGroup = new NetGroup(netConnection, groupSpecifier.groupspecWithAuthorizations()); + netGroup.addEventListener(NetStatusEvent.NET_STATUS, NetStatusHandler); + + StatusMessage("Join \"" + groupSpecifier.groupspecWithAuthorizations() + "\"\n"); + + } + + private function OnNetGroupConnect():void{ + joinedGroup = true; + } + + private function DoDisconnect(e:MouseEvent):void{ + if(netConnection){ + netConnection.close(); + } + } + + private function OnDisconnect():void{ + StatusMessage("Disconnected\n"); + netConnection = null; + netGroup = null; + connected = false; + joinedGroup = false; + connectButton.enabled = true; + disconnectButton.enabled = false; + } + + private function ClearChatText():void{ + chatText.text = ""; + } + + // Called when you the chatText field has focus and you press Enter. + private function DoPost(e:ComponentEvent):void{ + if(joinedGroup){ + var message:Object = new Object; + message.user = userNameText.text; + message.text = chatText.text; + message.sequence = sequenceNumber++; + message.sender = netConnection.nearID; + + netGroup.post(message); + StatusMessage("==> " + chatText.text + "\n"); + } else { + StatusMessage("Click Connect before sending a chat message"); + } + ClearChatText(); + } + + private function OnPosting(message:Object):void{ + StatusMessage("<" + message.user + "> " + message.text + "\n"); + } + + private function DoUI():void { + + groupLabel = new Label(); + groupLabel.move(20, 10); + groupLabel.autoSize = TextFieldAutoSize.LEFT + groupLabel.text = "Group name:" + addChild(groupLabel); + + groupNameText = new TextInput(); + groupNameText.move(90, 10); + groupNameText.text = "channel" + (int(Math.random() * 899) + 101); + addChild(groupNameText); + + connectButton = new Button(); + connectButton.addEventListener(MouseEvent.CLICK, DoConnect); + connectButton.move(205, 10); + connectButton.label = "Connect"; + addChild(connectButton); + + disconnectButton = new Button(); + disconnectButton.addEventListener(MouseEvent.CLICK, DoDisconnect); + disconnectButton.move(310, 10); + disconnectButton.label = "Disconnect"; + disconnectButton.enabled = false; + addChild(disconnectButton); + + statusLog = new TextArea(); + statusLog.move(30, 38); + statusLog.width = 360; + statusLog.height = 215; + statusLog.editable = false; + addChild(statusLog); + + userLabel = new Label(); + userLabel.move(20, 270); + userLabel.autoSize = TextFieldAutoSize.LEFT + userLabel.text = "User name:" + addChild(userLabel); + + userNameText = new TextInput(); + userNameText.move(80, 270); + userNameText.text = "user " + int(Math.random() * 65536); + addChild(userNameText); + + chatText = new TextInput(); + chatText.addEventListener(ComponentEvent.ENTER, DoPost); + chatText.move(185, 270); + chatText.maxChars = 255; + chatText.width = 215; + addChild(chatText); + + } + + public function onPlayStatus(info:Object):void {} + public function onMetaData(info:Object):void {} + public function onCuePoint(info:Object):void {} + public function onTextData(info:Object):void {} + + } + +} + + + + +
flash.events.NetStatusEvent.info.code="NetGroup.Posting.Notify"
removeHaveObjects + Removes objects from startIndex through endIndex, from the set of objects this node + advertises to neighbors as objects for which it fulfills requests.A number passed to this method is less than 0 + or greater than 9007199254740992. + + RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to remove from the Have set. + endIndexNumberThe end of the range of object indices to remove from the Have set. + + Removes objects from the set of objects this node advertises to neighbors as objects for which it fulfills requests. + + + Removes objects from startIndex through endIndex, from the set of objects this node + advertises to neighbors as objects for which it fulfills requests. + Indices must be whole numbers from 0 through 9007199254740992. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
addHaveObjects()
removeWantObjects + Removes objects from startIndex through endIndex, from the set of objects to retrieve.A number passed to this method is less than 0 + or greater than 9007199254740992. + + RangeErrorRangeErrorstartIndexNumberThe beginning of the range of object indices to remove from the Want set. + endIndexNumberThe end of the range of object indices to remove from the Want set. + + Removes objects from the set of objects to retrieve. + + + Removes objects from startIndex through endIndex, from the set of objects to retrieve. + Indices must be whole numbers from 0 through 9007199254740992. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
addWantObjects()
sendToAllNeighbors + Sends a message to all neighbors.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. + + StringmessageObjectThe message to send. + + Sends a message to all neighbors. Returns NetGroupSendResult.SENT if at least one neighbor was selected. + +

For more information about routing messages, see + "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

+ +

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener + with NetGroup.SendTo.Notify + in the code property of the info object.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
sendToNeighbor()flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"flash.net.NetGroupSendResult
sendToNearest + Sends a message to the neighbor (or local node) nearest to the specified group address.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. + + StringmessageObjectThe message to send. + groupAddressStringThe group address toward which to route the message. + + Sends a message to the neighbor (or local node) nearest to the specified group address. + Considers neighbors from the entire ring. Returns NetGroupSendResult.SENT if the message + was successfully sent toward its destination. + +

For more information about routing messages, see + "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

+ +

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener + with NetGroup.SendTo.Notify + in the code property of the info object.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
convertPeerIDToGroupAddress()receiveModeflash.net.NetGroupSendResultflash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"
sendToNeighbor + Sends a message to the neighbor specified by the sendMode parameter.A property of enumeration class NetGroupSendResult indicating the success or failure of the send. + + StringmessageObjectThe message to send. + sendModeStringA property of enumeration class NetGroupSendMode specifying the neighbor to which to send the message. + Sends message to the neighbor specified by the sendMode parameter. + + Sends a message to the neighbor specified by the sendMode parameter. + Returns NetGroupSendResult.SENT if the message was successfully sent to the requested destination. + +

For more information about routing messages, see + "Route messages directly to a peer" in Flash Media Server Developer’s Guide.

+ +

When a node receives a message, a NetStatusEvent is sent to the NetGroup's event listener + with NetGroup.SendTo.Notify + in the code property of the info object.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
sendToAllNeighbors()flash.events.NetStatusEvent.info.code="NetGroup.SendTo.Notify"flash.net.NetGroupSendModeflash.net.NetGroupSendResult
writeRequestedObject + Satisfies the request as received by + NetStatusEvent NetGroup.Replication.Request for an object previously + advertised with the addHaveObjects() method.requestIDintThe request identifier as given in the NetGroup.Replication.Request event. + objectObjectThe object corresponding to the index given in the NetGroup.Replication.Request event. + + Satisfies the request for an object that was previously advertised. + + + Satisfies the request as received by + NetStatusEvent NetGroup.Replication.Request for an object previously + advertised with the addHaveObjects() method. The object + can be any of the following: An Object, an int, a Number, and a String. + The object cannot be a MovieClip. + +

For more information about object replication, + see "Replicate an object within a group" in Flash Media Server Developer’s Guide.

+ +

NOTE: Test for the NetGroup.Neighbor.Connect event before calling this method.

+ +
addHaveObjects()denyRequestedObject()flash.events.NetStatusEvent.info.code="NetGroup.Replication.Request"
estimatedMemberCount + Specifies the estimated number of members of the group, based on local neighbor density and + assuming an even distribution of group addresses.NumberSpecifies the estimated number of members of the group. + + + Specifies the estimated number of members of the group, based on local neighbor density and + assuming an even distribution of group addresses. + + neighborCountinfo + Returns a NetGroupInfo object whose properties provide Quality of Service + statistics about this NetGroup's RTMFP peer-to-peer data transport.flash.net:NetGroupInfoReturns a NetGroupInfo object whose properties provide Quality of Service statistics. + + + Returns a NetGroupInfo object whose properties provide Quality of Service + statistics about this NetGroup's RTMFP peer-to-peer data transport. + + flash.net.NetGroupInfolocalCoverageFrom + Specifies the start of the range of group addresses for which this node is the "nearest" and responsible.String + Specifies the start of the range of group addresses for which this node is the "nearest" and responsible. + The range is specified in the increasing direction along the group address ring mod 2256. + + localCoverageToreceiveModesendToNearest()flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"localCoverageTo + Specifies the end of the range of group addresses for which this node is the "nearest" and responsible.String + Specifies the end of the range of group addresses for which this node is the "nearest" and responsible. + The range is specified in the increasing direction along the group address ring mod 2256. + + localCoverageFromreceiveModesendToNearest()flash.events.NetStatusEvent.info.code="NetGroup.LocalCoverage.Notify"neighborCount + Specifies the number of group members to which this node is directly connected.NumberSpecifies the number of group members to which this node is directly connected. + + + Specifies the number of group members to which this node is directly connected. + + addNeighbor()estimatedMemberCountflash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Connect"flash.events.NetStatusEvent.info.code="NetGroup.Neighbor.Disconnect"receiveMode + Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class.String + Specifies this node's routing receive mode as one of values in the NetGroupReceiveMode enum class. + + localCoverageFromlocalCoverageTosendToNearest()flash.net.NetGroupReceiveModereplicationStrategy + Specifies the object replication fetch strategy.String + Specifies the object replication fetch strategy. The value is one of the enumerated values + in the NetGroupReplicationStrategy class. + + flash.net.NetGroupReplicationStrategy
getClassByAlias + Looks up a class that previously had an alias registered through a call to the registerClassAlias() + method.The alias was not registered. + + ReferenceErrorReferenceErrorThe class associated with the given alias. If not found, an exception will be thrown. + + ClassaliasNameStringThe alias to find. + + + Looks up a class that previously had an alias registered through a call to the registerClassAlias() + method. +

This method does not interact with the flash.utils.getDefinitionByName() + method.

+ +
registerClassAlias()
navigateToURL + Opens or replaces a window in the application that contains the Flash Player container + (usually a browser).The digest property of the request object is not + null. You should only set the digest property of a URLRequest object + for use calling the URLLoader.load() method when loading a SWZ file (an Adobe + platform component). + + IOErrorflash.errors:IOErrorIn Flash Player (and in non-application sandbox content in Adobe AIR), + this error is thrown in the following situations: +
  • Local untrusted SWF files may not communicate with + the Internet. You can avoid this situation by reclassifying this SWF file + as local-with-networking or trusted.
  • A navigate operation attempted to evaluate a scripting + pseudo-URL, but the containing document (usually an HTML document in a + browser) is from a sandbox to which you do not have access. You can avoid this situation + by specifying allowScriptAccess="always" in the containing + document.
  • You cannot navigate the special windows + "_self", "_top", or "_parent" + if your SWF file is contained by an HTML page + that has set the allowScriptAccess to + "none", or to "sameDomain" + when the domains of the HTML file and the SWF file do not match.
  • You cannot navigate a window with a nondefault name + from within a SWF file that is in the local-with-filesystem sandbox.
  • You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.
+ +
SecurityErrorSecurityError
If the method is not called in response to a user action, such as a mouse + event or keypress event. This requirement only applies to content in Flash Player and + to non-application sandbox content in Adobe AIR. + + ErrorErrorrequestflash.net:URLRequestA URLRequest object that specifies the URL to navigate to. + +

For content running in Adobe AIR, when + using the navigateToURL() function, the runtime treats a URLRequest that uses the POST + method (one that has its method property set to URLRequestMethod.POST) + as using the GET method.

+ +
windowStringnullThe browser window or HTML frame in which to display + the document indicated by the request parameter. + You can enter the name of a specific window or use one of the following values: +
  • "_self" specifies the current frame in the current window.
  • "_blank" specifies a new window.
  • "_parent" specifies the parent of the current frame.
  • "_top" specifies the top-level frame in the current window.
+

If you do not specify a value for this parameter, a new empty window is created. + In the stand-alone player, you can either specify a new ("_blank") window + or a named window. The other values don't apply.

+ +

Note: When code in a SWF file that is running in the + local-with-filesystem sandbox calls the navigateToURL() + function and specifies a custom window name for the window + parameter, the window name is transfered into a random name. The name is in + the form "_flashXXXXXXXX", where each X represents a random + hexadecimal digit. Within the same session (until you close the containing + browser window), if you call the function again and specify the same name for + the window parameter, the same random string is used.

+ +
+ Opens or replaces a window in the application that contains the Flash Player container + (usually a browser). In Adobe AIR, the function opens a URL in the default system web browser + + +

Important Security Note

+

Developers often pass URL values to the navigateToURL() function that were obtained from external sources + such as FlashVars. Attackers may try to manipulate these external sources to perform attacks such as cross-site scripting. + Therefore, developers should validate all URLs before passing them to this function.

+ +

Good data validation for URLs can mean different things depending on the usage of the URL within the overall application. + The most common data validation techniques include validating that the URL is of the appropriate scheme. + For instance, unintentionally allowing javascript: URLs may result in cross-site scripting. + Validating that the URL is a within your domain can ensure that the SWF file can't be used as an open-redirector + by people who conduct phishing attacks. For additional security, you may also choose to validate the path of the URL + and to validate that the URL conforms to the RFC guidelines

+ +

For example, the following code shows a simple example of performing data validation by denying any URL + that does not begin with http:// or https:// and validating that the URL is within your domain name. + This example may not be appropriate for all web applications and you should consider whether additional checks + against the URL are necessary.

+ + + // AS3 Regular expression pattern match for URLs that start with http:// and https:// plus your domain name. + function checkProtocol (flashVarURL:String):Boolean { + // Get the domain name for the SWF if it is not known at compile time. + // If the domain is known at compile time, then the following two lines can be replaced with a hard coded string. + var my_lc:LocalConnection = new LocalConnection(); + var domainName:String = my_lc.domain; + // Build the RegEx to test the URL. + // This RegEx assumes that there is at least one "/" after the + // domain. http://www.mysite.com will not match. + var pattern:RegExp = new RegExp("^http[s]?\:\\/\\/([^\\/]+)\\/"); + var result:Object = pattern.exec(flashVarURL); + if (result == null || result[1] != domainName || flashVarURL.length >= 4096) { + return (false); + } + return (true); + } + + +

For local content running in a browser, calls to the + navigateToURL() method that specify a "javascript:" pseudo-protocol + (via a URLRequest object passed as the first parameter) are only permitted if the SWF + file and the containing web page (if there is one) are in the local-trusted security sandbox. + Some browsers do not support using the javascript protocol with the navigateToURL() + method. Instead, consider using the call() method of the ExternalInterface + API to invoke JavaScript methods within the enclosing HTML page.

+ +

In Flash Player, and in non-application sandboxes in Adobe AIR, + you cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

In Flash Player 10 and later running in a browser, using this method programmatically to + open a pop-up window may not be successful. Various browsers (and browser configurations) may block pop-up windows + at any time; it is not possible to guarantee any pop-up window will appear. + However, for the best chance of success, use this method to open a pop-up window only in code that executes + as a direct result of a user action (for example, in an event handler for a mouse click or key-press event.)

+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ + + +

In AIR, on mobile platforms, the sms: and tel: URI schemes are supported. On Android, vipaccess:, connectpro:, and market: URI schemes are supported. + The URL syntax is subject to the platform conventions. For example, on Android, the URI scheme must be lower case. + When you navigate to a URL using one of these schemes, the runtime opens the URL in the default application for + handling the scheme. Thus, navigating to tel:+5555555555 opens the phone dialer with the specified + number already entered. A separate application or utility, such as a phone dialer must be available to process the URL.

+ +

The following code shows how you can invoke the VIP Access and Connect Pro applications on Android:

+ + + //Invoke the VIP Access Application. + navigateToURL(new URLRequest("vipaccess://com.verisign.mvip.main?action=securitycode")); + + //Invoke the Connect Pro Application. + navigateToURL(new URLRequest("connectpro://")); + + + +
The following example opens the URL http://www.adobe.com in a new browser window and passes data about a + user session, captured in a URLVariables object, to the web server. + +package { + import flash.display.Sprite; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.net.URLVariables; + + public class NavigateToURLExample extends Sprite { + + public function NavigateToURLExample() { + var url:String = "http://www.adobe.com"; + var variables:URLVariables = new URLVariables(); + variables.exampleSessionId = new Date().getTime(); + variables.exampleUserLabel = "Your Name"; + var request:URLRequest = new URLRequest(url); + request.data = variables; + try { + navigateToURL(request); + } + catch (e:Error) { + // handle error here + } + } + } +} + The following example shows how you can open new browser windows from Flash Player using the navigateToURL() method. + Example provided by + ActionScriptExamples.com. + +// Requires +// - Button symbol on Stage (or a display object, such as a MovieClip) with instance name "buttonSymbol" +// +buttonSymbol.addEventListener(MouseEvent.CLICK, buttonSymbol_click); + +function buttonSymbol_click(evt:MouseEvent):void { + var req:URLRequest = new URLRequest("http://www.adobe.com/"); + navigateToURL(req, "_blank"); +} + The following example illustrates the syntax for launching the + device telephone dialer with a specified number. + +var request:URLRequest = new URLRequest( "tel:+5555555555" ); +navigateToURL( request ); + The following example illustrates the syntax for launching the + device text message application with a specified receipient. + +var request:URLRequest = new URLRequest( "sms:+5555555555" ); +navigateToURL( request ); + The following example illustrates the syntax for launching the + Android Market app. The search parameter is set to find the Flash Player app. + +var request:URLRequest = new URLRequest( "market://search?q=pname:com.adobe.flashplayer" ); +navigateToURL( request ); +
flash.external.ExternalInterface.call()
registerClassAlias + Preserves the class (type) of an object when the object is encoded in Action Message Format (AMF).If either parameter is null. + + TypeErrorTypeErroraliasNameStringThe alias to use. + classObjectClassThe class associated with the given alias. + + + Preserves the class (type) of an object when the object is encoded in Action Message Format (AMF). + When you encode an object into AMF, this function saves the alias for its class, so that you can + recover the class when decoding the object. + If the encoding context did not register an alias for an object's class, the object + is encoded as an anonymous object. Similarly, if the decoding context does not have the same + alias registered, an anonymous object is created for the decoded data. + +

LocalConnection, ByteArray, SharedObject, NetConnection and NetStream are all examples + of classes that encode objects in AMF.

+ +

The encoding and decoding contexts do not need to use the same class for an alias; + they can intentionally change classes, provided that the destination class contains all of the members + that the source class serializes.

+ +
This example uses the registerClassAlias() function to register + an alias (com.example.eg) for the class ExampleClass. Because + an alias is registered for the class, the object is able to be deserialized as an instance + of ExampleClass, and the code outputs true. If the registerClassAlias() + call were removed, the code would output false. + +package { + import flash.display.Sprite; + import flash.net.registerClassAlias; + import flash.utils.ByteArray; + + public class RegisterClassAliasExample extends Sprite { + public function RegisterClassAliasExample() { + registerClassAlias("com.example.eg", ExampleClass); + var eg1:ExampleClass = new ExampleClass(); + var ba:ByteArray = new ByteArray(); + ba.writeObject(eg1); + ba.position = 0; + var eg2:* = ba.readObject(); + trace(eg2 is ExampleClass); // true + } + } +} + +class ExampleClass {} +
ObjectEncoding class
sendToURL + Sends a URL request to a server, but ignores any response.Local untrusted SWF files cannot communicate with + the Internet. You can avoid this situation by reclassifying this SWF file + as local-with-networking or trusted. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + + SecurityErrorSecurityErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to send data to. + + Sends a URL request to a server, but ignores any response. +

To examine the server response, use the URLLoader.load() method instead.

+ +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

You can prevent a SWF file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content.

+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example passes data about a + user session, captured in a URLVariables object, to the application at http://www.yourDomain.com/application.jsp. + + package { + import flash.display.Sprite; + import flash.net.URLRequest; + import flash.net.URLVariables; + import flash.net.sendToURL; + + public class SendToURLExample extends Sprite { + + public function SendToURLExample() { + var url:String = "http://www.yourDomain.com/application.jsp"; + var variables:URLVariables = new URLVariables(); + variables.sessionId = new Date().getTime(); + variables.userLabel = "Your Name"; + + var request:URLRequest = new URLRequest(url); + request.data = variables; + trace("sendToURL: " + request.url + "?" + request.data); + try { + sendToURL(request); + } + catch (e:Error) { + // handle error here + } + } + } +} +
NetGroupReceiveMode +The NetGroupReceiveMode class is an enumeration of constant values used for the receiveMode property +of the NetGroup class.An enumeration of constant values used for the receiveMode property of the NetGroup class. + +Object +The NetGroupReceiveMode class is an enumeration of constant values used for the receiveMode property +of the NetGroup class. + +flash.net.NetGroup.receiveModeflash.net.NetGroup.sendToNearest()EXACT + Specifies that this node accepts local messages from neighbors only if the address the neighbor uses + matches this node's address exactly.exactString + Specifies that this node accepts local messages from neighbors only if the address the neighbor uses + matches this node's address exactly. That is, this node considers itself as nearest for any + NetGroup.sendToNearest() call only if the groupAddress parameter passed to + NetGroup.sendToNearest() matches this node's group address exactly. + This value is the default setting. + +

If you want to enable distributed routing behavior, set this value + to NetGroupReceiveMode.NEAREST. With this value set, a node waits for its connectivity to stabilize + before participating in the Directed Routing mesh.

+ + +
flash.net.NetGroup.sendToNearest()
NEAREST + Specifies that this node accepts local messages from neighbors that send messages to group + addresses that don't match this node's address exactly.nearestString + Specifies that this node accepts local messages from neighbors that send messages to group + addresses that don't match this node's address exactly. Messages are received when this node is nearest among all neighbors whose + receive mode is NetGroupReceiveMode.NEAREST. Distance is measured between addresses on the ring mod 2256. + + flash.net.NetGroup.sendToNearest()
Responder + The Responder class provides an object that is used + in NetConnection.call() to handle return + values from the server related to the success or failure of + specific operations.Object + The Responder class provides an object that is used + in NetConnection.call() to handle return + values from the server related to the success or failure of + specific operations. When working with NetConnection.call(), + you may encounter a network operation fault specific to the current operation + or a fault related to the current connection status. Operation errors target + the Responder object instead of the NetConnection object for easier error handling. + + + NetConnection.call()Responder + Creates a new Responder object.resultFunctionThe function invoked if the call to the server succeeds and returns a result. + statusFunctionnullThe function invoked if the server returns an error. + + Creates a new Responder object. You pass a Responder object to + NetConnection.call() to handle return values + from the server. You may pass null for either or + both parameters. + + URLRequestHeader + A URLRequestHeader object encapsulates a single HTTP request header + and consists of a name/value pair.Object + A URLRequestHeader object encapsulates a single HTTP request header + and consists of a name/value pair. + + URLRequestHeader objects are used in the requestHeaders property of the URLRequest class. + +

In Adobe® AIR®, content in the application security sandbox (such as + content installed with the AIR application) can use any request headers, without error. However, for content + running in Adobe AIR that is in a different security sandbox, + or for content running in Flash® Player, + using following request headers cause a runtime error to be thrown, and the + restricted terms are not case-sensitive (for example, Get, get, and GET + are each not allowed):

+ +

In Flash Player and in Adobe AIR content outside of the application security sandbox, + the following request headers cannot be used, and the restricted terms are not case-sensitive + (for example, Get, get, and GET are all not allowed). Also, + hyphenated terms apply if an underscore character is used (for example, both Content-Length and + Content_Length are not allowed):

+ +

Accept-Charset, Accept-Encoding, Accept-Ranges, Age, Allow, + Allowed, Authorization, Charge-To, Connect, + Connection, + Content-Length, Content-Location, Content-Range, Cookie, + Date, Delete, + ETag, Expect, Get, Head, Host, If-Modified-Since, + Keep-Alive, Last-Modified, Location, + Max-Forwards, Options, Origin, Post, + Proxy-Authenticate, Proxy-Authorization, Proxy-Connection, + Public, Put, + Range, Referer, Request-Range, Retry-After, Server, + TE, Trace, Trailer, Transfer-Encoding, + Upgrade, URI, User-Agent, Vary, Via, Warning, + WWW-Authenticate, x-flash-version.

+ +

URLRequestHeader objects are restricted in length. If the cumulative length of a + URLRequestHeader object (the length of the name property plus the value + property) or an array of URLRequestHeader objects used in the URLRequest.requestHeaders + property exceeds the acceptable length, an exception is thrown.

+ +

Content running in Adobe AIR sets the ACCEPT header to the following, unless you + specify a setting for the ACCEPT header in the requestHeaders + property of the URLRequest class:

+ + text/xml, + application/xml, + application/xhtml+xml, + text/html;q=0.9, + text/plain;q=0.8, + image/png, + application/x-shockwave-flash, + video/mp4;q=0.9, + flv-application/octet-stream;q=0.8, + video/x-flv;q=0.7, + audio/mp4, + ~~/~~;q=0.5 +

Not all methods that accept URLRequest parameters support the requestHeaders property, + consult the documentation for the method you are calling. For example, the FileReference.upload() + and FileReference.download() methods do not + support the URLRequest.requestHeaders property.

+

Due to browser limitations, custom HTTP request headers are only supported for POST requests, + not for GET requests.

+ +
The following example adds a single HTTP request header header to the array for the requestHeaders property. The header indicates that the application should forward the request to the origin server even if it has a cached copy of what is being requested. + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.net.URLRequestHeader; + import flash.net.URLRequestMethod; + import flash.net.URLVariables; + + public class URLRequestHeaderExample extends Sprite { + public function URLRequestHeaderExample() { + var loader:URLLoader = new URLLoader(); + configureListeners(loader); + + var header:URLRequestHeader = new URLRequestHeader("pragma", "no-cache"); + var request:URLRequest = new URLRequest("http://www.[yourdomain].com/greeting.cfm"); + request.data = new URLVariables("name=John+Doe"); + request.method = URLRequestMethod.POST; + request.requestHeaders.push(header); + try { + loader.load(request); + } catch (error:Error) { + trace("Unable to load requested document."); + } + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + var loader:URLLoader = URLLoader(event.target); + trace("completeHandler: " + loader.data); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
URLRequestURLLoaderURLRequestHeader + Creates a new URLRequestHeader object that encapsulates a single HTTP request header.nameStringAn HTTP request header name (such as Content-Type + or SOAPAction). + valueStringThe value associated with the name property + (such as text/plain). + + Creates a new URLRequestHeader object that encapsulates a single HTTP request header. + URLRequestHeader objects are used in the requestHeaders + property of the URLRequest class. + + name + An HTTP request header name (such as Content-Type or SOAPAction).String + An HTTP request header name (such as Content-Type or SOAPAction). + value + The value associated with the name property (such as text/plain).String + The value associated with the name property (such as text/plain). +
URLRequestMethod + The URLRequestMethod class provides values that specify whether the URLRequest object should + use the POST method or the GET method when sending data to a server.Object + The URLRequestMethod class provides values that specify whether the URLRequest object should + use the POST method or the GET method when sending data to a server. + + The following example loads and displays the + data found in a local text file. It also traces event handling information. + +

Note:To run this example, put a file named example.txt + in the same directory as your SWF file. That file should be a simple text file containing + a few words or lines of text. +

+

The example code does the following:

+
  1. The constructor function creates a URLLoader instance named loader.
  2. The loader object is passed to the configureListeners() method, + which adds listeners for each of the supported URLLoader events.
  3. A URLRequest instance named request is created, which specifies name of the file to be loaded.
  4. The method property of the request is set to URLRequestMethod.POST.
  5. The request object is then passed to loader.load(), which loads the text file.
  6. When the URLLoader has finished loading the text file the Event.COMPLETE event fires, + triggering the completeHandler() method. The completeHandler() method simply traces + the data property, the contents of the text file.
+ + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.*; + + public class URLRequestMethodExample extends Sprite { + + public function URLRequestMethodExample() { + var loader:URLLoader = new URLLoader(); + configureListeners(loader); + + var request:URLRequest = new URLRequest("example.txt"); + + request.method = URLRequestMethod.POST; + loader.load(request); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + var loader:URLLoader = URLLoader(event.target); + trace("completeHandler: " + loader.data); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
URLRequestURLVariablesDELETE + Specifies that the URLRequest object is a DELETE.DELETEStringSpecifies that the URLRequest object is a DELETE. + + Specifies that the URLRequest object is a DELETE. + GET + Specifies that the URLRequest object is a GET.GETStringSpecifies that the URLRequest object is a GET. + + + Specifies that the URLRequest object is a GET. + + HEAD + Specifies that the URLRequest object is a HEAD.HEADStringSpecifies that the URLRequest object is a HEAD. + + Specifies that the URLRequest object is a HEAD. + OPTIONS + Specifies that the URLRequest object is OPTIONS.OPTIONSStringSpecifies that the URLRequest object is OPTIONS. + + Specifies that the URLRequest object is OPTIONS. + POST + Specifies that the URLRequest object is a POST.POSTStringSpecifies that the URLRequest object is a POST. + + + Specifies that the URLRequest object is a POST. + +

Note: For content running in Adobe AIR, when + using the navigateToURL() function, the runtime + treats a URLRequest that uses the POST method (one that has its method property set to + URLRequestMethod.POST) as using the GET method.

+ +
PUT + Specifies that the URLRequest object is a PUT.PUTStringSpecifies that the URLRequest object is a PUT. + + + Specifies that the URLRequest object is a PUT. + +
FileReference + The FileReference class provides a means to upload and + download files between a user's computer and a server.flash.events:EventDispatcher + The FileReference class provides a means to upload and + download files between a user's computer and a server. An operating-system + dialog box prompts the user to select a file to upload or a location for + download. Each FileReference object refers to a single file on the user's disk + and has properties that contain information about + the file's size, type, name, creation date, modification date, and creator type + (Macintosh only). + +

Note: In Adobe AIR, the File class, which extends the FileReference class, + provides more capabilities and has less security restrictions than the FileReference class.

+ +

FileReference instances are created in the following ways:

+
  • When you use the new operator with the FileReference constructor: + + var myFileReference = new FileReference();
  • When you call the FileReferenceList.browse() method, which creates an array of FileReference objects.
+ +

During an upload operation, all the properties of a FileReference object are + populated by calls to the FileReference.browse() or FileReferenceList.browse() methods. + During a download operation, the name property is populated when the + select event is dispatched; all other properties are populated when the + complete event is dispatched.

+ +

The browse() method opens an operating-system dialog box that prompts the + user to select a file for upload. The FileReference.browse() method + lets the user select a single file; the FileReferenceList.browse() method + lets the user select multiple files. After a successful call to the browse() method, + call the FileReference.upload() method to upload one file at a time. The + FileReference.download() method prompts the user for a location to save + the file and initiates downloading from a remote URL.

+ +

The FileReference and FileReferenceList classes do not let you set the default file location + for the dialog box that the browse() or download() methods generate. + The default location shown in the dialog box is the most + recently browsed folder, if that location can be determined, or the desktop. + The classes do not allow you to read from or write to the transferred file. + They do not allow the SWF file that initiated the + upload or download to access the uploaded or downloaded file or the file's location on + the user's disk.

+ +

The FileReference and FileReferenceList classes also do not provide + methods for authentication. With servers that require authentication, you can + download files with the Flash® Player browser plug-in, but + uploading (on all players) and downloading (on the stand-alone or + external player) fails. Listen for FileReference events to determine whether + operations complete successfully and to handle errors.

+ +

For content running in Flash Player or for + content running in Adobe AIR outside of the application security sandbox, + uploading and downloading operations can access files only within its own domain and within + any domains that a URL policy file specifies. Put a policy file on the file server + if the content initiating the upload or download doesn't come from the same domain as the file server.

+ +

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have + only one of the following operations active at one time: FileReference.browse(), + FileReference.upload(), FileReference.download(), FileReference.load(), + FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() + to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player + are unaffected by this restriction on simultaneous multiple operations.

+ +

While calls to the FileReference.browse(), FileReferenceList.browse(), + or FileReference.download() methods are executing, SWF file playback pauses in stand-alone and external versions + of Flash Player and in AIR for Linux and Mac OS X 10.1 and earlier

+ +

The following sample HTTP POST request is sent from Flash Player to a server-side + script if no parameters are specified: +

+ +
+  POST /handler.cfm HTTP/1.1 
+  Accept: text/~~
+  Content-Type: multipart/form-data; 
+  boundary=----------Ij5ae0ae0KM7GI3KM7 
+  User-Agent: Shockwave Flash 
+  Host: www.example.com 
+  Content-Length: 421 
+  Connection: Keep-Alive 
+  Cache-Control: no-cache
+  
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Filename"
+  
+  MyFile.jpg
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg"
+  Content-Type: application/octet-stream
+  
+  FileDataHere
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Upload"
+  
+  Submit Query
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
+  
+ +

Flash Player sends the following HTTP POST request if the user + specifies the parameters "api_sig", "api_key", and + "auth_token": +

+ +
+  POST /handler.cfm HTTP/1.1 
+  Accept: text/~~
+  Content-Type: multipart/form-data; 
+  boundary=----------Ij5ae0ae0KM7GI3KM7 
+  User-Agent: Shockwave Flash 
+  Host: www.example.com 
+  Content-Length: 421 
+  Connection: Keep-Alive 
+  Cache-Control: no-cache
+  
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Filename"
+  
+  MyFile.jpg
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="api_sig"
+  
+  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="api_key"
+  
+  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="auth_token"
+  
+  XXXXXXXXXXXXXXXXXXXXXX
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Filedata"; filename="MyFile.jpg"
+  Content-Type: application/octet-stream
+  
+  FileDataHere
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
+  Content-Disposition: form-data; name="Upload"
+  
+  Submit Query
+  ------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--
+  
+
The following example displays the + data format and status information for a file loaded at runtime. +

Note: + To run this example, change the uploadURL.url property to point to an actual URL, + rather than the fictional one in the example. The URL should point to a file named + yourUploadHandlerScript.cfm in the root web directory of the URL specified. + Based on your configuration, you might also need to compile the SWF file with Local Playback Security set to Access Network Only + or to update Flash Player security settings to allow this file network access. +

+ +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileFilter; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class FileReferenceExample extends Sprite { + private var uploadURL:URLRequest; + private var file:FileReference; + + public function FileReferenceExample() { + uploadURL = new URLRequest(); + uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; + file = new FileReference(); + configureListeners(file); + file.browse(getTypes()); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CANCEL, cancelHandler); + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(Event.SELECT, selectHandler); + dispatcher.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadCompleteDataHandler); + } + + private function getTypes():Array { + var allTypes:Array = new Array(getImageTypeFilter(), getTextTypeFilter()); + return allTypes; + } + + private function getImageTypeFilter():FileFilter { + return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"); + } + + private function getTextTypeFilter():FileFilter { + return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf"); + } + + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function uploadCompleteDataHandler(event:DataEvent):void { + trace("uploadCompleteData: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + uploadURL.url); + file.upload(uploadURL); + } + } +} +
flash.net.FileReferenceListflash.filesystem.FileuploadCompleteData + Dispatched after data is received from the server after a successful upload.flash.events.DataEvent.UPLOAD_COMPLETE_DATAflash.events.DataEvent + Dispatched after data is received from the server after a successful upload. + This event is not dispatched if data is not returned from the server. + httpResponseStatus + Dispatched if a call to the upload() or uploadUnencoded() + method attempts to access data over HTTP and Adobe AIR is able to detect and return + the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent + Dispatched if a call to the upload() or uploadUnencoded() + method attempts to access data over HTTP and Adobe AIR is able to detect and return + the status code for the request. + + upload()uploadUnencoded()httpStatus + Dispatched when an upload fails and an HTTP status code is available + to describe the failure.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent + Dispatched when an upload fails and an HTTP status code is available + to describe the failure. The httpStatus event + is dispatched, followed by an ioError event. + +

The httpStatus event is dispatched only for upload failures. + For content running in Flash Player this event is not applicable for download failures. + If a download fails because of an HTTP error, the error is reported as an I/O error.

+ +
FileReference.upload()
select + Dispatched when the user selects a file for upload or download from the file-browsing dialog box.flash.events.Event.SELECTflash.events.Event + Dispatched when the user selects a file for upload or download from the file-browsing dialog box. + (This dialog box opens when you call the FileReference.browse(), + FileReferenceList.browse(), + or FileReference.download() method.) + When the user selects a file and confirms the operation (for example, by clicking OK), + the properties of the FileReference object are populated. + +

For content running in Flash Player or outside of the + application security sandbox in the Adobe AIR runtime, + the select event acts slightly differently depending on what + method invokes it. When the select event is dispatched after a browse() call, + Flash Player or the AIR application can read all the + FileReference object's properties, because the file selected by the user is on the local + file system. When the select event occurs after a download() call, + Flash Player or the AIR application can read only + the name property, because the file hasn't yet been downloaded to the local file system + at the moment the select event is dispatched. When the file is downloaded and the + complete event dispatched, Flash Player or + the AIR application can read all other properties of the FileReference object.

+ +
The following example shows usage of the select event object. + To run this example, change the uploadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + In order for this example to run from your desktop, your server also needs to have a crossdomain.xml + file posted. + If the ioErrorHandler() function is triggered, you probably need to update the provided uploadURL with + a valid url that is configured to receive uploads. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class FileReference_event_select extends Sprite { + private var uploadURL:URLRequest; + private var file:FileReference; + + public function FileReference_event_select() { + uploadURL = new URLRequest(); + uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; + file = new FileReference(); + file.addEventListener(Event.SELECT, selectHandler); + file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + file.addEventListener(ProgressEvent.PROGRESS, progressHandler); + file.addEventListener(Event.COMPLETE, completeHandler); + file.browse(); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + uploadURL.url); + file.upload(uploadURL); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + } +} +
securityError + Dispatched when a call to the FileReference.upload() + or FileReference.download() method tries to upload a file to a server or + get a file from a server that is outside the caller's security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched when a call to the FileReference.upload() + or FileReference.download() method tries to upload a file to a server or + get a file from a server that is outside the caller's security sandbox. The value of + the text property that describes the specific error that occurred + is normally "securitySandboxError". + The calling SWF file may have tried to access a SWF file + outside its domain and does not have permission to do so. You can + try to remedy this error by using a URL policy file. + +

In Adobe AIR, these security restrictions do not apply + to content in the application security sandbox.

+ +

In Adobe AIR, these security restrictions do not apply + to content in the application security sandbox.

+ +
FileReference.download()FileReference.upload()
progress + Dispatched periodically during the file upload or download operation.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched periodically during the file upload or download operation. + The progress event is dispatched while Flash Player + transmits bytes to a server, and it is periodically dispatched during the + transmission, even if the transmission is ultimately not successful. + To determine if and when the file transmission is actually successful + and complete, listen for the complete event. + +

In some cases, progress events are not received. For example, + when the file being transmitted is very small or the upload or download + happens very quickly a progress event might not be dispatched.

+ +

File upload progress cannot be determined on Macintosh platforms earlier than OS X 10.3. + The progress event is called during the upload operation, but the value of the + bytesLoaded property of the progress event is -1, + indicating that the progress cannot be determined.

+ +
The following example shows usage of the progress event. + To run this example, change the downloadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class FileReference_event_progress extends Sprite { + private var downloadURL:URLRequest; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function FileReference_event_progress() { + downloadURL = new URLRequest(); + downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; + file = new FileReference(); + file.addEventListener(ProgressEvent.PROGRESS, progressHandler); + file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + file.addEventListener(Event.COMPLETE, completeHandler); + file.download(downloadURL, fileName); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + } +} +
FileReference.completeflash.events.ProgressEventFileReference.download()FileReference.upload()
open + Dispatched when an upload or download operation starts.flash.events.Event.OPENflash.events.Event + Dispatched when an upload or download operation starts. + + + The following example shows usage of the download event object. + To run this example, change the downloadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + import flash.net.FileFilter; + + public class FileReference_download extends Sprite { + private var downloadURL:URLRequest; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function FileReference_download() { + downloadURL = new URLRequest(); + downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; + file = new FileReference(); + configureListeners(file); + file.download(downloadURL, fileName); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CANCEL, cancelHandler); + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(Event.SELECT, selectHandler); + } + + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); + } + } +} +FileReference.download()FileReference.upload()ioError + Dispatched when the upload or download fails.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when the upload or download fails. A file transfer can fail for one of the following reasons: + +
  • An input/output error occurs while the player is reading, writing, or transmitting the file.
  • The SWF file + tries to upload a file to a server that requires authentication + (such as a user name and password). During upload, Flash Player or + Adobe AIR does not provide a means for users to enter passwords. If a SWF file + tries to upload a file to a server that + requires authentication, the upload fails.
  • The SWF file + tries to download a file from a server that requires authentication, + within the stand-alone or external player. During download, the stand-alone and external players + do not provide a means for users to enter passwords. If a SWF file + in these players tries to download + a file from a server that requires authentication, the download fails. + File download can succeed only in the ActiveX control, browser plug-in + players, and the Adobe AIR runtime.
  • The value passed to the url parameter in the upload() method contains an + invalid protocol. Valid protocols are HTTP and HTTPS.
+ +

Important: Only applications running + in a browser — that is, using the browser plug-in or ActiveX control — and + content running in Adobe AIR can provide a dialog box to prompt + the user to enter a user name and password for authentication, and then only for downloads. + For uploads using the plug-in or ActiveX control version of Flash Player, or for upload or + download using either the stand-alone or the external player, the file transfer fails.

+ +
FileReference.download()FileReference.upload()
complete + Dispatched when download is complete or when upload generates an HTTP status code of 200.flash.events.Event.COMPLETEflash.events.Event + Dispatched when download is complete or when upload generates an HTTP status code of 200. + For file download, this event is dispatched when Flash Player or + Adobe AIR finishes downloading the entire file to disk. + For file upload, this event is dispatched after the + Flash Player or Adobe AIR + receives an HTTP status code of 200 from the server receiving + the transmission. + + The following example shows usage of the complete event object. + To run this example, change the downloadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class FileReference_event_complete extends Sprite { + private var downloadURL:URLRequest; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function FileReference_event_complete() { + downloadURL = new URLRequest(); + downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; + file = new FileReference(); + configureListeners(file); + file.download(downloadURL, fileName); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CANCEL, cancelHandler); + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(Event.SELECT, selectHandler); + } + + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); + } + } +} +FileReference.download()FileReference.upload()cancel + Dispatched when a file upload or download is canceled through the file-browsing dialog + box by the user.flash.events.Event.CANCELflash.events.Event + Dispatched when a file upload or download is canceled through the file-browsing dialog + box by the user. Flash Player does not dispatch this event if the user cancels an upload + or download through other means (closing the browser or stopping the current + application). + + The following example shows usage of the cancel event object. + To run this example, change the downloadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + + public class FileReference_event_cancel extends Sprite { + private var downloadURL:URLRequest; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function FileReference_event_cancel() { + downloadURL = new URLRequest(); + downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; + file = new FileReference(); + file.addEventListener(Event.CANCEL, cancelHandler); + file.download(downloadURL, fileName); + } + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + } +} +FileReference + Creates a new FileReference object. + Creates a new FileReference object. When populated, a FileReference object represents a file + on the user's local disk. + + FileReference.browse()browse + Displays a file-browsing dialog box that lets the + user select a file to upload.Thrown in the following situations: + 1) Another FileReference or FileReferenceList browse session is in + progress; only one file browsing session may be performed at a time. + 2) A setting in the user's mms.cfg file prohibits this operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the typeFilter array contains + FileFilter objects that are incorrectly formatted, an exception is thrown. + For information on the correct format for FileFilter objects, + see the FileFilter class. + + ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse + event or keypress event. + + ErrorErrorReturns true if the parameters are valid and the file-browsing dialog box + opens. + + BooleantypeFilterArraynullAn array of FileFilter instances used to filter the files that are + displayed in the dialog box. If you omit this parameter, + all files are displayed. + For more information, see the FileFilter class. + + + + Displays a file-browsing dialog box that lets the + user select a file to upload. The dialog box is native to the user's + operating system. The user can select a file on the local computer + or from other systems, for example, through a UNC path on Windows. + +

Note: The File class, available in Adobe AIR, includes methods for + accessing more specific system file selection dialog boxes. These methods are + File.browseForDirectory(), File.browseForOpen(), + File.browseForOpenMultiple(), and File.browseForSave().

+ +

When you call this method and the user + successfully selects a file, the properties of this FileReference object are populated with + the properties of that file. Each subsequent time that the FileReference.browse() method + is called, the FileReference + object's properties are reset to the file that the user selects in the dialog box. + Only one browse() or download() session + can be performed at a time (because only one dialog box can be invoked at a time).

+ +

Using the typeFilter parameter, you can determine which files the dialog box displays.

+ +

In Flash Player 10 and Flash Player 9 Update 5, you can only call this method successfully in response + to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling + this method results in Flash Player throwing an Error exception.

+ +

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have + only one of the following operations active at one time: FileReference.browse(), + FileReference.upload(), FileReference.download(), FileReference.load(), + FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() + to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player + are unaffected by this restriction on simultaneous multiple operations.

+ +

In Adobe AIR, the file-browsing dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +
select eventcancel eventFileReference.download()FileReferenceList.browse()File.browseForDirectory()File.browseForOpen()File.browseForOpenMultiple()File.browseForSave()selectflash.events:EventDispatched when the user successfully selects an item from the Browse file chooser. + Dispatched when the user successfully selects an item from the Browse file chooser.cancelflash.events:EventDispatched when the user cancels the file upload Browse window. + + Dispatched when the user cancels the file upload Browse window.
cancel + Cancels any ongoing upload or download operation on this FileReference object.Cancels any ongoing upload or download. + + Cancels any ongoing upload or download operation on this FileReference object. + Calling this method does not dispatch the cancel event; that event + is dispatched only when the user cancels the operation by dismissing the + file upload or download dialog box. + + download + Opens a dialog box that lets the user download a file from a remote server.Thrown in the following situations: 1) Another browse session is in + progress; only one file browsing session can be performed at a time. + 2) The value passed to request does not contain + a valid path or protocol. + 3) The filename to download contains prohibited characters. + 4) A setting in the user's mms.cfg file prohibits this operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorLocal untrusted content may not communicate with the Internet. To avoid this situation, reclassify this + SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the filename + and the URL that may not be accessed because of local file security restrictions. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorIf url.data is of type ByteArray, an exception is + thrown. For use with the FileReference.upload() and + FileReference.download() methods, url.data can only be of type + URLVariables or String. + + ArgumentErrorArgumentErrorThis error can occur for the following reasons: + 1) Flash Player cannot convert the URLRequest.data + parameter from UTF8 to MBCS. This error is applicable if the URLRequest object + passed to the FileReference.download() method is set to perform a GET operation and if + System.useCodePage is set to true. + 2) Flash Player cannot allocate memory for the POST data. This error is + applicable if the URLRequest object passed to the FileReference.download() method is set + to perform a POST operation. + + MemoryErrorflash.errors:MemoryErrorIf the method is not called in response to a user action, such as a mouse + event or keypress event. + + ErrorErrorrequestflash.net:URLRequestThe URLRequest object. The url property of the URLRequest object + should contain the URL of the file to download to the local computer. + If this parameter is null, an exception is thrown. The requestHeaders property + of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads. + + To send POST or GET parameters to the server, set the value of URLRequest.data + to your parameters, and set URLRequest.method to either URLRequestMethod.POST + or URLRequestMethod.GET. + +

On some browsers, URL strings are limited in length. Lengths greater than 256 characters may + fail on some browsers or servers.

+ +
defaultFileNameStringnullThe default filename displayed in the dialog box for the file + to be downloaded. This string must not contain the following characters: + / \ : ~~ ? " < > | % +

If you omit this parameter, the filename of the + remote URL is parsed and used as the default.

+ +
+ Opens a dialog box that lets the user download a file from a remote server. + Although Flash Player has no restriction on the size of files you can upload or download, + the player officially supports uploads or downloads of up to 100 MB. + +

The download() method first opens + an operating-system dialog box that asks the user to enter a filename and + select a location on the local computer + to save the file. When the user selects a location and confirms the download operation + (for example, by clicking Save), the download from the remote server begins. + Listeners receive events to indicate the progress, success, or + failure of the download. + To ascertain the status of the dialog box and the download operation after calling + download(), your code must listen for events + such as cancel, open, + progress, and complete. +

+ +

The FileReference.upload() and FileReference.download() functions + are nonblocking. These functions return after they are called, before the file transmission + is complete. In addition, if the FileReference object goes out of scope, any upload or download + that is not yet completed on that object is canceled upon leaving the scope. + Be sure that your FileReference object remains in scope for as long as the + upload or download is expected to continue.

+ +

When the file is downloaded successfully, the + properties of the FileReference object are populated with the properties + of the local file. The complete event is dispatched if the + download is successful.

+ +

Only one browse() or download() session can + be performed at a time (because only one dialog box can be invoked at a time).

+ +

This method supports downloading of any file type, with either HTTP or HTTPS.

+ +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

Note: If your server requires user authentication, only + SWF files running in a browser — that is, using the browser plug-in or ActiveX control — + can provide a dialog box to prompt the user for a user name and password for authentication, + and only for downloads. For uploads using the plug-in or ActiveX control, or for + uploads and downloads using the stand-alone or external player, the file transfer fails.

+ +

When you use this method , consider the Flash Player + security model:

+ +
  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a + resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking + parameter of the the object and embed tags in the HTML + page that contains the SWF content.
  • In Flash Player 10 and Flash Player 9 Update 5, you can only call this method successfully in response + to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling + this method results in Flash Player throwing an Error exception.
+ +

However, in Adobe AIR, + content in the application security sandbox (content + installed with the AIR application) is not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ + +

When you download a file using this method, it is flagged as downloaded on operating systems + that flag downloaded files:

+ +
  • Windows XP service pack 2 and later, and on Windows Vista
  • Mac OS 10.5 and later
+ +

Some operating systems, such as Linux, do not flag downloaded files.

+ +

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have + only one of the following operations active at one time: FileReference.browse(), + FileReference.upload(), FileReference.download(), FileReference.load(), + FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() + to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player + are unaffected by this restriction on simultaneous multiple operations.

+ + +

In Adobe AIR, the download dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +
The following example shows usage of the download event object. + To run this example, change the downloadURL.url property to point to an actual domain and file, + rather than the fictional http://www.[yourDomain].com/SomeFile.pdf. + You might also need to compile the SWF file with Local playback security set to Access network only + or to update Flash Player security settings to allow this file network access. + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.URLRequest; + import flash.net.FileFilter; + + public class FileReference_download extends Sprite { + private var downloadURL:URLRequest; + private var fileName:String = "SomeFile.pdf"; + private var file:FileReference; + + public function FileReference_download() { + downloadURL = new URLRequest(); + downloadURL.url = "http://www.[yourDomain].com/SomeFile.pdf"; + file = new FileReference(); + configureListeners(file); + file.download(downloadURL, fileName); + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.CANCEL, cancelHandler); + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(Event.SELECT, selectHandler); + } + + private function cancelHandler(event:Event):void { + trace("cancelHandler: " + event); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function selectHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url); + } + } +} +
File.downloadedFileReference.browse()FileReferenceList.browse()FileReference.upload()FileReference.save()openflash.events:EventDispatched when a download operation starts. + Dispatched when a download operation starts.progressflash.events:ProgressEventDispatched periodically during the file download operation. + Dispatched periodically during the file download operation.completeflash.events:EventDispatched when the file download operation successfully completes. + Dispatched when the file download operation successfully completes.cancelflash.events:EventDispatched when the user dismisses the dialog box. + Dispatched when the user dismisses the dialog box.selectflash.events:EventDispatched when the user selects a file for download from the dialog box. + Dispatched when the user selects a file for download from the dialog box.securityErrorflash.events:SecurityErrorEventDispatched when a download fails because of a + security error. + Dispatched when a download fails because of a + security error.ioErrorflash.events:IOErrorEventDispatched for any of the following reasons: +
  • An input/output error occurs while the file is being read or transmitted.
  • SWF content running in the stand-alone or external versions of Flash Player tries to download a + file from a server that requires authentication. During download, the standalone and external players + do not provide a means for users to enter passwords. If a SWF file in these players tries to download + a file from a server that requires authentication, the download fails. + File download can succeed only in the ActiveX control and browser plug-in players.
+ +
Dispatched for any of the following reasons: + + An input/output error occurs while the file is being read or transmitted. + SWF content running in the stand-alone or external versions of Flash Player tries to download a + file from a server that requires authentication.
load + Starts the load of a local file selected by a user.Thrown in the following situations: 1) Another FileReference or + FileReferenceList browse session is in progress; only one file browsing session may be performed + at a time. + 2) A setting in the user's mms.cfg file prohibits this operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThis error can occur if the application cannot allocate memory for the file. + The file may be too large or available memory may be too low. + + MemoryErrorflash.errors:MemoryErrorStarts the load of a local file. + + + Starts the load of a local file selected by a user. + Although Flash Player has no restriction on the size of files you can upload, + download, load or save, it officially supports sizes of up to 100 MB. For content running in Flash Player, + you must call the FileReference.browse() or FileReferenceList.browse() method before + you call the load() method. However, content running in AIR in the application sandbox can call + the load() method of a File object without first calling the browse() method. + (The AIR File class extends the FileReference class.) + +

Listeners receive events to indicate the progress, success, or + failure of the load. Although you can use the FileReferenceList object to let users + select multiple files to load, you must load the files one by one. To load the files + one by one, iterate through the FileReferenceList.fileList array of FileReference objects.

+ +

Adobe AIR also includes the FileStream class which provides more options for + reading files.

+ +

The FileReference.upload(), FileReference.download(), FileReference.load() + and FileReference.save() functions + are nonblocking. These functions return after they are called, before the file transmission + is complete. In addition, if the FileReference object goes out of scope, any transaction + that is not yet completed on that object is canceled upon leaving the scope. + Be sure that your FileReference object remains in scope for as long as the + upload, download, load or save is expected to continue.

+ +

If the file finishes loading successfully, its contents are stored as a byte array + in the data property of the FileReference object.

+ +

The following security considerations apply:

+ +
  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a + resource by adding a cross-domain policy file.
  • You can prevent a file from using this method by setting the allowNetworking + parameter of the the object and embed tags in the HTML + page that contains the SWF content.
+ +

However, these considerations do not apply to AIR content in the application sandbox.

+ +

Note that when publishing to Flash Player 10 or AIR 1.5, you can have only one of the following operations active at one time: + FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), + FileReference.save(). Otherwise, the application throws a runtime error (code 2174). Use FileReference.cancel() + to stop an operation in progress. This restriction applies only to Flash Player 10 and AIR 1.5. Previous versions of Flash Player + or AIR are unaffected by this restriction on simultaneous multiple operations.

+ + +

In Adobe AIR, the file-browsing dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +
The following example uploads an image from your local file system to the root display object (in this case, the stage). + Example provided by Andre Venancio. + + +var buttonShape:Shape = new Shape(); +buttonShape.graphics.beginFill(0x336699); +buttonShape.graphics.drawCircle(50, 50, 25); +var button = new SimpleButton(buttonShape, buttonShape, buttonShape, buttonShape); +addChild(button); + +var fileRef:FileReference= new FileReference(); +button.addEventListener(MouseEvent.CLICK, onButtonClick); + +function onButtonClick(e:MouseEvent):void { +fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]); +fileRef.addEventListener(Event.SELECT, onFileSelected); +} + +function onFileSelected(e:Event):void { +fileRef.addEventListener(Event.COMPLETE, onFileLoaded); +fileRef.load(); +} + +function onFileLoaded(e:Event):void { +var loader:Loader = new Loader(); +loader.loadBytes(e.target.data); +addChild(loader); +} +
FileReference.browse()FileReferenceList.browse()FileReference.dataFileReferenceList.fileListFileReference.save()FileStreamopenflash.events:EventDispatched when an load operation starts. + Dispatched when an load operation starts.progressflash.events:ProgressEventDispatched periodically during the file load operation. + Dispatched periodically during the file load operation.completeflash.events:EventDispatched when the file load operation completes successfully. + Dispatched when the file load operation completes successfully.ioErrorflash.events:IOErrorEventInvoked if the load fails because of an input/output error while the application + is reading or writing the file. + + Invoked if the load fails because of an input/output error while the application + is reading or writing the file.
save + Opens a dialog box that lets the user save a file to the local filesystem.Thrown in the following situations: 1) Another browse session is in + progress; only one file browsing session can be performed at a time. + 2) The filename to download contains prohibited characters. + 3) A setting in the user's mms.cfg file prohibits this operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf data is not of type ByteArray, and it does not + have a toString() method, an exception is thrown. If data is + not of type XML, and it does not have a toXMLString() method, an exception is thrown. + + ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse + event or keypress event. + + ErrorErrorThis error can occur if Flash Player cannot allocate memory for the file. + The file may be too large or available memory may be too low. + + MemoryErrorflash.errors:MemoryErrordataThe data to be saved. The data can be in one of several formats, and will be treated + appropriately: +
  • If the value is null, the application throws an ArgumentError exception.
  • If the value is a String, it is saved as a UTF-8 text file.
  • If the value is XML, it is written to a text file in XML format, with all formatting preserved.
  • If the value is a ByteArray object, it is written to a data file verbatim.
  • If the value is none of the above, the save() method calls the toString() method of the + object to convert the data to a string, and it then saves the data as a text file. If that fails, the application throws + an ArgumentError exception.
+ +
defaultFileNameStringnullThe default filename displayed in the dialog box for the file + to be saved. This string must not contain the following characters: + / \ : ~~ ? " < > | % +

+ If a File object calls this method, the filename will be that of the file the File object references. (The AIR File class + extends the FileReference class.)

+ +
+ Opens a dialog box that lets the user save a file to the local filesystem. + Although Flash Player has no restriction on + the size of files you can upload, download, load or save, + the player officially supports sizes of up to 100 MB. + +

The save() method first opens + an operating-system dialog box that asks the user to enter a filename and + select a location on the local computer + to save the file. When the user selects a location and confirms the save operation + (for example, by clicking Save), the save process begins. + Listeners receive events to indicate the progress, success, or + failure of the save operation. + To ascertain the status of the dialog box and the save operation after calling + save(), your code must listen for events + such as cancel, open, + progress, and complete. +

+ +

Adobe AIR also includes the FileStream class which provides more options for + saving files locally.

+ +

The FileReference.upload(), FileReference.download(), FileReference.load() + and FileReference.save() functions + are nonblocking. These functions return after they are called, before the file transmission + is complete. In addition, if the FileReference object goes out of scope, any transaction + that is not yet completed on that object is canceled upon leaving the scope. + Be sure that your FileReference object remains in scope for as long as the + upload, download, load or save is expected to continue.

+ +

When the file is saved successfully, the + properties of the FileReference object are populated with the properties + of the local file. The complete event is dispatched if the + save is successful.

+ +

Only one browse() or save() session can + be performed at a time (because only one dialog box can be invoked at a time).

+ +

In Flash Player, you can only call this method successfully in response to + a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling + this method results in Flash Player throwing an Error exception. This limitation does not apply to + AIR content in the application sandbox.

+ + +

In Adobe AIR, the save dialog is not always displayed in front of windows that are + "owned" by another window (windows that have a non-null owner property). + To avoid window ordering issues, hide owned windows before calling this method.

+ +
The following example saves the content typed into a text field to a file. + The example creates an editable text field (MyTextField) + and another text field that is not editable (MyButtonField)to serve as a "button" + to respond to a mouse click. A user can edit the first text field and click the button + to save the text field contents to a local file. The mouse click event handler clickhandler + uses the FileReference.save() method (for a FileReference object named MyFileReference) + to open a dialog on the user's current operating system so the user can save the contents to a local file with the + name the user provides. + +var MyTextField:TextField = new TextField(); +var MyButtonField:TextField = new TextField(); +var MyFile:FileReference = new FileReference(); + +MyTextField.border = true; +MyTextField.type = TextFieldType.INPUT; + +MyButtonField.background = true; +MyButtonField.backgroundColor = 0x339933; +MyButtonField.x = 150; +MyButtonField.height = 20; +MyButtonField.text = "Click here to save"; + +addChild(MyTextField); +addChild(MyButtonField); +MyButtonField.addEventListener(MouseEvent.CLICK, clickhandler); + +function clickhandler(e:MouseEvent): void { + MyFile.save(MyTextField.text); +} +
FileReferenceList.browse()FileReference.load()FileReference.dataFileReference.upload()FileReference.download()FileStreamopenflash.events:EventDispatched when a download operation starts. + Dispatched when a download operation starts.progressflash.events:ProgressEventDispatched periodically during the file download operation. + Dispatched periodically during the file download operation.completeflash.events:EventDispatched when the file download operation successfully completes. + Dispatched when the file download operation successfully completes.cancelflash.events:EventDispatched when the user dismisses the dialog box. + Dispatched when the user dismisses the dialog box.selectflash.events:EventDispatched when the user selects a file for download from the dialog box. + Dispatched when the user selects a file for download from the dialog box.ioErrorflash.events:IOErrorEventDispatched if an input/output error occurs while the file is being read or transmitted. + + Dispatched if an input/output error occurs while the file is being read or transmitted.
uploadUnencoded + Initiate uploading a file to a URL without any encoding.Local untrusted SWF files may not communicate with + the Internet. To avoid this situation, reclassify this SWF file + as local-with-networking or trusted. This exception is thrown with a message indicating the name of + the local file and the URL that may not be accessed. + + SecurityErrorSecurityErrorThrown in the following situations: 1) Another FileReference or FileReferenceList + browse session is in progress; only one file browsing session may be performed at a time. 2) The URL parameter + is not a valid path or protocol. File upload must use HTTP. + + IllegalOperationErrorflash.errors:IllegalOperationErrorrequestflash.net:URLRequestThe URLRequest object; the url property of the URLRequest object + should contain the URL of the server script + configured to handle upload through HTTP POST calls. + On some browsers, URL strings are limited in length. + Lengths greater than 256 characters may fail on some browsers or servers. + If this parameter is null, an exception is thrown. + +

The URL can be HTTP or, for secure uploads, HTTPS. + To use HTTPS, use an HTTPS url in the url parameter. + If you do not specify a port number in the url + parameter, port 80 is used for HTTP and port 443 us used for HTTPS, by default.

+ +

To send POST or GET parameters to the server, set the data property + of the URLRequest object to your parameters, and set the method property + to either URLRequestMethod.POST or + URLRequestMethod.GET.

+ +
Starts the upload of a file to a remote server without encoding. + +
+ Initiate uploading a file to a URL without any encoding. Whereas the upload() method encodes + the file in a form-data envelope, the uploadUnencoded() method passes the file contents as-is + in the HTTP request body. Use the uploadUnencoded() method if the data you wish to send is already encoded + in a format that the receiving server can understand.You typically use the uploadeUnencoded() + method with the HTTP/WebDAV PUT method. + +
FileReference.browse()FileReferenceList.browse()FileReference.download()FileReferenceList.fileListupload()openflash.events:EventDispatched when an upload operation starts. + + Dispatched when an upload operation starts.progressflash.events:ProgressEventDispatched periodically during the file upload operation. + + Dispatched periodically during the file upload operation.completeflash.events:EventDispatched when the file upload operation completes successfully. + + Dispatched when the file upload operation completes successfully.uploadCompleteDataflash.events:DataEventDispatched when data has been received from the server after a + successful file upload. + + Dispatched when data has been received from the server after a + successful file upload.securityErrorflash.events:SecurityErrorEventDispatched when an upload fails because of a + security violation. + + Dispatched when an upload fails because of a + security violation.httpStatusflash.events:HTTPStatusEventDispatched when an upload fails because of an HTTP error. + + Dispatched when an upload fails because of an HTTP error.httpResponseStatusflash.events:HTTPStatusEventThe upload operation completes successfully and the server + returns a response URL and response headers. + + The upload operation completes successfully and the server + returns a response URL and response headers.ioErrorflash.events:IOErrorEventInvoked in any of the following situations: +
  • The upload fails because of an input/output error while Adobe AIR is reading, + writing, or transmitting the file.
  • The upload fails because an attempt to upload a file to a server that requires + authentication (such as a user name and password). During upload, no mean is provided + for users to enter passwords.
  • The upload fails because the url parameter contains an invalid protocol. + FileReference.upload() must use HTTP or HTTPS.
+ +
Invoked in any of the following situations: + + The upload fails because of an input/output error while Adobe AIR is reading, + writing, or transmitting the file. + The upload fails because an attempt to upload a file to a server that requires + authentication (such as a user name and password).
upload + Starts the upload of the file to a remote server.Local untrusted SWF files may not communicate with + the Internet. To avoid this situation, reclassify this SWF file + as local-with-networking or trusted. This exception is thrown with a message indicating the name of + the local file and the URL that may not be accessed. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorThrown in the following situations: 1) Another FileReference or + FileReferenceList browse session is in progress; only one file browsing session may be performed + at a time. + 2) The URL parameter is not a valid path or protocol. File upload must use HTTP, + and file download must use FTP or HTTP. + 3) The uploadDataFieldName parameter is set to null. + 4) A setting in the user's mms.cfg file prohibits this operation. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThrown in the following situations: 1) The uploadDataFieldName + parameter is an empty string. 2) url.data is of type ByteArray. + For use with the FileReference.upload() and + FileReference.download() methods, url.data may only be of type + URLVariables or String. 3) In the AIR runtime (in the application security sandbox), the method of the + URLRequest is not GET or POST (use uploadEncoded() instead). + + ArgumentErrorArgumentErrorThis error can occur for the following reasons: + 1) Flash Player cannot convert the URLRequest.data + parameter from UTF8 to MBCS. This error is applicable if the URLRequest object + passed to FileReference.upload() is set to perform a GET operation and if + System.useCodePage is set to true. + 2) Flash Player cannot allocate memory for the POST data. This error is + applicable if the URLRequest object passed to FileReference.upload() is set + to perform a POST operation. + + MemoryErrorflash.errors:MemoryErrorrequestflash.net:URLRequestThe URLRequest object; the url property of the URLRequest object + should contain the URL of the server script + configured to handle upload through HTTP POST calls. + On some browsers, URL strings are limited in length. + Lengths greater than 256 characters may fail on some browsers or servers. + If this parameter is null, an exception is thrown. The requestHeaders property + of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads. + +

The URL can be HTTP or, for secure uploads, HTTPS. + To use HTTPS, use an HTTPS url in the url parameter. + If you do not specify a port number in the url + parameter, port 80 is used for HTTP and port 443 us used for HTTPS, by default.

+ +

To send POST or GET parameters to the server, set the data property + of the URLRequest object to your parameters, and set the method property + to either URLRequestMethod.POST or + URLRequestMethod.GET.

+ + +
uploadDataFieldNameStringFiledataThe field name that precedes the file data in the upload POST operation. + The uploadDataFieldName value must be non-null and a non-empty String. + By default, the value of uploadDataFieldName is "Filedata", + as shown in the following sample POST request: +
+    Content-Type: multipart/form-data; boundary=AaB03x
+    --AaB03x 
+    Content-Disposition: form-data; name="Filedata"; filename="example.jpg" 
+    Content-Type: application/octet-stream
+    ... contents of example.jpg ... 
+    --AaB03x-- 
+    
+ +
testUploadBooleanfalseA setting to request a test file upload. If testUpload + is true, for files larger than 10 KB, Flash Player attempts + a test file upload POST with a Content-Length of 0. The test upload + checks whether the actual file upload will be successful and that server + authentication, if required, will succeed. A test upload + is only available for Windows players. + + + Starts the upload of a file to a remote server. + +
+ Starts the upload of the file to a remote server. Although + Flash Player has no restriction on the size of files you can upload or download, + the player officially supports uploads or downloads of up to 100 MB. + You must call the FileReference.browse() or FileReferenceList.browse() + method before you call this method. + +

For the Adobe AIR File class, which extends the FileReference class, you can use the upload() + method to upload any file. For the FileReference class (used in Flash Player), the user must first + select a file.

+ +

Listeners receive events to indicate the progress, success, or + failure of the upload. Although you can use the FileReferenceList object to let users + select multiple files for upload, you must upload the files one by one; to do so, iterate through + the FileReferenceList.fileList array of FileReference objects.

+ +

The FileReference.upload() and FileReference.download() functions + are nonblocking. These functions return after they are called, before the file transmission + is complete. In addition, if the FileReference object goes out of scope, any upload or download + that is not yet completed on that object is canceled upon leaving the scope. + Be sure that your FileReference object remains in scope for as long as the + upload or download is expected to continue.

+ +

The file is uploaded to the URL passed in the url parameter. The URL + must be a server script configured to accept uploads. Flash Player uploads files by using + the HTTP POST method. The server script that handles the upload + should expect a POST request with the following elements:

+
  • Content-Type of multipart/form-data
  • Content-Disposition with a name attribute set to "Filedata" by default + and a filename attribute set to the name of the original file
  • The binary contents of the file
+ +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

For a sample POST request, see the description of the uploadDataFieldName + parameter. You can send POST or GET parameters to the server with the upload() + method; see the description of the request parameter.

+ +

If the testUpload parameter is true, + and the file to be uploaded is bigger than approximately 10 KB, Flash Player on Windows + first sends a test upload POST operation with zero content before uploading the actual file, + to verify that the transmission is likely to succeed. Flash Player then sends + a second POST operation that contains the actual file content. + For files smaller than 10 KB, Flash Player performs a single + upload POST with the actual file content to be uploaded. + Flash Player on Macintosh does not perform test upload POST operations.

+ +

Note: If your server requires user authentication, only + SWF files running in a browser — that is, using the browser plug-in or ActiveX control — + can provide a dialog box to prompt the user for a username and password for authentication, + and only for downloads. For uploads using the plug-in or ActiveX control, or for + uploads and downloads using the stand-alone or external player, the file transfer fails.

+ +

When you use this method , consider the Flash Player + security model:

+ + +
  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a + resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking + parameter of the the object and embed tags in the HTML + page that contains the SWF content.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have + only one of the following operations active at one time: FileReference.browse(), + FileReference.upload(), FileReference.download(), FileReference.load(), + FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() + to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player + are unaffected by this restriction on simultaneous multiple operations.

+ +
FileReference.browse()FileReferenceList.browse()FileReference.download()FileReferenceList.fileListFileReference.load()openflash.events:EventDispatched when an upload operation starts. + + Dispatched when an upload operation starts.progressflash.events:ProgressEventDispatched periodically during the file upload operation. + + Dispatched periodically during the file upload operation.completeflash.events:EventDispatched when the file upload operation completes successfully. + + Dispatched when the file upload operation completes successfully.uploadCompleteDataflash.events:DataEventDispatched when data has been received from the server after a successful file upload. + + Dispatched when data has been received from the server after a successful file upload.securityErrorflash.events:SecurityErrorEventDispatched when an upload fails because of a + security violation. + + Dispatched when an upload fails because of a + security violation.httpStatusflash.events:HTTPStatusEventDispatched when an upload fails because of an HTTP error. + + Dispatched when an upload fails because of an HTTP error.httpResponseStatusflash.events:HTTPStatusEventThe upload operation completes successfully and the server + returns a response URL and response headers. + + The upload operation completes successfully and the server + returns a response URL and response headers.ioErrorflash.events:IOErrorEventInvoked in any of the following situations: +
  • The upload fails because of an input/output error while Flash + Player or Adobe AIR is reading, writing, or transmitting the file.
  • The upload fails because an attempt to upload a file to a server that requires + authentication (such as a user name and password). During upload, no mean is provided + for users to enter passwords.
  • The upload fails because the url parameter contains an invalid protocol. + FileReference.upload() must use HTTP or HTTPS.
+ +
Invoked in any of the following situations: + + The upload fails because of an input/output error while Flash + Player or Adobe AIR is reading, writing, or transmitting the file. + The upload fails because an attempt to upload a file to a server that requires + authentication (such as a user name and password).
creationDate + The creation date of the file on the local disk.DateIf the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. + In this case, the value of the creationDate property is null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file information cannot be accessed, an exception is thrown with a message + indicating a file I/O error. + + IOErrorflash.errors:IOErrorGets the creation date of the file as a Date object. + + + The creation date of the file on the local disk. If the object is + was not populated, a call to get the value of this property returns null. + + FileReference.browse()creator + The Macintosh creator type of the file, which is only used in Mac OS versions + prior to Mac OS X.StringOn Macintosh, if the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. In this case, the value of the creator property + is null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe Macintosh creator type. + + The Macintosh creator type of the file, which is only used in Mac OS versions + prior to Mac OS X. In Windows or Linux, this property is null. + If the FileReference object + was not populated, a call to get the value of this property returns null. + + FileReference.browse()FileReference.extensiondata + The ByteArray object representing the data from the loaded file after a successful call to the load() method.flash.utils:ByteArrayIf the load() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. In this case, the value of the data property + is null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file cannot be opened or read, or if a similar error is encountered in + accessing the file, an exception is thrown with a message indicating a file I/O error. In this case, the value + of the data property is null. + + IOErrorflash.errors:IOErrorThe loaded data of the file, as a ByteArray. + + The ByteArray object representing the data from the loaded file after a successful call to the load() method. + + FileReference.browse()FileReference.load()extension + The filename extension.StringIf the reference is not initialized. + + IllegalOperationErrorflash.errors:IllegalOperationError + The filename extension. + +

A file's extension is the part of the name following (and not including) the final dot ("."). + If there is no dot in the filename, the extension is null.

+ +

Note: You should use the extension property to determine a file's type; do not use the + creator or type properties. You should consider the creator and type + properties to be considered deprecated. They apply to older versions of Mac OS.

+ +
modificationDate + The date that the file on the local disk was last modified.DateIf the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. In this case, + the value of the modificationDate property is null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file information cannot be accessed, an exception is thrown with a message + indicating a file I/O error. + + IOErrorflash.errors:IOErrorGets the modification date of the file as a Date object. + + The date that the file on the local disk was last modified. If the FileReference + object was not populated, a call to get the value of this property returns null. + + FileReference.browse()name + The name of the file on the local disk.StringIf the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. + + IllegalOperationErrorflash.errors:IllegalOperationErrorGets the name of the file as a String. + + The name of the file on the local disk. If the FileReference object + was not populated (by a valid call to FileReference.download() or + FileReference.browse()), Flash Player throws an error when you try to get the + value of this property. +

All the properties of a FileReference object are populated by calling the browse() method. + Unlike other FileReference properties, if you call the download() method, + the name property is populated when the select event is dispatched.

+ +
FileReference.browse()
size + The size of the file on the local disk in bytes.NumberIf the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. + + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the file cannot be opened or read, or if a similar error is encountered in + accessing the file, an exception is thrown with a message indicating a file I/O error. + + IOErrorflash.errors:IOErrorThe size of the file in bytes. + + The size of the file on the local disk in bytes. If size is 0, + an exception is thrown. + +

Note: In the initial version of ActionScript 3.0, the size property was + defined as a uint object, which supported files with sizes up to about 4 GB. It is now implemented as a Number + object to support larger files.

+ +
FileReference.browse()
type + The file type.StringIf the FileReference.browse(), + FileReferenceList.browse(), or FileReference.download() method was not called + successfully, an exception is thrown with a message indicating that functions were called in the + incorrect sequence or an earlier call was unsuccessful. In this case, the value of the type property + is null. + + IllegalOperationErrorflash.errors:IllegalOperationErrorGets the type or extension of the file. + + The file type. + +

In Windows or Linux, this property is the file extension. On the Macintosh, this property is + the four-character file type, which is only used in Mac OS versions prior to Mac OS X. If the FileReference object + was not populated, a call to get the value of this property returns null.

+ +

For Windows, Linux, and Mac OS X, the file extension — the portion of the name property that + follows the last occurrence of the dot (.) character — identifies the file type.

+ +
FileReference.extension
FileReferenceList + The FileReferenceList class provides a means to let users select one or more files for uploading.Provides a means to upload one or more files. + + flash.events:EventDispatcher + The FileReferenceList class provides a means to let users select one or more files for uploading. + A FileReferenceList object represents a group of one or more local files on the user's disk as + an array of FileReference objects. For detailed information and important considerations about + FileReference objects and the FileReference class, which you use with FileReferenceList, + see the FileReference class. + +

To work with the FileReferenceList class:

+
  • Instantiate the class: var myFileRef = new FileReferenceList();
  • Call the FileReferenceList.browse() method, which opens a dialog box that + lets the user select one or more files for upload: myFileRef.browse();
  • After the browse() method is called successfully, the fileList property of + the FileReferenceList object is populated with an array of FileReference objects.
  • Call FileReference.upload() on each element in the + fileList array.
+ +

The FileReferenceList class includes a browse() method and a + fileList property for working with multiple files. While a call to FileReferenceList.browse() + is executing, SWF file playback pauses in stand-alone and external versions of Flash Player + and in AIR for Linux and Mac OS X 10.1 and earlier.

+ +
The following example shows how you can use events to manage the upload of multiple files. + The CustomFileReferenceList class extends FileReferenceList and includes a complete event, + which is dispatched + when each individual file in the FileReferenceList object is uploaded. The LIST_COMPLETE + event in the FileReferenceListExample class is dispatched when all the files in the FileReferenceList + object have been uploaded. + +

To run this example, place a script that is written to accept + a file upload at http://www.[yourDomain].com/yourUploadHandlerScript.cfm. + Based on the location of your SWF file and where you are uploading files to, you + also might need to compile the SWF file with Local Playback Security set to Access Network Only + or update Flash® Player security settings to allow this file network access. + If your upload server is remote and you run this example from your desktop computer, + your server must have a crossdomain.xml file.

+ + + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.FileReference; + import flash.net.FileReferenceList; + + public class FileReferenceListExample extends Sprite { + public static var LIST_COMPLETE:String = "listComplete"; + public function FileReferenceListExample() { + initiateFileUpload(); + } + + private function initiateFileUpload():void { + var fileRef:CustomFileReferenceList = new CustomFileReferenceList(); + fileRef.addEventListener(FileReferenceListExample.LIST_COMPLETE, listCompleteHandler); + fileRef.browse(fileRef.getTypes()); + } + + private function listCompleteHandler(event:Event):void { + trace("listCompleteHandler"); + } + } +} + +import flash.events.*; +import flash.net.FileReference; +import flash.net.FileReferenceList; +import flash.net.FileFilter; +import flash.net.URLRequest; + +class CustomFileReferenceList extends FileReferenceList { + private var uploadURL:URLRequest; + private var pendingFiles:Array; + + public function CustomFileReferenceList() { + uploadURL = new URLRequest(); + uploadURL.url = "http://www.[yourDomain].com/yourUploadHandlerScript.cfm"; + initializeListListeners(); + } + + private function initializeListListeners():void { + addEventListener(Event.SELECT, selectHandler); + addEventListener(Event.CANCEL, cancelHandler); + } + + public function getTypes():Array { + var allTypes:Array = new Array(); + allTypes.push(getImageTypeFilter()); + allTypes.push(getTextTypeFilter()); + return allTypes; + } + + private function getImageTypeFilter():FileFilter { + return new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"); + } + + private function getTextTypeFilter():FileFilter { + return new FileFilter("Text Files (*.txt, *.rtf)", "*.txt;*.rtf"); + } + + private function doOnComplete():void { + var event:Event = new Event(FileReferenceListExample.LIST_COMPLETE); + dispatchEvent(event); + } + + private function addPendingFile(file:FileReference):void { + trace("addPendingFile: name=" + file.name); + pendingFiles.push(file); + file.addEventListener(Event.OPEN, openHandler); + file.addEventListener(Event.COMPLETE, completeHandler); + file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + file.addEventListener(ProgressEvent.PROGRESS, progressHandler); + file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + file.upload(uploadURL); + } + + private function removePendingFile(file:FileReference):void { + for (var i:uint; i < pendingFiles.length; i++) { + if (pendingFiles[i].name == file.name) { + pendingFiles.splice(i, 1); + if (pendingFiles.length == 0) { + doOnComplete(); + } + return; + } + } + } + + private function selectHandler(event:Event):void { + trace("selectHandler: " + fileList.length + " files"); + pendingFiles = new Array(); + var file:FileReference; + for (var i:uint = 0; i < fileList.length; i++) { + file = FileReference(fileList[i]); + addPendingFile(file); + } + } + + private function cancelHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("cancelHandler: name=" + file.name); + } + + private function openHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("openHandler: name=" + file.name); + } + + private function progressHandler(event:ProgressEvent):void { + var file:FileReference = FileReference(event.target); + trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal); + } + + private function completeHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("completeHandler: name=" + file.name); + removePendingFile(file); + } + + private function httpErrorHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("httpErrorHandler: name=" + file.name); + } + + private function ioErrorHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("ioErrorHandler: name=" + file.name); + } + + private function securityErrorHandler(event:Event):void { + var file:FileReference = FileReference(event.target); + trace("securityErrorHandler: name=" + file.name + " event=" + event.toString()); + } +} +
FileReferenceselect + Dispatched when the user selects one or more files to upload from the file-browsing dialog box.flash.events.Event.SELECTflash.events.Event + Dispatched when the user selects one or more files to upload from the file-browsing dialog box. + (This dialog box opens + when you call the FileReferenceList.browse(), + FileReference.browse(), or FileReference.download() methods.) + + When the user selects a file and confirms the operation (for example, by clicking Save), + the FileReferenceList object is populated with FileReference objects + that represent the files that the user selects. + + FileReferenceList.browse()cancel + Dispatched when the user dismisses the file-browsing dialog box.flash.events.Event.CANCELflash.events.Event + Dispatched when the user dismisses the file-browsing dialog box. + (This dialog box opens + when you call the FileReferenceList.browse(), + FileReference.browse(), or FileReference.download() methods.) + + FileReferenceList.browse()FileReferenceList + Creates a new FileReferenceList object. + Creates a new FileReferenceList object. A FileReferenceList object contains nothing + until you call the browse() method on it and the user selects one or more files. + When you call browse() on the + FileReference object, the fileList property of the object is populated + with an array of FileReference objects. + + FileReferenceFileReferenceList.browse()browse + Displays a file-browsing dialog box that lets the + user select one or more local files to upload.Thrown for the following reasons: 1) Another FileReference + or FileReferenceList browse session is in progress; only one file browsing session + may be performed at a time. 2) A setting in the user's mms.cfg file prohibits this operation. + IllegalOperationErrorflash.errors:IllegalOperationErrorIf the typeFilter array does not contain correctly formatted + FileFilter objects, an exception is thrown. For details on correct filter formatting, + see the FileFilter documentation. + + ArgumentErrorArgumentErrorIf the method is not called in response to a user action, such as a mouse + event or keypress event. + + ErrorErrorReturns true if the parameters are valid and the file-browsing dialog box + opens. + + BooleantypeFilterArraynullAn array of FileFilter instances used to filter the files that are + displayed in the dialog box. If you omit this parameter, all files are displayed. + For more information, see the FileFilter class. + + Displays a file-browsing dialog box that lets the + user select local files to upload. + + + Displays a file-browsing dialog box that lets the + user select one or more local files to upload. The dialog box is native to the user's + operating system. + +

In Flash Player 10 and later, you can call this method successfully + only in response to a user event (for example, in an event handler for a mouse click or keypress event). + Otherwise, calling this method results in Flash Player throwing an Error.

+ +

When you call this method and the user successfully selects files, + the fileList property of this FileReferenceList object is populated with + an array of FileReference objects, one for each file that the user selects. + Each subsequent time that the FileReferenceList.browse() method is called, the + FileReferenceList.fileList property is reset to the file(s) that the + user selects in the dialog box.

+ +

Using the typeFilter parameter, you can determine which files + the dialog box displays.

+ +

Only one FileReference.browse(), FileReference.download(), + or FileReferenceList.browse() session can be performed at a time + on a FileReferenceList object + (because only one dialog box can be opened at a time).

+ +
FileReference.browse()FileReference classFileFilter classselectflash.events:EventInvoked when the user has successfully selected an item for upload from the dialog box. + Invoked when the user has successfully selected an item for upload from the dialog box.cancelflash.events:EventInvoked when the user dismisses the dialog box by clicking Cancel or by closing it. + + Invoked when the user dismisses the dialog box by clicking Cancel or by closing it.
fileList + An array of FileReference objects.ArrayAn array of FileReference objects. + + + An array of FileReference objects. + +

When the FileReferenceList.browse() method is called and the user + has selected one or more files from the dialog box that the browse() method opens, + this property is populated with an array of FileReference objects, + each of which represents the files the user selected. + You can then use this array to upload each file with the FileReference.upload()method. + You must upload one file at a time.

+ +

The fileList property is populated anew each time browse() is called on + that FileReferenceList object.

+ +

The properties of FileReference objects are described + in the FileReference class documentation.

+ +
FileReferenceFileReference.upload()FileReferenceList.browse()
NetworkInterface + The NetworkInterface class describes a network interface.Object + The NetworkInterface class describes a network interface. + +

You can get a list of network interfaces by calling the + findInterfaces() method of a NetworkInfo object.

+ +
NetworkInfoInterfaceAddressactive + Reports whether this interface is active.Boolean + Reports whether this interface is active. + + addresses + The list of the addresses bound to this network interface. + The list of the addresses bound to this network interface. + + displayName + The display name of this network interface.String + The display name of this network interface. + + hardwareAddress + The hardware address of this network interface.String + The hardware address of this network interface. + +

The hardware address is typically the Media Access Control (MAC) address + of the network adapter or interface card.

+ +
mtu + The maximum transmission unit (MTU) of this network interface.int + The maximum transmission unit (MTU) of this network interface. + +

If the mtu value is reported as -1, then the actual MTU is unknown.

+ +
name + The name of this network interface.String + The name of this network interface. + + parent + The NetworkInterface object representing the parent interface (if this interface has a parent).flash.net:NetworkInterface + The NetworkInterface object representing the parent interface (if this interface has a parent). + +

This interface could have a parent if it is a subinterface. The parent + property is null if this interface has no parent.

+ +
subInterfaces + The list of subinterfaces attached to this network interface. + The list of subinterfaces attached to this network interface. + +

Subinterfaces are often virtual interfaces. The subInterfaces + property is null if this interface has no subinterfaces.

+
SharedObjectFlushStatus + The SharedObjectFlushStatus class provides values for the code returned from a call to the SharedObject.flush() method.Object + The SharedObjectFlushStatus class provides values for the code returned from a call to the SharedObject.flush() method. + + SharedObject.flush()FLUSHED + Indicates that the flush completed successfully.flushedString + Indicates that the flush completed successfully. + SharedObject.flush()PENDING + Indicates that the user is being prompted to increase disk space for the shared object + before the flush can occur.pendingString + Indicates that the user is being prompted to increase disk space for the shared object + before the flush can occur. + SharedObject.flush()SecureSocket + The SecureSocket class enables code to make socket connections utilizing the Secure Sockets Layer (SSL) + and Transport Layer Security (TLS) protocols.flash.net:Socket + The SecureSocket class enables code to make socket connections utilizing the Secure Sockets Layer (SSL) + and Transport Layer Security (TLS) protocols. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on all AIR for TV devices. + It is not supported on mobile devices. You can test + for support at run time using the SecureSocket.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

The SSL/TLS protocols provide a mechanism by which the + identity of a host can be authenticated via its certificate, and provides for encrypted communication + over the socket. SSLv3 and TLSv1 are supported. Validation of the server certificate is performed using + the trust store and certificate validation support of the client platform.

+ +

The SecureSocket class will only connect to servers with valid, trusted certificates. You cannot choose + to connect to a server in spite of a problem with it's certificate. For example, there is no way to connect + to a server with an expired certificate or a certificate that doesn't chain to a trusted root certificate + even though the certificate would be valid otherwise.

+ +

The SecureSocket class is useful for performing encrypted communication to a trusted server. In other respects + a SecureSocket object behaves like a regular Socket object.

+ +

To use the methods of the SecureSocket class, first use the constructor, new SecureSocket(), + to create a SecureSocket object. When you connect to a server, the server certificate is validated. If the + certificate is valid and trusted, the connection is established and the Socket dispatches a + connect event. If the certificate cannot be validated, the Socket dispatches an + IOError event.

+ +

Important: The Online Certificate Status Protocol (OCSP) is not supported by all operating systems. + Users can also disable OCSP checking on individual computers. If OCSP is not supported or is disabled and + a certificate does not contain the information necessary to check revocation using a Certificate Revocation + List (CRL), then certificate revocation is not checked. The certificate is accepted if otherwise valid. + This could allow a server to use a revoked certificate.

+ +
The following example illustrates how to create and connect a + SecureSocket object. +package +{ + import flash.display.Sprite; + import flash.errors.IOError; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.net.SecureSocket; + + public class SecureSocketExample extends Sprite + { + private var secureSocket:SecureSocket = new SecureSocket(); + + public function SecureSocketExample() + { + secureSocket.addEventListener( Event.CONNECT, onConnect ) + secureSocket.addEventListener( IOErrorEvent.IO_ERROR, onError ); + + try + { + secureSocket.connect( "208.77.188.166", 443 ); + } + catch ( error:Error ) + { + trace ( error.toString() ); + } + } + + private function onConnect( event:Event ):void + { + trace("Connected."); + } + + private function onError( error:IOErrorEvent ):void + { + trace( error.text + ", " + secureSocket.serverCertificateStatus ); + } + } +} +
Socket classsocketData + Dispatched when a socket has received data.flash.events.ProgressEvent.SOCKET_DATAflash.events.ProgressEvent + Dispatched when a socket has received data. + + Events of type socketData do not use the ProgressEvent.bytesTotal + property. + + ioError + Dispatched when an input or output error occurs that causes a send or receive operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input or output error occurs that causes a send or receive operation to fail. + +

When a server certificate cannot be validated, the error event dispatched is an IOError. In this case, + you can check the serverCertificateStatus property to determine the cause of the problem.

+ +
connect + Dispatched when a network connection has been established.flash.events.Event.CONNECTflash.events.Event + Dispatched when a network connection has been established. + + close + Dispatched when the server closes the socket connection.flash.events.Event.CLOSEflash.events.Event + Dispatched when the server closes the socket connection. + +

The close event is dispatched only when the server + closes the connection; it is not dispatched when you call the SecureSocket.close() method.

+ +
SecureSocket + Creates a new SecureSocket object.This error occurs when SSLv3 or TLSv1 support is not available. + + IllegalOperationErrorflash.errors:IllegalOperationError + Creates a new SecureSocket object. + +

Check SecureSocket.isSupported before attempting to create a SecureSocket + instance. If SSLv3 or TLSv1 sockets are not supported, the runtime will throw an IllegalOperationError.

+ +
connect + Connects the socket to the specified host and port using SSL or TLS.No host was specified and the connection failed. + + IOErrorflash.errors:IOErrorThis error occurs if you specify a socket port less than + zero or higher than 65535. + + SecurityErrorSecurityErrorhostStringThe name or IP address of the host to connect to. + + portintThe port number to connect to. + + + Connects the socket to the specified host and port using SSL or TLS. + +

When you call the connect() method, the server certificate is validated. If the + SSL/TLS handshake succeeds and the certificate is valid and trusted, the connection is established, + the socket dispatches a connect event. If the handshake fails or the certificate cannot + be validated, the socket dispatches an IOError event. You can check the certificate + validation result by reading the serverCertificateStatus property after one of these + events has been dispatched. (When a connect event is dispatched, the certificate + status is always trusted.)

+ +

If the socket is already connected, the existing connection is closed first.

+ +
connectflash.events:EventDispatched when a network connection has been + established. + Dispatched when a network connection has been + established.ioErrorflash.events:IOErrorEventDispatched if a host is specified and an + input/output error occurs that causes the connection to fail. + This includes SSL/TLS handshake errors and failure to + successfully validate the host's server certificate. + + Dispatched if a host is specified and an + input/output error occurs that causes the connection to fail.
isSupported + Indicates whether the secure sockets are supported on the current system.Boolean + Indicates whether the secure sockets are supported on the current system. + +

Secure sockets are not supported on all platforms. Check this property + before attempting to create a new SecureSocket instance.

+ +
serverCertificateStatus + The status of the server's certificate.String + The status of the server's certificate. + +

The status is CertificateStatus.UNKNOWN until the + socket attempts to connect to a server. After validation, the status will be one + of the strings enumerated by the CertificateStatus class. The connection only + succeeds when the certificate is valid and trusted. Thus, after a + connect event, the status is always trusted.

+ +

Note: Once the certificate has been validated or rejected, the status + value is not updated until the next call to the connect() method. + Calling close() does not reset the status value to "unknown".

+ +
CertificateStatus class
ServerSocket + The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) + connections.flash.events:EventDispatcher + The ServerSocket class allows code to act as a server for Transport Control Protocol (TCP) + connections. + +

AIR profile support: This feature is supported + on all desktop operating systems, but is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the ServerSocket.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

A TCP server listens for incoming connections from remote clients. When a client attempts to + connect, the ServerSocket dispatches a connect event. The ServerSocketConnectEvent object + dispatched for the event provides a Socket object representing the TCP connection between + the server and the client. Use this Socket object for subsequent communication + with the connected client. You can get the client address and port from the Socket object, if needed.

+ +

Note: Your application is responsible for maintaining a reference to + the client Socket object. If you don't, the object is eligible for garbage collection and may be + destroyed by the runtime without warning.

+ +

To put a ServerSocket object into the listening state, call the listen() method. + In the listening state, the server socket object dispatches connect events + whenever a client using the TCP protocol attempts to connect to the bound address and port. The ServerSocket object + continues to listen for additional connections until you call the close() method.

+ +

TCP connections are persistent — they exist until one side of the connection closes it (or a serious + network failure occurs). Any data sent over the connection is broken into transmittable packets and reassembled + on the other end. All packets are guaranteed to arrive (within reason) — any lost packets are retransmitted. + In general, the TCP protocol manages the available network bandwidth better than the UDP protocol. + Most AIR applications that require socket communications should use the ServerSocket and Socket + classes rather than the DatagramSocket class.

+ +

The ServerSocket class can only be used in Adobe AIR + applications and only in the application security sandbox.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
The following example creates a socket server. To use the server, bind the + socket to a local port and then connect to that port from another application. The server + only understands UTF-8 strings. + +package +{ + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.events.ProgressEvent; + import flash.events.ServerSocketConnectEvent; + import flash.net.ServerSocket; + import flash.net.Socket; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.utils.ByteArray; + + public class ServerSocketExample extends Sprite + { + private var serverSocket:ServerSocket = new ServerSocket(); + private var clientSocket:Socket; + + private var localIP:TextField; + private var localPort:TextField; + private var logField:TextField; + private var message:TextField; + + public function ServerSocketExample() + { + setupUI(); + } + + private function onConnect( event:ServerSocketConnectEvent ):void + { + clientSocket = event.socket; + clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData ); + log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); + } + + private function onClientSocketData( event:ProgressEvent ):void + { + var buffer:ByteArray = new ByteArray(); + clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable ); + log( "Received: " + buffer.toString() ); + } + + private function bind( event:Event ):void + { + if( serverSocket.bound ) + { + serverSocket.close(); + serverSocket = new ServerSocket(); + + } + serverSocket.bind( parseInt( localPort.text ), localIP.text ); + serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect ); + serverSocket.listen(); + log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort ); + } + + private function send( event:Event ):void + { + try + { + if( clientSocket != null && clientSocket.connected ) + { + clientSocket.writeUTFBytes( message.text ); + clientSocket.flush(); + log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); + } + else log("No socket connection."); + } + catch ( error:Error ) + { + log( error.message ); + } + } + + private function log( text:String ):void + { + logField.appendText( text + "\n" ); + logField.scrollV = logField.maxScrollV; + trace( text ); + } + + private function setupUI():void + { + localIP = createTextField( 10, 10, "Local IP", "0.0.0.0"); + localPort = createTextField( 10, 35, "Local port", "0" ); + createTextButton( 170, 60, "Bind", bind ); + message = createTextField( 10, 85, "Message", "Lucy can't drink milk." ); + createTextButton( 170, 110, "Send", send ); + logField = createTextField( 10, 135, "Log", "", false, 200 ) + + this.stage.nativeWindow.activate(); + } + + private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField + { + var labelField:TextField = new TextField(); + labelField.text = label; + labelField.type = TextFieldType.DYNAMIC; + labelField.width = 100; + labelField.x = x; + labelField.y = y; + + var input:TextField = new TextField(); + input.text = defaultValue; + input.type = TextFieldType.INPUT; + input.border = editable; + input.selectable = editable; + input.width = 280; + input.height = height; + input.x = x + labelField.width; + input.y = y; + + this.addChild( labelField ); + this.addChild( input ); + + return input; + } + + private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField + { + var button:TextField = new TextField(); + button.htmlText = "<u><b>" + label + "</b></u>"; + button.type = TextFieldType.DYNAMIC; + button.selectable = false; + button.width = 180; + button.x = x; + button.y = y; + button.addEventListener( MouseEvent.CLICK, clickHandler ); + + this.addChild( button ); + return button; + } + } +} +
ServerSocketConnectEvent classSocket classXMLSocket classDatagramSocket classconnect + Dispatched when a remote socket seeks to connect to this server socket.flash.events.ServerSocketConnectEvent.CONNECTflash.events.ServerSocketConnectEvent + Dispatched when a remote socket seeks to connect to this server socket. + + close + Dispatched when the operating system closes this socket.flash.events.Event.CLOSEflash.events.Event + Dispatched when the operating system closes this socket. + +

The close event is not dispatched when the ServerSocket close() + method is called. If other objects in your application rely on the close event, + you can dispatch the event manually before calling the close() method.

+ +
ServerSocket + Creates a ServerSocket object.This error occurs ff the calling content is running outside + the AIR application security sandbox. + + SecurityErrorSecurityError + Creates a ServerSocket object. + + bind + Binds this socket to the specified local address and port.This error occurs when localPort is less than 0 or greater than 65535. + RangeErrorRangeErrorThis error occurs when localAddress is not a syntactically well-formed IP address. + + ArgumentErrorArgumentErrorwhen the socket cannot be bound, such as when: +
  • the underlying network socket (IP and port) is already in bound by another object or process.
  • the application is running under a user account that does not + have the privileges necessary to bind to the port. Privilege issues typically + occur when attempting to bind to well known ports (localPort < 1024)
  • this ServerSocket object is already bound. (Call close() before binding to a different + socket.)
  • when localAddress is not a valid local address.
+ +
IOErrorflash.errors:IOError
localPortint0The number of the port to bind to on the local computer. If localPort, + is set to 0 (the default), the next available system port is bound. Permission to connect to a port + number below 1024 is subject to the system security policy. On Mac and Linux systems, for example, + the application must be running with root privileges to connect to ports below 1024. + + localAddressString0.0.0.0The IP address on the local machine to bind to. This address can be an + IPv4 or IPv6 address. If localAddress is set to 0.0.0.0 (the default), + the socket listens on all available IPv4 addresses. + To listen on all available IPv6 addresses, you must specify "::" as the localAddress + argument. To use an IPv6 address, the computer and network must both be + configured to support IPv6. Furthermore, a socket bound to an IPv4 address + cannot connect to a socket with an IPv6 address. Likewise, a socket bound to an IPv6 + address cannot connect to a socket with an IPv4 address. The type of address must match. + +
+ Binds this socket to the specified local address and port. + +
close + Closes the socket and stops listening for connections.This error occurs if the socket could not be closed, or the socket was not open. + + ErrorError + Closes the socket and stops listening for connections. + +

Closed sockets cannot be reopened. Create a new ServerSocket instance instead.

+ +
listen + Initiates listening for TCP connections on the bound IP address and port.This error occurs if the socket is not open or bound. This error also + occurs if the call to listen() fails for any other reason. + + IOErrorflash.errors:IOErrorThis error occurs if the backlog parameter is less than zero. + + RangeErrorRangeErrorbacklogint0The maximum length of the queue of pending connections. If + backlog is 0, the queue length is set to the maximum system value. + + + Initiates listening for TCP connections on the bound IP address and port. + +

The listen() method returns immediately. Once you call listen(), + the ServerSocket object dispatches a connect + event whenever a connection attempt is made. The socket property of the + ServerSocketConnectEvent event object references + a Socket object representing the server-client connection.

+ +

The backlog parameter specifies how many pending connections are queued while the + connect events are processed by your application. If the queue is full, additional connections + are denied without a connect event being dispatched. If the default value of zero is + specified, then the system-maximum queue length is used. This length varies by platform and can be + configured per computer. If the specified value exceeds the system-maximum length, then the + system-maximum length is used instead. No means for discovering the actual backlog value is provided. + (The system-maximum value is determined by the SOMAXCONN setting of the TCP network subsystem on the + host computer.)

+ +
bound + Indicates whether the socket is bound to a local address and port.Boolean + Indicates whether the socket is bound to a local address and port. + + bind()isSupported + Indicates whether or not ServerSocket features are supported in the run-time environment.Boolean + Indicates whether or not ServerSocket features are supported in the run-time environment. + + + listening + Indicates whether the server socket is listening for incoming connections.Boolean + Indicates whether the server socket is listening for incoming connections. + + listen()localAddress + The IP address on which the socket is listening.String + The IP address on which the socket is listening. + + bind()localPort + The port on which the socket is listening.int + The port on which the socket is listening. + + bind()
FileFilter + The FileFilter class is used to indicate what files on the user's system are shown + in the file-browsing dialog box that is displayed when the FileReference.browse() + method, the FileReferenceList.browse() method is called or a + browse method of a File, FileReference, or FileReferenceList object is called.Object + The FileFilter class is used to indicate what files on the user's system are shown + in the file-browsing dialog box that is displayed when the FileReference.browse() + method, the FileReferenceList.browse() method is called or a + browse method of a File, FileReference, or FileReferenceList object is called. + FileFilter instances are passed as a value for the optional typeFilter parameter to the method. + If you use a FileFilter instance, extensions and file types that aren't specified in the FileFilter instance + are filtered out; that is, they are not available to the user for selection. + If no FileFilter object is passed to the method, all files are shown in the dialog box. + +

You can use FileFilter instances in one of two ways:

+ +
  • A description with file extensions only
  • A description with file extensions and Macintosh file types
+ +

The two formats are not interchangeable within a single call to the browse method. + You must use one or the other.

+ +

You can pass one or more FileFilter instances to the browse method, as shown in the following:

+ + + var imagesFilter:FileFilter = new FileFilter("Images", "~~.jpg;~~.gif;~~.png"); + var docFilter:FileFilter = new FileFilter("Documents", "~~.pdf;~~.doc;~~.txt"); + var myFileReference:FileReference = new FileReference(); + myFileReference.browse([imagesFilter, docFilter]); + + +

Or in an AIR application:

+ + + var imagesFilter:FileFilter = new FileFilter("Images", "~~.jpg;~~.gif;~~.png"); + var docFilter:FileFilter = new FileFilter("Documents", "~~.pdf;~~.doc;~~.txt"); + var myFile:File = new File(); + myFile.browseForOpen("Open", [imagesFilter, docFilter]); + + + + +

The list of extensions in the FileFilter.extension property + is used to filter the files shown in the file browsing dialog. The list is not actually + displayed in the dialog box; to display the file types + for users, you must list the file types in the description string as well as in the extension + list. The description string is displayed in the dialog box in Windows and Linux. + (It is not used on the Macintosh®.) On the Macintosh, if you supply a list of Macintosh file types, + that list is used to filter the files. If not, the list of file extensions is used.

+ +
FileFilter + Creates a new FileFilter instance.descriptionStringThe description string that is visible to users when they select files for uploading. + + extensionStringA list of file extensions that indicate which file formats are visible to users + when they select files for uploading. + + macTypeStringnullA list of Macintosh file types that indicate which file types are visible to + users when they select files for uploading. If no value is passed, this parameter is set to null. + + + Creates a new FileFilter instance. + The following example uploads an image from your local file system to the root display object (in this case, the stage). + Example provided by Andre Venancio. + + +var buttonShape:Shape = new Shape(); +buttonShape.graphics.beginFill(0x336699); +buttonShape.graphics.drawCircle(50, 50, 25); +var button = new SimpleButton(buttonShape, buttonShape, buttonShape, buttonShape); +addChild(button); + +var fileRef:FileReference= new FileReference(); +button.addEventListener(MouseEvent.CLICK, onButtonClick); + +function onButtonClick(e:MouseEvent):void { +fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]); +fileRef.addEventListener(Event.SELECT, onFileSelected); +} + +function onFileSelected(e:Event):void { +fileRef.addEventListener(Event.COMPLETE, onFileLoaded); +fileRef.load(); +} + +function onFileLoaded(e:Event):void { +var loader:Loader = new Loader(); +loader.loadBytes(e.target.data); +addChild(loader); +} +description + The description string for the filter.String + The description string for the filter. The description + is visible to the user in the dialog box that opens + when FileReference.browse() + or FileReferenceList.browse() is called. + The description string contains a string, such as + "Images (~~.gif, ~~.jpg, ~~.png)", that can + help instruct the user on what file types can be uploaded + or downloaded. Note that the actual file types that are supported by + this FileReference object are stored in the extension + property. + + extension + A list of file extensions.String + A list of file extensions. This list indicates the types of files + that you want to show in the file-browsing dialog box. (The list + is not visible to the user; the user sees only the value of the + description property.) The extension property contains + a semicolon-delimited list of file extensions, + with a wildcard (~~) preceding each extension, as shown + in the following string: "~~.jpg;~~.gif;~~.png". + + + macType + A list of Macintosh file types.String + A list of Macintosh file types. This list indicates the types of files + that you want to show in the file-browsing dialog box. (This list + itself is not visible to the user; the user sees only the value of the + description property.) The macType property contains + a semicolon-delimited list of Macintosh file types, as shown + in the following string: "JPEG;jp2_;GIFF". + +
URLRequest + The URLRequest class captures all of the information in a single HTTP request.Object + The URLRequest class captures all of the information in a single HTTP request. URLRequest + objects are passed to the load() methods of the Loader, URLStream, + and URLLoader classes, and to other loading operations, to initiate URL downloads. + They are also passed to the upload() and download() methods + of the FileReference class. + +

A SWF file in the local-with-filesystem sandbox may not load data from, + or provide data to, a resource that is in the network sandbox.

+ +

By default, the calling SWF file + and the URL you load must be in the same domain. For example, a SWF file + at www.adobe.com can load data only from sources that are also at www.adobe.com. + To load data from a different domain, place a URL policy file on the server + hosting the data.

+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) is not restricted by these security limitations. + For content running in Adobe AIR, files in the application security sandbox + can access URLs using any of the following URL schemes:

+ + + +
  • http and https
  • file
  • app-storage
  • app
+ +

Content running in Adobe AIR that is not in the application security + sandbox observes the same restrictions as content running in the browser + (in Flash Player), and loading is + governed by the content's domain and any permissions granted in URL + policy files.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ + +
The following example creates a new Loader object and passes it + a URLRequest object that contains the path to an XML file. If the loading operation is + successful, a complete event is dispatched and the data in the XML + file traces to the output. Additional event handlers capture other events, including error + events. +

To run this example, place a file named XMLFile.xml in the same directory + as your SWF file.

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.*; + + public class URLRequestExample extends Sprite { + + public function URLRequestExample() { + var loader:URLLoader = new URLLoader(); + configureListeners(loader); + + var request:URLRequest = new URLRequest("XMLFile.xml"); + try { + loader.load(request); + } catch (error:Error) { + trace("Unable to load requested document."); + } + } + + private function configureListeners(dispatcher:IEventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + var loader:URLLoader = URLLoader(event.target); + trace("completeHandler: " + loader.data); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
FileReferenceURLRequestHeaderURLRequestDefaultsURLLoaderURLStreamHTMLLoader classURLRequest + Creates a URLRequest object.urlStringnullThe URL to be requested. You can set the URL later by using the url property. + + + Creates a URLRequest object. + + If System.useCodePage is true, the request is encoded using the + system code page, rather than Unicode. + + If System.useCodePage is false, the request is encoded using Unicode, rather than the + system code page. + + The following example shows how you can open new browser windows from Flash Player using the navigateToURL() method. + Example provided by + ActionScriptExamples.com. + +// Requires +// - Button symbol on Stage (or a display object, such as a MovieClip) with instance name "buttonSymbol" +// +buttonSymbol.addEventListener(MouseEvent.CLICK, buttonSymbol_click); + +function buttonSymbol_click(evt:MouseEvent):void { + var req:URLRequest = new URLRequest("http://www.adobe.com/"); + navigateToURL(req, "_blank"); +} +flash.system.System.useCodePageauthenticate + Specifies whether authentication requests should be handled (true + or not (false) for this request.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + Specifies whether authentication requests should be handled or not. + + + Specifies whether authentication requests should be handled (true + or not (false) for this request. If false, authentication + challenges return an HTTP error. + +

The supported authentication methods are:

+ +
  • Windows—HTTP Basic/Digest, Windows Integrated Authentication + (including NTLM and Kerberos), SSL Certificate Authentication.
  • Mac—HTTP Basic/Digest, NTLM, SSL Certificate Authentication.
+ +

Note:The FileReference.upload(), + FileReference.download(), and HTMLLoader.load() + methods do not support the URLRequest.authenticate property.

+ +
flash.net.URLRequestDefaults.authenticate
cacheResponse + Specifies whether successful response data should be cached for this request.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + Specifies whether successful response data should be cached for this request. + When set to true, the AIR application uses the operating system's + HTTP cache. + +

Note:The HTMLLoader.load() method + does not support the URLRequest.cacheResponse property.

+ +
flash.net.URLRequestDefaults.cacheResponse
contentType + The MIME content type of the content in the the data property.StringThe MIME content type of the content in the data property. + + + The MIME content type of the content in the the data property. + +

The default value is application/x-www-form-urlencoded.

+ +

Note:The FileReference.upload(), + FileReference.download(), and HTMLLoader.load() methods do not + support the URLRequest.contentType property.

+ +

When sending a POST request, the values of the contentType + and data properties must correspond properly. The value of the contentType + property instructs servers on how to interpret the value of the data property.

+ +
  • If the value of the data property is a URLVariables object, the value of + contentType must be application/x-www-form-urlencoded.
  • If the value of the data property is any other type, the value of contentType + should indicate the type of the POST data that will be sent (which is the binary or string data + contained in the value of the data property).
  • For FileReference.upload(), + the Content-Type of the request is set automatically to multipart/form-data, + and the value of the contentType property is ignored.
+ +

In Flash Player 10 and later, if you use a multipart Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ +
data
data + An object containing data to be transmitted with the URL request.Object + An object containing data to be transmitted with the URL request. + +

This property is used in conjunction with the method property. + When the value of method is GET, + the value of data is appended to the value of URLRequest.url, + using HTTP query-string syntax. When the method value is POST + (or any value other than GET), the value + of data is transmitted in the body of the HTTP request.

+ +

The URLRequest API offers binary POST support and support for URL-encoded variables, + as well as support for strings. The data object can be a ByteArray, URLVariables, + or String object.

+ +

The way in which the data is used depends on the type of object used:

+ +
  • If the object is a ByteArray object, the binary + data of the ByteArray object is used as POST data. For GET, data of ByteArray type + is not supported. Also, data of ByteArray type is not supported for + FileReference.upload() and FileReference.download().
  • If the object is a URLVariables object and the method is POST, + the variables are encoded using x-www-form-urlencoded format + and the resulting string is used as POST data. An exception is a call to + FileReference.upload(), in which the variables are sent as separate fields in + a multipart/form-data post.
  • If the object is a URLVariables object and the method is GET, + the URLVariables object defines variables to be sent with the URLRequest object.
  • Otherwise, the object is converted to a string, and the string + is used as the POST or GET data.
+ +

This data is not sent until a method, such as navigateToURL() + or FileReference.upload(), uses the URLRequest object.

+ +

Note: The value of contentType must correspond to the type of data + in the data property. See the note in the description of the + contentType property.

+ +
The following example opens the remote application hosted at + http://www.[yourDomain].com/application.jsp in a new browser window and passes + data about a user session, captured in a URLVariables object, to the application. + +

Highlights of the example follow:

+
  1. The constructor function creates a URLRequest + instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The example calls navigateToURL, which opens a new browser window + to the remote application's URL.
+

Note: To run the example, the remote application URL in the example must be replaced + with a working URL. Additionally, you would need server code + to process the information captured by Flash Player in the URLVariables object.

+ +package { + import flash.display.Sprite; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.net.URLVariables; + + public class URLVariablesExample extends Sprite { + + public function URLVariablesExample() { + var url:String = "http://www.[yourDomain].com/application.jsp"; + var request:URLRequest = new URLRequest(url); + var variables:URLVariables = new URLVariables(); + variables.exampleSessionId = new Date().getTime(); + variables.exampleUserLabel = "guest"; + request.data = variables; + navigateToURL(request); + } + } +} +
URLRequest.methodURLRequestMethodURLVariablesflash.utils.ByteArraycontentType
digest + A string that uniquely identifies the signed Adobe platform component to be stored + to (or retrieved from) the Flash Player cache.StringThe digest provided does not match the digest of the file that is + extracted from the downloaded signed file or the signed file loaded out of the cache. The + application also throws this error if the provided digest is the wrong length or contains invalid + (nonhexadecimal) characters. + + ArgumentErrorArgumentError + A string that uniquely identifies the signed Adobe platform component to be stored + to (or retrieved from) the Flash Player cache. An Adobe + platform component is a signed file (a SWZ file) that contains SWF content that is cached + persistently on a user's machine. All SWZ files are signed by Adobe. A digest + corresponds to a single cached file; if you change the file in any way, its digest + will change in an unpredictable way. By using a digest, you can verify the cached file across + multiple domains. Two files with the same digest are the same file, and two files with different + digests are not the same file. A file cannot (practically) be created to "spoof" a digest and + pretend to be another digest. + +

The digest is based on an SHA-256 message digest algorithm + (64 characters long in hexadecimal format).

+ +

For example, the Flex SDK includes a SWZ for the Flex framework (and it + provides the digest string for that SWZ file). You can post this SWZ on your web server and load it + in your SWF file (using the load() method of a URLLoader object). If the end user's + machine already has the matching SWZ file cached, the application uses the cached SWZ file. + (A SWZ file matches if its digest matches the one you provide.) Otherwise, the + application downloads the SWZ file from the URL you specify.

+ +

Only set the digest parameter in a URLRequest object + used in a call to the URLLoader.load() method to load a SWZ file. If the digest + property of a a URLRequest object is set when it is used in other methods, the application throws an + IOError exception.

+ +
The following example loads a remote file into the cache. At the end of the load, the byte array + contains the actual file (not the signed file). The example completes the load operation by calling loadBytes(): + + +var myURLReq:URLRequest = new URLRequest(); +myURLReq.url = "http://yourdomain/users/jdoe/test01/_rsc/Automated/AssetCaching_rsc/test01/rsl.swz"; +myURLReq.digest = "3B0AA28C7A990385E044D80F5637FB036317BB41E044D80F5637FB036317BB41"; +var myURLLoader:URLLoader = new URLLoader(); +myURLLoader.dataFormat = URLLoaderDataFormat.BINARY; +myURLLoader.addEventListener("complete", onC); + +myURLLoad.load(myURLReq); + +function onC(e) { + var someLoader:Loader = new Loader(); + addChild(someLoader); + someLoader.loadBytes((ByteArray)(myURLLoad.data)); +} + +
followRedirects + Specifies whether redirects are to be followed (true) + or not (false).BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + Specifies whether redirects are to be followed. + + + Specifies whether redirects are to be followed (true) + or not (false). + +

Note:The FileReference.upload(), + FileReference.download(), and HTMLLoader.load() methods do not + support the URLRequest.followRedirects property.

+ +
URLRequestDefaults.followRedirects
idleTimeout + Specifies the idle timeout value (in milliseconds) for this request.NumberThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrorinitialized from the URLRequestDefaults.idleTimeout property + + + Specifies the idle timeout value (in milliseconds) for this request. + +

The idle timeout is the amount of time the client waits for a response from the server, after the connection is established, + before abandoning the request.

+ +

Note: The HTMLLoader.load() method + does not support the URLRequest.idleTimeout property. + The HTMLLoader class defines its own idleTimeout property.

+ +
URLRequestDefaults.idleTimeout
manageCookies + Specifies whether the HTTP protocol stack should manage cookies for this + request.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + Specifies whether the HTTP protocol stack should manage cookies for this + request. When true, cookies are added to the request + and response cookies are remembered. If false, cookies are + not added to the request and response cookies are not + remembered, but users can manage cookies themselves by direct header + manipulation. + + Note: On Windows, you cannot add cookies to a URL request manually + when manageCookies is set to true. On other operating systems, + adding cookies to a request is permitted irrespective of whether manageCookies + is set to true or false. When permitted, you can add cookies + to a request manually by adding a URLRequestHeader object containing the + cookie data to the requestHeaders array. + +

On Mac OS, cookies are shared with Safari. To clear cookies on Mac OS:

+ +
  1. Open Safari.
  2. Select Safari > Preferences, and click the Security panel.
  3. Click the Show Cookies button.
  4. Click the Reomove All button.
+ +

To clear cookies on Windows:

+ +
  1. Open the Internet Properties control panel, and click the General tab.
  2. Click the Delete Cookies button.
+ +
flash.net.URLRequestDefaults.manageCookies
method + Controls the HTTP form submission method.StringIf the value parameter is not + URLRequestMethod.GET or URLRequestMethod.POST. + + ArgumentErrorArgumentErrorURLRequestMethod.GET + + + Controls the HTTP form submission method. + +

For SWF content running in Flash Player + (in the browser), this property is limited to GET or + POST operations, and valid values are URLRequestMethod.GET + or URLRequestMethod.POST.

+ +

For content running in Adobe AIR, you + can use any string value + if the content is in the application security sandbox. Otherwise, + as with content running in Flash Player, + you are restricted to using GET or POST operations.

+ +

For content running in Adobe AIR, when + using the navigateToURL() function, the runtime treats a URLRequest that uses the POST + method (one that has its method property set to URLRequestMethod.POST) + as using the GET method.

+ +

Note: + If running in Flash Player and the referenced form has no body, + Flash Player automatically uses a GET operation, even if the method is set to + URLRequestMethod.POST. For this reason, it is recommended to always include + a "dummy" body to ensure that the correct method is used.

+ +
The following example opens the remote application hosted at + http://www.[yourDomain].com/application.jsp in a new browser window and passes + data about a user session, captured in a URLVariables object, to the application. + It explicitly sets the value of the URLRequest.method property to + URLRequestMethod.POST. +

Highlights of the example follow:

+
  1. The constructor function creates a URLRequest + instance named request, taking the URL of the remote application as a parameter.
  2. A URLVariables object is created and two of its properties are assigned values.
  3. The URLVariables object is assigned to the data property of the URLRequest object.
  4. The value of the URLRequest.method property is set to + URLRequestMethod.POST.
  5. The example calls navigateToURL, which opens a new browser window + to the remote application's URL.
+

Note: To run the example, the remote application URL in the example must be replaced + with a working URL. Additionally, you would need server code + to process the information captured by Flash Player in the URLVariables object.

+ +package { + import flash.display.Sprite; + import flash.net.navigateToURL; + import flash.net.URLRequest; + import flash.net.URLRequestMethod; + import flash.net.URLVariables; + + public class URLRequest_method extends Sprite { + + public function URLRequest_method() { + var url:String = "http://www.[yourDomain].com/application.jsp"; + var request:URLRequest = new URLRequest(url); + + var variables:URLVariables = new URLVariables(); + variables.exampleSessionId = new Date().getTime(); + variables.exampleUserLabel = "guest"; + request.data = variables; + request.method = URLRequestMethod.POST; + + navigateToURL(request); + } + } +} +
URLRequestMethod class
requestHeaders + The array of HTTP request headers to be appended to the + HTTP request.Array + The array of HTTP request headers to be appended to the + HTTP request. The array is composed of URLRequestHeader objects. + Each object in the array must be a URLRequestHeader object that + contains a name string and a value string, as follows: + + var rhArray:Array = new Array(new URLRequestHeader("Content-Type", "text/html")); + + +

Flash Player and the AIR runtime impose + certain restrictions on request headers; + for more information, see the URLRequestHeader class description.

+ +

Not all methods that accept URLRequest parameters support the requestHeaders property, + consult the documentation for the method you are calling. For example, the FileReference.upload() + and FileReference.download() methods do not + support the URLRequest.requestHeaders property.

+

Due to browser limitations, custom HTTP request headers are only supported for POST requests, + not for GET requests.

+ +
URLRequestHeader
url + The URL to be requested.String + The URL to be requested. + +

Be sure to encode any characters that are either described as unsafe in the Uniform Resource Locator + specification (see http://www.faqs.org/rfcs/rfc1738.html) or that are reserved in the + URL scheme of the URLRequest object (when not used for their reserved purpose). For example, + use "%25" for the percent (%) symbol and "%23" for the number sign (#), as in + "http://www.example.com/orderForm.cfm?item=%23B-3&discount=50%25".

+ +

By default, the URL must be in the same domain as the calling file, + unless the content is running in the Adobe AIR application + security sandbox. If you need to load data from a different domain, + put a URL policy file on the server that is hosting the data. For more information, + see the description of the URLRequest class.

+ +

For content running in Adobe AIR, files + in the application security sandobx + — files installed with the AIR application — can access URLs using any of the + following URL schemes:

+ +
  • http and https
  • file
  • app-storage
  • app
+ +

Note: IPv6 (Internet Protocol version 6) is supported in + AIR and in Flash Player 9.0.115.0 and later. + + IPv6 is a version of Internet Protocol that supports + 128-bit addresses (an improvement on the earlier IPv4 protocol that supports 32-bit + addresses). You might need to activate IPv6 on your networking interfaces. For more + information, see the Help for the operating system hosting the data. + If IPv6 is supported on the hosting system, you can specify numeric IPv6 literal addresses + in URLs enclosed in brackets ([]), as in the following.

+ + +
+     rtmp://[2001:db8:ccc3:ffff:0:444d:555e:666f]:1935/test
+     
+
+ +
The following example shows how you can dynamically load an image using the Loader class in ActionScript 3.0. + Example provided by + ActionScriptExamples.com. + +var url:String = "http://www.helpexamples.com/flash/images/image2.jpg"; +var urlRequest:URLRequest = new URLRequest(url); +var loader:Loader = new Loader(); +loader.load(urlRequest); +addChild(loader); +
useCache + Specifies whether the local cache should be consulted before this URLRequest + fetches data.BooleanThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityErrortrue + + + Specifies whether the local cache should be consulted before this URLRequest + fetches data. + +

Note:The HTMLLoader.load() method + does not support the URLRequest.useCache property.

+ +
flash.net.URLRequestDefaults.useCache
userAgent + Specifies the user-agent string to be used in the HTTP request.StringThe caller is not in the AIR application security sandbox. + + SecurityErrorSecurityError + Specifies the user-agent string to be used in the HTTP request. + +

The default value is the same user agent string that is used by + Flash Player, which is different on Mac, Linux, and Windows.

+ +

Note: This property does not affect the user agent string when + the URLRequest object is used with the load() method of an + HTMLLoader object. To set the user agent string for an HTMLLoader object, + set the userAgent property of the HTMLLoader object or set + the static URLRequestDefaults.userAgent property.

+ +
flash.net.URLRequestDefaults.userAgentflash.html.HTMLLoader.userAgent
InterfaceAddress + The InterfaceAddress class reports the properties of a network interface address.Object + The InterfaceAddress class reports the properties of a network interface address. + + NetworkInfo classNetworkInterface classaddress + The Internet Protocol (IP) address.String + The Internet Protocol (IP) address. + + broadcast + The broadcast address of the local network segment.String + The broadcast address of the local network segment. + + ipVersion + The IP address type (IPv4 or IPv6).String + The IP address type (IPv4 or IPv6). + + prefixLength + The prefix length for this address.int + The prefix length for this address. + +

For IPv4 addresses, this is the subnet mask. Examples of the prefix length for + IPv4 values include: 8 (255.0.0.0), 16 (255.255.0.0) and 24 (255.255.255.0). + Example IPv6 prefix length values include 128 (::1/128) and 32 (2001:db8::/32)

+ +

Note: If the prefix length for this address is not available, the value of + prefixLength is -1. A prefix value is not always returned by + the network implementation of a specific client computer.

+ +
GroupSpecifier + The GroupSpecifier class is used to construct the opaque groupspec strings + that can be passed to NetStream and NetGroup constructors.Constructs the opaque groupspec strings passed to NetStream and NetGroup constructors. + Object + The GroupSpecifier class is used to construct the opaque groupspec strings + that can be passed to NetStream and NetGroup constructors. + A groupspec specifies an RTMFP Peer-to-Peer Group, including + the capabilities, restrictions, and authorizations of the member using the groupspec. + +

By default, all capabilities are disabled, and peer-to-peer connections are allowed.

+ +
flash.net.NetGroupflash.net.NetStreamGroupSpecifier + Creates a new GroupSpecifier object.if name is empty or null. + + ArgumentErrorArgumentErrornameStringA name for the Group on which all members must agree. + + + Creates a new GroupSpecifier object. + + By default, all capabilities are disabled, and peer-to-peer connections are allowed. + + flash.net.NetGroupflash.net.NetStreamaddBootstrapPeer + Causes the associated NetStream or NetGroup to make an initial neighbor connection to the + specified peerID.peerIDStringThe peerID to which an initial neighbor connection should be made to + bootstrap into the peer-to-peer mesh. + + + Causes the associated NetStream or NetGroup to make an initial neighbor connection to the + specified peerID. + + encodeBootstrapPeerIDSpec()flash.net.NetGroup.addMemberHint()flash.net.NetGroup.addNeighbor()addIPMulticastAddress + Causes the associated NetStream or NetGroup to join the specified IP multicast group and listen + to the specified UDP port.addressStringA String specifying the address of the IPv4 or IPv6 multicast group to join, optionally followed + by a colon (":") and the UDP port number. If specifying an IPv6 address and a port, + the IPv6 address must be enclosed in square brackets. Examples: "224.0.0.254", + "224.0.0.254:30000", "ff03::ffff", "[ff03::ffff]:30000". + + portnullThe UDP port on which to receive IP multicast datagrams. If port is null, + the UDP port must be specified in address. If not null, the + UDP port must not be specified in address. + + sourceStringnullIf not null, a String specifying the source IP address of a source-specific multicast (SSM). + + + Causes the associated NetStream or NetGroup to join the specified IP multicast group and listen + to the specified UDP port. + + encodeIPMulticastAddressSpec()ipMulticastMemberUpdatesEnabledauthorizations + Returns a string that represents passwords for IP multicast publishing and for posting.String + Returns a string that represents passwords for IP multicast publishing and for posting. + Append the string to an unauthorized groupspec to enable + features for which passwords have been set. + + encodePostingAuthorization()encodePublishAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()setPostingPassword()setPublishPassword()encodeBootstrapPeerIDSpec + Encodes and returns a string that represents a bootstrap peerID.StringpeerIDStringThe peerID to which an initial neighbor connection should be made to + bootstrap into the peer-to-peer mesh. + + + Encodes and returns a string that represents a bootstrap peerID. If you append the string + to a groupspec, the associated NetStream or NetGroup makes an initial neighbor connection to the + specified peerID. + + addBootstrapPeer()flash.net.NetGroup.addMemberHint()flash.net.NetGroup.addNeighbor()encodeIPMulticastAddressSpec + Encodes and returns a string that represents an IP multicast socket address.StringaddressStringA String indicating the address of the IPv4 or IPv6 multicast group to join, optionally followed + by a colon (":") and the UDP port number. If specifying an IPv6 address and a port, + the IPv6 address must be enclosed in square brackets. Examples: "224.0.0.254", + "224.0.0.254:30000", "ff03::ffff", "[ff03::ffff]:30000". + + portnullThe UDP port on which to receive IP multicast datagrams. If port is null, + the UDP port must be specified in address. If not null, the + UDP port must not be specified in address. + + sourceStringnullIf not null, a String specifying the source IP address of a source-specific multicast (SSM). + + + Encodes and returns a string that represents an IP multicast socket address. + If you append the string to a groupspec, the associated NetStream or NetGroup + joins the specified IP multicast group and listens to the specified UDP port. + + + addIPMulticastAddress()ipMulticastMemberUpdatesEnabledencodePostingAuthorization + Encodes and returns a string that represents a posting password.StringpasswordStringThe password to encode, which must match the posting + password (if set) to enable NetGroup.post(). + + + Encodes and returns a string that represents a posting password. When posting is password-protected, + you can concatenate the string to a groupspec to enable posting. + + groupspecWithoutAuthorizations()setPostingPassword()flash.net.NetGroup.post()encodePublishAuthorization + Encodes and returns a string that represents a multicast publishing password.StringpasswordStringThe password to encode, which must match the publish + password (if set) to enable NetStream.publish(). + + + Encodes and returns a string that represents a multicast publishing password. When multicast publishing is password-protected, + you can concatenate the string to a groupspec to enable publishing. + + groupspecWithoutAuthorizations()setPublishPassword()flash.net.NetStream.publish()groupspecWithAuthorizations + Returns the opaque groupspec string, including authorizations, that can be passed to NetStream and NetGroup constructors.String + Returns the opaque groupspec string, including authorizations, that can be passed to NetStream and NetGroup constructors. + + authorizations()groupspecWithoutAuthorizations()setPostingPassword()setPublishPassword()toString()groupspecWithoutAuthorizations + Returns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors.StringReturns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors. + + Returns the opaque groupspec string, without authorizations, that can be passed to NetStream and NetGroup constructors. + + authorizations()encodePostingAuthorization()encodePublishAuthorization()groupspecWithAuthorizations()makeUnique + Adds a strong pseudorandom tag to the groupspec to make it unique.Adds a strong pseudorandom tag to the groupspec to make it unique. + + Adds a strong pseudorandom tag to the groupspec to make it unique. The opaque groupspec string must then + be passed verbatim to other potential members of the Group if they are to successfully join. + + setPostingPassword + Specifies whether a password is required to post in the NetGroup.passwordStringnullThe password that must be given to use NetGroup.post(). If null, + no password is required to post. + + saltStringnullModifies the hash of the password to increase the difficulty of guessing it. + For best security, this parameter should be set to a random value. + + + Specifies whether a password is required to post in the NetGroup. + + encodePostingAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()flash.net.NetGroup.post()setPublishPassword + Specifies whether a password is required to publish a multicast stream in the NetStream.passwordStringnullThe password that must be given to use NetStream.publish(). If null, + no password is required to publish. + + saltStringnullModifies the hash of the password to increase the difficulty of guessing it. + For best security, this parameter should be set to a random value. + + + Specifies whether a password is required to publish a multicast stream in the NetStream. + + encodePublishAuthorization()groupspecWithAuthorizations()groupspecWithoutAuthorizations()flash.net.NetStream.publish()toString + Identical to the groupspecWithAuthorizations() method.StringIdentical to the groupspecWithAuthorizations() method. + + Identical to the groupspecWithAuthorizations() method. + Convenience method to return the opaque groupspec string, including authorizations, + that can be passed to NetStream and NetGroup constructors. + + groupspecWithAuthorizations()ipMulticastMemberUpdatesEnabled + Specifies whether information about group membership can be exchanged on IP multicast + sockets.Boolean + Specifies whether information about group membership can be exchanged on IP multicast + sockets. IP multicast servers may send group membership updates to help bootstrap P2P meshes + or heal partitions. Peers may send membership updates on the LAN to help bootstrap LAN P2P + meshes and to inform on-LAN neighbors in global meshes that other on-LAN neighbors exist. + These updates can improve P2P performance. + + addIPMulticastAddress()peerToPeerDisabledmulticastEnabled + Specifies whether streaming is enabled for the NetGroup.Boolean + Specifies whether streaming is enabled for the NetGroup. Methods used for streaming + are NetStream.publish(), NetStream.play(), and NetStream.play2(). + By default, this property is FALSE (streaming is disabled). + + setPublishPassword()flash.net.NetStream.play()flash.net.NetStream.play2()flash.net.NetStream.publish()objectReplicationEnabled + Specifies whether object replication is enabled for the NetGroup.Boolean + Specifies whether object replication is enabled for the NetGroup. + By default, this property is FALSE (object replication is disabled). + + flash.net.NetGroup.addHaveObjects()flash.net.NetGroup.addWantObjects()flash.net.NetGroup.denyRequestedObject()flash.net.NetGroup.removeHaveObjects()flash.net.NetGroup.removeWantObjects()flash.net.NetGroup.writeRequestedObject()peerToPeerDisabled + Specifies whether peer-to-peer connections are disabled for the NetGroup or NetStream.Boolean + Specifies whether peer-to-peer connections are disabled for the NetGroup or NetStream. + By default, this property is FALSE (P2P connections are enabled). + +

If P2P connections are disabled (you set this property to TRUE), the P2P warning dialog is suppressed. + In this situation, no neighbor connections can be made, and no group members use upstream bandwidth. + Disabling P2P connections in this way is generally useful only when receiving multicast streams via pure IP multicast.

+ +
postingEnabled + Specifies whether posting is enabled for the NetGroup.Boolean + Specifies whether posting is enabled for the NetGroup. + By default, this property is FALSE (posting is disabled). + + flash.net.NetGroup.post()routingEnabled + Specifies whether directed routing methods are enabled for the NetGroup.Boolean + Specifies whether directed routing methods are enabled for the NetGroup. + By default, this property is FALSE (directed routing methods are disabled). + + flash.net.NetGroup.sendToNearest()serverChannelEnabled + Specifies whether members of the NetGroup can open a channel to the server.Boolean + Specifies whether members of the NetGroup can open a channel to the server. + By default, this property is FALSE. + +

A channel to the server must be opened before the + server can provide supporting functions to group members. Depending on server + configuration, supporting functions may or may not be provided over this channel.

+ +
LocalConnection + The LocalConnection class lets you create a LocalConnection object that can invoke a method in another + LocalConnection object.flash.events:EventDispatcher + The LocalConnection class lets you create a LocalConnection object that can invoke a method in another + LocalConnection object. The communication can be: + +
  • Within a single SWF file
  • Between multiple SWF files
  • Between content (SWF-based or HTML-based) in AIR applications
  • Between content (SWF-based or HTML-based) in an AIR application and SWF content running in a browser
+ +

AIR profile support: This feature is supported + on all desktop operating systems and on all AIR for TV devices, but is not supported on mobile devices. + You can test for support at run time using the LocalConnection.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

Note: AIR for TV devices support communication only between SWF-based content in AIR + applications.

+ +

Local connections enable this kind of communication between SWF files without the use of fscommand() + or JavaScript. LocalConnection objects can communicate only among files that are running + on the same client computer, but they can be + running in different applications — for example, a file running in a browser + and a SWF file running in Adobe AIR.

+ +

LocalConnection objects created in ActionScript 3.0 can communicate with + LocalConnection objects created in ActionScript 1.0 or 2.0. The reverse is also true: + LocalConnection objects created in ActionScript 1.0 or 2.0 can communicate with LocalConnection + objects created in ActionScript 3.0. Flash Player handles this communication + between LocalConnection objects of different versions automatically.

+ +

There are three ways to add callback methods to a LocalConnection object:

+ +
  • Subclass the LocalConnection class and add methods.
  • Set the LocalConnection.client property to an object that implements the methods.
  • Create a dynamic class that extends LocalConnection and dynamically attach methods.
+ +

To understand how to use LocalConnection objects to implement communication between two files, + it is helpful to identify the commands used in each file. One file is called the receiving file; + it is the file that contains the method to be invoked. The receiving file must contain a LocalConnection object + and a call to the connect() method. The other file is called the sending file; + it is the file that invokes the method. The sending file must contain another LocalConnection object + and a call to the send() method.

+ +

Your use of send() and connect() differs depending on whether the + files are in the same domain, in different domains with predictable domain names, + or in different domains with unpredictable or dynamic domain names. The following paragraphs + explain the three different situations, with code samples for each.

+ +

Same domain. This is the simplest way to use a LocalConnection object, + to allow communication only between LocalConnection objects that are located in the same domain, + because same-domain communication is permitted by default. When two files from the same domain communicate, + you do not need to implement any special security measures, and you simply pass the same + value for the connectionName parameter to both the connect() + and send() methods:

+ +

+ + +// receivingLC is in http://www.domain.com/receiving.swf +receivingLC.connect('myConnection'); + +// sendingLC is in http://www.domain.com/sending.swf +// myMethod() is defined in sending.swf +sendingLC.send('myConnection', 'myMethod'); + +

Different domains with predictable domain names. + When two SWF files from different domains communicate, + you need to allow communication between the two domains by calling the allowDomain() + method. You also need to qualify the connection name in the send() method + with the receiving LocalConnection object's domain name:

+ +

+ + +// receivingLC is in http://www.domain.com/receiving.swf +receivingLC.allowDomain('www.anotherdomain.com'); +receivingLC.connect('myConnection'); + +// sendingLC is in http://www.anotherdomain.com/sending.swf +sendingLC.send('www.domain.com:myConnection', 'myMethod'); + + +

Different domains with unpredictable domain names. + Sometimes, you might want to make the file with the receiving LocalConnection object + more portable between domains. To avoid specifying the domain name in the send() method, + but to indicate that the receiving and sending LocalConnection objects + are not in the same domain, precede the connection name + with an underscore (_), in both the connect() and send() calls. + To allow communication between the two domains, call the allowDomain() method + and pass the domains from which you want to allow LocalConnection calls. + Alternatively, pass the wildcard (~~) argument to allow calls from all domains:

+ +

+ +// receivingLC is in http://www.domain.com/receiving.swf +receivingLC.allowDomain('~~'); +receivingLC.connect('_myConnection'); + +// sendingLC is in http://www.anotherdomain.com/sending.swf +sendingLC.send('_myConnection', 'myMethod'); + + +

From Flash Player to an AIR application. + A LocalConnection object created in the AIR application sandbox uses a special string as it's connection + prefix instead of a domain name. This string has the form: + app#appID.pubID where appID is the application ID and pubID is the publisher ID of the application. + (Only include the publisher ID if the AIR application uses a publisher ID.) For example, if an + AIR application has an application ID of, "com.example", and no publisher ID, you could use: + app#com.example:myConnection as the local connection string. The AIR application also must call + the allowDomain() method, passing in the calling SWF file's domain of origin:

+ +

+ + +// receivingLC is an AIR application with app ID = com.example (and no publisher ID) +receivingLC.allowDomain('www.domain.com'); +receivingLC.connect('myConnection'); + +// sendingLC is in http://www.domain.com/sending.swf +sendingLC.send('app#com.example:myConnection', 'myMethod'); + + +

Note: If an AIR application loads a SWF outside the AIR application sandbox, then the rules for + establishing a local connection with that SWF are the same as the rules for establishing a connection with a SWF + running in Flash Player.

+ +

From an AIR application to Flash Player. + When an AIR application communicates with a SWF running in the Flash Player runtime, + you need to allow communication between the two by calling the allowDomain() + method and passing in the AIR application's connection prefix. For example, if an + AIR application has an application ID of, "com.example", and no publisher ID, you could pass the string: + app#com.example to the allowDomain() method. + You also need to qualify the connection name in the send() method + with the receiving LocalConnection object's domain name (use "localhost" as the domain for SWF files loaded from the + local file system):

+ +

+ + +// receivingLC is in http://www.domain.com/receiving.swf +receivingLC.allowDomain('app#com.example'); +receivingLC.connect('myConnection'); + +// sendingLC is an AIR application with app ID = com.example (and no publisher ID) +sendingLC.send('www.domain.com:myConnection', 'myMethod'); + + +

From an AIR application to another AIR application. + To communicate between two AIR applications, + you need to allow communication between the two by calling the allowDomain() + method and passing in the sending AIR application's connection prefix. For example, if the sending + application has an application ID of, "com.example", and no publisher ID, you could pass the string: + app#com.example to the allowDomain() method in the receiving application. + You also need to qualify the connection name in the send() method + with the receiving LocalConnection object's connection prefix:

+ +

+ + +// receivingLC is an AIR application with app ID = com.sample (and no publisher ID) +receivingLC.allowDomain('app#com.example'); +receivingLC.connect('myConnection'); + +// sendingLC is an AIR application with app ID = com.example (and no publisher ID) +sendingLC.send('app#com.sample:myConnection', 'myMethod'); + + +

You can use LocalConnection objects to send and receive data within a single file, + but this is not a typical implementation.

+ +

For more information about the send() and connect() methods, see the discussion of the + connectionName parameter in the LocalConnection.send() and + LocalConnection.connect()entries. Also, see the allowDomain() and domain entries.

+ +
This example consists of two ActionScript classes which + should be compiled into two separate SWF files: + +

In the LocalConnectionSenderExample SWF file, a LocalConnection instance is created, + and when the button is pressed the call() method is used to + call the method named lcHandler in the SWF file with the + connection name "myConnection," passing the contents of the + TextField as a parameter.

+ +

In the LocalConnectionReceiverExample SWF file, a LocalConnection instance is + created and the connect() method is called to designate + this SWF file as the recipient of messages that are addressed to the + connection named "myConnection." In addition, this class includes + a public method named lcHandler(); this method is the + one that is called by the LocalConnectionSenderExample SWF file. When it's called, + the text that is passed in as a parameter is appended to the + TextField on the Stage.

+ +

Note: To test the example, both SWF files must + be loaded on the same computer simultaneously.

+ + +// Code in LocalConnectionSenderExample.as +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.net.LocalConnection; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.events.StatusEvent; + import flash.text.TextFieldAutoSize; + + public class LocalConnectionSenderExample extends Sprite { + private var conn:LocalConnection; + + // UI elements + private var messageLabel:TextField; + private var message:TextField; + private var sendBtn:Sprite; + + public function LocalConnectionSenderExample() { + buildUI(); + sendBtn.addEventListener(MouseEvent.CLICK, sendMessage); + conn = new LocalConnection(); + conn.addEventListener(StatusEvent.STATUS, onStatus); + } + + private function sendMessage(event:MouseEvent):void { + conn.send("myConnection", "lcHandler", message.text); + } + + private function onStatus(event:StatusEvent):void { + switch (event.level) { + case "status": + trace("LocalConnection.send() succeeded"); + break; + case "error": + trace("LocalConnection.send() failed"); + break; + } + } + + private function buildUI():void { + const hPadding:uint = 5; + // messageLabel + messageLabel = new TextField(); + messageLabel.x = 10; + messageLabel.y = 10; + messageLabel.text = "Text to send:"; + messageLabel.autoSize = TextFieldAutoSize.LEFT; + addChild(messageLabel); + + // message + message = new TextField(); + message.x = messageLabel.x + messageLabel.width + hPadding; + message.y = 10; + message.width = 120; + message.height = 20; + message.background = true; + message.border = true; + message.type = TextFieldType.INPUT; + addChild(message); + + // sendBtn + sendBtn = new Sprite(); + sendBtn.x = message.x + message.width + hPadding; + sendBtn.y = 10; + var sendLbl:TextField = new TextField(); + sendLbl.x = 1 + hPadding; + sendLbl.y = 1; + sendLbl.selectable = false; + sendLbl.autoSize = TextFieldAutoSize.LEFT; + sendLbl.text = "Send"; + sendBtn.addChild(sendLbl); + sendBtn.graphics.lineStyle(1); + sendBtn.graphics.beginFill(0xcccccc); + sendBtn.graphics.drawRoundRect(0, 0, (sendLbl.width + 2 + hPadding + hPadding), (sendLbl.height + 2), 5, 5); + sendBtn.graphics.endFill(); + addChild(sendBtn); + } + } +} +
+// Code in LocalConnectionReceiverExample.as +package { + import flash.display.Sprite; + import flash.net.LocalConnection; + import flash.text.TextField; + + public class LocalConnectionReceiverExample extends Sprite { + private var conn:LocalConnection; + private var output:TextField; + + public function LocalConnectionReceiverExample() { + buildUI(); + + conn = new LocalConnection(); + conn.client = this; + try { + conn.connect("myConnection"); + } catch (error:ArgumentError) { + trace("Can't connect...the connection name is already being used by another SWF"); + } + } + + public function lcHandler(msg:String):void { + output.appendText(msg + "\n"); + } + + private function buildUI():void { + output = new TextField(); + output.background = true; + output.border = true; + output.wordWrap = true; + addChild(output); + } + } +} +
flash.net.LocalConnection.send()flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.domainstatus + Dispatched when a LocalConnection object reports its status.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when a LocalConnection object reports its status. + If LocalConnection.send() is successful, the value of the status event + object's level property is "status"; if the call fails, the level property + is "error". If the receiving file refuses the connection, the call can fail + without notification to the sending file. + + LocalConnection.send()securityError + Dispatched if a call to LocalConnection.send() + attempts to send data to a different security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched if a call to LocalConnection.send() + attempts to send data to a different security sandbox. + send()asyncError + Dispatched when an exception is thrown asynchronously &#x2014; that is, + from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent + Dispatched when an exception is thrown asynchronously — that is, + from native asynchronous code. + + LocalConnection + Creates a LocalConnection object. + Creates a LocalConnection object. You can use LocalConnection objects to enable + communication between different files that are running on the same client computer. + + flash.net.LocalConnection.connect()flash.net.LocalConnection.send()allowDomain + Specifies one or more domains that can send LocalConnection calls to this LocalConnection instance.All parameters specified must be non-null strings. + + ArgumentErrorArgumentErrordomainsOne or more strings that name the domains from which + you want to allow LocalConnection calls. This parameter has two special cases: + +
  • You can specify a wildcard character "~~" to allow calls from all domains.
  • You can specify the string "localhost" to allow calls to this file from files that + are installed locally. Flash Player 8 introduced security restrictions + on local files. By default, a SWF file running in Flash Player + that is allowed to access the Internet cannot also have access to the local file system. + In Flash Player, if you specify "localhost", any local SWF file can access this + SWF file.
+ +
+ Specifies one or more domains that can send LocalConnection calls to this LocalConnection instance. + +

You cannot use this method to let files hosted using a secure protocol (HTTPS) allow access from + files hosted in nonsecure protocols; you must use the allowInsecureDomain() method instead.

+ +

You may want to use this method so that a child file from a different domain can make LocalConnection + calls to the parent file, without knowing the final domain from which the child file will come. + This can happen, for example, when you use load-balancing redirects or third-party servers. In this situation, + you can use the url property of the LoaderInfo object used with the load, to get the domain to use with + the allowDomain() method. For example, if you use a Loader object to load a child file, once the file + is loaded, you can check the contentLoaderInfo.url property of the Loader object, and parse the domain + out of the full URL string. If you do this, make sure that you wait until the file is loaded, because the + contentLoaderInfo.url property will not have its final, correct value until the file is completely loaded.

+ +

The opposite situation can also occur: you might create a child file that wants to accept LocalConnection + calls from its parent but doesn't know the domain of its parent. In this situation, implement this method by + checking whether the domain argument matches the domain of the loaderInfo.url property in the + loaded file. Again, you must parse the domain out of the full URL from loaderInfo.url. + In this situation, you don't have to wait for the parent file to load; the parent will already be loaded + by the time the child loads.

+ +

When using this method, consider the Flash Player security model. By default, a LocalConnection object + is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection + objects are not allowed unless you call the LocalConnection.allowDomain() method in the + receiving file. However, in Adobe AIR, content in the application security sandbox + (content installed with the AIR application) are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +

Note: The allowDomain() method has changed + from the form it had in ActionScript 1.0 and 2.0. In those earlier versions, + allowDomain was a callback method that you + implemented. In ActionScript 3.0, allowDomain() is a built-in + method of LocalConnection that you call. With this change, allowDomain() + works in much the same way as flash.system.Security.allowDomain().

+ +
flash.net.LocalConnection.allowInsecureDomain()flash.display.LoaderInfo.urlflash.system.Security.allowDomain()
allowInsecureDomain + Specifies one or more domains that can send LocalConnection calls to this LocalConnection object.All parameters specified must be non-null strings. + ArgumentErrorArgumentErrordomainsOne or more strings that name the domains from which + you want to allow LocalConnection calls. There are two special cases + for this parameter: +
  • You can specify the wildcard character "~~" to allow calls from all domains. + Specifying "~~" does not include local hosts.
  • You can specify the string "localhost" to allow calls to this SWF file from SWF files that + are installed locally. Flash Player 8 introduced security restrictions on local SWF files. A SWF file + that is allowed to access the Internet cannot also have access to the local file system. If you + specify "localhost", any local SWF file can access this SWF file. Remember that you must also + designate the calling SWF file as a local-with-networking SWF file at authoring time.
+ +
+ Specifies one or more domains that can send LocalConnection calls to this LocalConnection object. + +

The allowInsecureDomain() method works just like the allowDomain() method, + except that the allowInsecureDomain() method additionally permits SWF files + from non-HTTPS origins to send LocalConnection calls to files from HTTPS origins. This difference + is meaningful only if you call the allowInsecureDomain() method from a + file that was loaded using HTTPS. You must call the allowInsecureDomain() method even + if you are crossing a non-HTTPS/HTTPS boundary within the same domain; by default, LocalConnection calls + are never permitted from non-HTTPS files to HTTPS files, even within the same domain.

+ +

Calling allowInsecureDomain() is not recommended, + because it can compromise the security offered by HTTPS. When you + load a file over HTTPS, you can be reasonably sure that the file + will not be tampered with during delivery over the network. If you + then permit a non-HTTPS file to make LocalConnection calls to the + HTTPS file, you are accepting calls from a file that may in fact have + been tampered with during delivery. This generally requires extra + vigilance because you cannot trust the authenticity of LocalConnection + calls arriving at your HTTPS file.

+ +

By default, files hosted using the HTTPS protocol can be accessed only by other files hosted + using the HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol.

+ +

Using this method to override the default behavior is not recommended, because it compromises HTTPS security. + However, you might need to do so, for example, if you need to permit access to HTTPS SWF files published for + Flash Player 9 or later from HTTP files SWF published for Flash Player 6 or earlier.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
flash.net.LocalConnection.allowDomain()
close + Closes (disconnects) a LocalConnection object.The LocalConnection instance is not connected, so it cannot be closed. + + ArgumentErrorArgumentError + Closes (disconnects) a LocalConnection object. Issue this command when you no longer want the object + to accept commands — for example, when you want to issue a connect() + command using the same connectionName parameter in another SWF file. + + flash.net.LocalConnection.connect()connect + Prepares a LocalConnection object to receive commands that are sent from a send() command + (from the sending LocalConnection object).The value passed to the connectionName parameter must be non-null. + + TypeErrorTypeErrorThis error can occur for three reasons: 1) The string value passed to the connectionName parameter + was null. Pass a non-null value. 2) The value passed to the connectionName parameter + contained a colon (:). Colons are used as special characters to separate the superdomain + from the connectionName string in the send() method, not the + connect()method. 3) The LocalConnection instance is already connected. + + ArgumentErrorArgumentErrorconnectionNameStringA string that corresponds to the connection name specified in the + send() command that wants to communicate with the receiving LocalConnection object. + + + Prepares a LocalConnection object to receive commands that are sent from a send() command + (from the sending LocalConnection object). The object used with the connect() method is + called the receiving LocalConnection object. The receiving and sending objects + must be running on the same client computer. + +

To avoid a race condition, define the methods attached to the + receiving LocalConnection object before + calling this method, as shown in the LocalConnection class example.

+ +

By default, the connectionName argument is resolved into a value of + "superdomain:connectionName", + where superdomain is the superdomain of the file that contains the + connect() command. For example, if the file that contains the + receiving LocalConnection object is located at www.someDomain.com, connectionName + resolves to "someDomain.com:connectionName". (If a file running in Flash Player + is located on the client computer, the value assigned to superdomain is + "localhost".)

+ +

In content running in the application security sandbox in Adobe AIR (content + installed with the AIR application), the runtime uses the string app# followed by the application + ID for the AIR application (defined in the application descriptor file) in place of the superdomain. + For example a connectionName for an application with the application ID com.example.air.MyApp + connectionName resolves to "app#com.example.air.MyApp:connectionName".

+ +

Also by default, Flash Player lets the receiving LocalConnection object accept commands only from + sending LocalConnection objects whose connection name also resolves into a value of + "superdomain:connectionName". In this way, Flash Player makes + it simple for files that are located in the same domain to communicate with each other.

+ +

If you are implementing communication only between files in the same domain, specify a string + for connectionName that does not begin with an underscore (_) and that does not specify + a domain name (for example, "myDomain:connectionName"). Use the same string in the + connect(connectionName) method.

+ +

If you are implementing communication between files in different domains, specifying a string + for connectionName that begins with an underscore (_) makes the file with the + receiving LocalConnection object more portable between domains. Here are the two possible cases:

+ +
  • If the string for connectionNamedoes not begin with an underscore (_), + a prefix is added with the superdomain and a colon (for example, + "myDomain:connectionName"). Although this ensures that your connection does not conflict + with connections of the same name from other domains, any sending LocalConnection objects must + specify this superdomain (for example, "myDomain:connectionName"). + If the file with the receiving LocalConnection object is moved to another domain, the player changes + the prefix to reflect the new superdomain (for example, "anotherDomain:connectionName"). + All sending LocalConnection objects would have to be manually edited to point to the new superdomain.
  • If the string for connectionNamebegins with an underscore (for example, + "_connectionName"), a prefix is not added to the string. This means that + the receiving and sending LocalConnection objects use identical strings for + connectionName. If the receiving object uses allowDomain() + to specify that connections from any domain will be accepted, the file with the receiving LocalConnection + object can be moved to another domain without altering any sending LocalConnection objects.
+ +

For more information, see the discussion in the class overview and the discussion + of connectionName in send(), and also + the allowDomain() and domain entries.

+ +

Note: Colons are used as special characters to separate the superdomain from the + connectionName string. A string for connectionName that contains a colon is + not valid.

+ +

When you use this method , consider the Flash Player + security model. By default, a LocalConnection object + is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection + objects are not allowed unless you call the LocalConnection.allowDomain() method in the + receiving file. You can prevent a file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content. However, in Adobe AIR, + content in the application security sandbox (content installed with the AIR application) + are not restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
flash.net.LocalConnection.send()flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.domain
send + Invokes the method named methodName on a connection that was opened with the + connect(connectionName) method (in the receiving LocalConnection + object).The value of either connectionName or methodName + is null. Pass non-null values for these parameters. + + TypeErrorTypeErrorThis error can occur for one of the following reasons: + 1) The value of either connectionName or methodName + is an empty string. Pass valid strings for these parameters. + 2) The method specified in methodName is restricted. + 3) The serialized message that is being sent is too large (larger than 40K). + + ArgumentErrorArgumentErrorconnectionNameStringCorresponds to the connection name specified in the connect() command + that wants to communicate with the sending LocalConnection object. + + methodNameStringThe name of the method to be invoked in the receiving LocalConnection object. The + following method names cause the command to fail: send, connect, + close, allowDomain, allowInsecureDomain, + client, and domain. + + argumentsAdditional optional parameters to be passed to the specified method. + + + Invokes the method named methodName on a connection that was opened with the + connect(connectionName) method (in the receiving LocalConnection + object). The object used with the send() method is called the sending LocalConnection object. + The SWF files that contain the sending and receiving objects must be running on the same client computer. + +

There is a 40 kilobyte limit to the amount of data you can pass as parameters to this command. + If send() throws an ArgumentError but your syntax is correct, try dividing the + send() requests into multiple commands, each with less than 40K of data.

+ +

As discussed in the connect() entry, the current superdomain in added to + connectionName by default. If you are implementing communication between different domains, + you need to define connectionName in both the sending and receiving LocalConnection + objects in such a way that the current superdomain is not added to connectionName. + You can do this in one of the following two ways:

+ +
  • Use an underscore (_) at the beginning of connectionName in both the sending and + receiving LocalConnection objects. In the file that contains the receiving object, use + LocalConnection.allowDomain() to specify that connections from any domain will be accepted. + This implementation lets you store your sending and receiving files in any domain.
  • Include the superdomain in connectionName in the sending LocalConnection + object — for example, myDomain.com:myConnectionName. In the receiving object, use + LocalConnection.allowDomain() to specify that connections from the specified superdomain + will be accepted (in this case, myDomain.com) or that connections from any domain will be accepted.
+ +

Note: You cannot specify a superdomain in connectionName in the receiving + LocalConnection object — you can do this in only the sending LocalConnection object.

+ +

When you use this method , consider the Flash Player + security model. By default, a LocalConnection object + is associated with the sandbox of the file that created it, and cross-domain calls to LocalConnection + objects are not allowed unless you call the LocalConnection.allowDomain() method in the + receiving file. For SWF content running in the browser, ou can prevent a file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content. However, in Adobe AIR, content in the + application security sandbox (content installed with the AIR application) are not + restricted by these security limitations.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.connect()flash.net.LocalConnection.domainsecurityErrorflash.events:SecurityErrorEventLocalConnection.send() attempted + to communicate with a SWF file from a security sandbox to which the calling + code does not have access. You can work around this in the receiver's + implementation of LocalConnection.allowDomain(). + + LocalConnection.send() attempted + to communicate with a SWF file from a security sandbox to which the calling + code does not have access.statusflash.events:StatusEventIf the value of the level property is "status", + the call was successful; if the value is "error", the call failed. The call can fail + if the receiving SWF file refuses the connection. + + If the value of the level property is "status", + the call was successful; if the value is "error", the call failed.
client + Indicates the object on which callback methods are invoked.ObjectThe client property must be set to a non-null object. + TypeErrorTypeError + Indicates the object on which callback methods are invoked. The default object + is this, the local connection being created. You can set the + client property to another object, and callback methods are + invoked on that other object. + domain + A string representing the domain of the location of the current file.String + A string representing the domain of the location of the current file. + +

In content running in the application security sandbox in Adobe AIR (content + installed with the AIR application), the runtime uses the string app# followed by the application + ID for the AIR application (defined in the application descriptor file) in place of the superdomain. + For example a connectionName for an application with the application ID com.example.air.MyApp + connectionName resolves to "app#com.example.air.MyApp:connectionName".

+ +

In SWF files published for Flash Player 9 or later, the returned string is the exact domain of + the file, including subdomains. For example, if the file is located at www.adobe.com, this command + returns "www.adobe.com".

+ +

If the current file is a local file residing on the client computer running in Flash Player, + this command returns "localhost".

+ +

The most common ways to use this property are to include the domain name of the sending + LocalConnection object as a parameter to the method you plan to invoke in the receiving + LocalConnection object, or to use it with LocalConnection.allowDomain() to accept commands + from a specified domain. If you are enabling communication only between LocalConnection objects + that are located in the same domain, you probably don't need to use this property.

+ +
flash.net.LocalConnection.allowDomain()flash.net.LocalConnection.connect()
isSupported + The isSupported property is set to true if the + LocalConnection class is supported on the current platform, otherwise it is + set to false.Boolean + The isSupported property is set to true if the + LocalConnection class is supported on the current platform, otherwise it is + set to false. + + isPerUserBoolean
NetStream + The NetStream class opens a one-way streaming channel over a NetConnection.flash.events:EventDispatcher + The NetStream class opens a one-way streaming channel over a NetConnection. + +

Use the NetStream class to do the following:

+ +
  • Call NetStream.play() to play a media file from a local disk, a web server, or Flash Media Server.
  • Call NetStream.publish() to publish a video, audio, and data stream to Flash Media Server.
  • Call NetStream.send() to send data messages to all subscribed clients.
  • Call NetStream.send() to add metadata to a live stream.
  • Call NetStream.appendBytes() to pass ByteArray data into the NetStream.
+ +

Note:You cannot play and publish a stream over the same NetStream object.

+ +

Adobe AIR and Flash Player 9.0.115.0 and later versions + support files derived from the standard MPEG-4 container format. These files include F4V, MP4, M4A, MOV, MP4V, 3GP, and 3G2 + if they contain H.264 video, HEAAC v2 encoded audio, or both. H.264 delivers higher quality video at lower bit rates + when compared to the same encoding profile in Sorenson or On2. AAC is a standard audio format defined in the MPEG-4 video standard. + HE-AAC v2 is an extension of AAC that uses Spectral Band Replication (SBR) + and Parametric Stereo (PS) techniques to increase coding efficiency at low bit rates.

+ +

For information about supported codecs and file formats, see the following:

+ +
  • Flash Media Server documentation
  • Exploring Flash Player support for high-definition H.264 video and AAC audio
  • FLV/F4V open specification documents
+ +

Receiving data from a Flash Media Server stream, progressive F4V file, or progressive FLV file

+ +

Flash Media Server, F4V files, and FLV files can send event objects containing data at specific + data points during streaming or playback. You can handle data from a stream or FLV file during playback in two ways:

+ +
  • + Associate a client property with an event handler to receive the data object. + Use the NetStream.client property to assign an object to call specific + data handling functions. The object assigned to the NetStream.client property + can listen for the following data points: onCuePoint(), + onImageData(), onMetaData(), onPlayStatus(), onSeekPoint(), + onTextData(), and onXMPData(). Write procedures within those functions + to handle the data object returned from the stream during playback. + See the NetStream.client property for more information. +
  • + Associate a client property with a subclass of the NetStream class, then write + an event handler to receive the data object. NetStream is + a sealed class, which means that properties or methods cannot be added to a NetStream object + at runtime. However, you can create a subclass of NetStream and define your event handler + in the subclass. You can also make the subclass dynamic and add the event handler to an + instance of the subclass. +
+ +

Wait to receive a NetGroup.Neighbor.Connect event before you use the object replication, direct routing, or posting APIs.

+ +

Note: To send data through an audio file, like an mp3 file, use the Sound class + to associate the audio file with a Sound object. Then, use the Sound.id3 property + to read metadata from the sound file.

+ +
The following example uses a Video object with the NetConnection and + NetStream classes to load and play an FLV file. +

In this example, the code that creates the Video and NetStream objects and calls the + Video.attachNetStream() and NetStream.play() methods is placed + in a handler function. The handler is called only if the + attempt to connect to the NetConnection object is successful; that is, + when the netStatus event returns an info object with a code + property that indicates success. + It is recommended that you wait for a successful connection before you call + NetStream.play().

+ +package { + import flash.display.Sprite; + import flash.events.NetStatusEvent; + import flash.events.SecurityErrorEvent; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + import flash.events.Event; + + public class NetConnectionExample extends Sprite { + private var videoURL:String = "http://www.helpexamples.com/flash/video/cuepoints.flv"; + private var connection:NetConnection; + private var stream:NetStream; + private var video:Video = new Video(); + + public function NetConnectionExample() { + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Stream not found: " + videoURL); + break; + } + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function connectStream():void { + var stream:NetStream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.client = new CustomClient(); + video.attachNetStream(stream); + stream.play(videoURL); + addChild(video); + } + } +} + +class CustomClient { + public function onMetaData(info:Object):void { + trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate); + } + public function onCuePoint(info:Object):void { + trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type); + } +} +
You can get metadata using a function, instead of creating a custom class. The following suggestion, + provided by Bill Sanders, shows how to edit the NetConnectionExample code above to call metadata within a function. In this case, the object + mdata is used to set up the width and height of a video instance video: + + //Place the following in the connectStream() function + //in the NetConnectionExample code + var metaSniffer:Object=new Object(); + stream.client=metaSniffer; //stream is the NetStream instance + metaSniffer.onMetaData=getMeta; + + + // Add the following function within the NetConnectionExample class + private function getMeta (mdata:Object):void + { + video.width=mdata.width/2; + video.height=mdata.height/2; + } +
flash.media.Videoflash.net.NetConnectionappendBytes()play()publish()send()onImageDataonMetaDatamediaTypeData + Dispatched when playing video content and certain type of messages are processed.flash.events.NetDataEventflash.events.NetDataEvent + Dispatched when playing video content and certain type of messages are processed. + +

A NetDataEvent is dispatched for the following messages:

+
  • onCuePoint
  • onImageData
  • onMetaData
  • onPlayStatus (for code NetStream.Play.Complete)
  • onTextData
  • onXMPData
+ +

Note: This event is not dispatched by content running in Flash Player in the browser on Android or Blackberry Tablet OS or + by content running in AIR on iOS.

+ +
onSeekPoint + Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable + point (for example, a video key frame). + Called synchronously from appendBytes() when the append bytes parser encounters a point that it believes is a seekable + point (for example, a video key frame). Use this event to construct a seek point table. The byteCount corresponds to + the byteCount at the first byte of the parseable message for that seek point, and is reset to zero as described above. + To seek, at the event NetStream.Seek.Notify, find the bytes that start at a + seekable point and call appendBytes(bytes). + If the bytes argument is a ByteArray consisting of bytes starting at the seekable point, the video + plays at that seek point. + +

Note: Calls to appendBytes() from within this callback are ignored.

+ +

The onSeekPoint property is a property of the NetStream.client + object. The property is listed in the Events section because it responds to data + coming into the appendBytes() method. + For more information, see the NetStream class description and the + NetStream.client property. You cannot use the addEventListener() + method, or any other EventDispatcher methods, to listen for or process + onSeekPoint as an event. To use onSeekPoint, define a + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods + cannot be added to a NetStream object at runtime. However, you can create a subclass of NetStream + and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function + to an instance of the subclass.
+ +
client
drmStatus + Dispatched when the digital rights management (DRM) encrypted content + begins playing (when the user is authenticated and authorized to play the content).flash.events.DRMStatusEvent.DRM_STATUSflash.events.DRMStatusEvent + Dispatched when the digital rights management (DRM) encrypted content + begins playing (when the user is authenticated and authorized to play the content). +

+ DRMStatusEvent object contains information related to the voucher, such as whether the content + is available offline or when the voucher expires and users can no longer view the content. +

+ +
flash.events.DRMStatusEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()
drmError + Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted + file, encounters a DRM-related error.flash.events.DRMErrorEvent.DRM_ERRORflash.events.DRMErrorEvent + Dispatched when a NetStream object, trying to play a digital rights management (DRM) encrypted + file, encounters a DRM-related error. For example, a DRMErrorEvent object is dispatched when + the user authorization fails. This may be because the user has not purchased the rights to view the content + or because the content provider does not support the viewing application. + + flash.events.DRMErrorEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()drmAuthenticate + Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted + content that requires a user credential for authentication before playing.flash.events.DRMAuthenticateEvent.DRM_AUTHENTICATEflash.events.DRMAuthenticateEvent + Dispatched when a NetStream object tries to play a digital rights management (DRM) encrypted + content that requires a user credential for authentication before playing. + +

+ Use the setDRMAuthenticationCredentials() method of the NetStream object + to authenticate the user. If user authentication failed, the application retries + authentication and dispatches a new DRMAuthenticateEvent event for the NetStream object. +

+ + +
flash.events.DRMAuthenticateEventflash.net.drm.DRMManager.resetDRMVouchers()setDRMAuthenticationCredentials()
onDRMContentData + Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file. + Establishes a listener to respond when AIR extracts DRM content metadata embedded in a media file. + +

A DRMContentData object contains the information needed to obtain + a voucher required to play a DRM-protected media file. Use the DRMManager class to download the voucher with + this information.

+ +

onDRMContentData is a property of the NetStream.client + object. This property is listed in the Events section because it responds to a data + event when preloading embedded data from a local media file. + For more information, see the NetStream class + description. You cannot use the addEventListener() method, or any + other EventDispatcher methods, to listen for, or process onDRMContentData as an event. + Rather, you must define a single + callback function and attach it directly to one of the following objects:

+
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties + or methods cannot be added to a NetStream object at runtime. However, you can create a subclass of + NetStream and define your event handler in the subclass or make the subclass dynamic and add the + event handler function to an instance of the subclass.
+ +
flash.net.drm.DRMContentDatapreloadEmbeddedData()flash.net.drm.DRMManagerflash.net.drm.DRMVoucher
onPlayStatus + Establishes a listener to respond when a NetStream object has completely played a stream. + Establishes a listener to respond when a NetStream object has completely played a stream. + The associated event object provides information in addition to + what's returned by the netStatus event. + You can use this property to trigger actions in your code when a NetStream object + has switched from one stream to another stream in a playlist (as indicated by the + information object NetStream.Play.Switch) + or when a NetStream object has played to the end (as indicated by the information object + NetStream.Play.Complete). + +

onPlayStaus is actually a property of the NetStream.client + object. The property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class + description. You cannot use the addEventListener() method, or any + other EventDispatcher methods, to listen for, or process onPlayStatus as an event. Define a + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that + properties or methods cannot be added to a NetStream object at runtime. Create a subclass of NetStream and + define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function to + an instance of the subclass.
+ +

This event can return an information object with the following properties:

+ + Code propertyLevel propertyMeaningNetStream.Play.Switch"status"The subscriber is switching from one stream to another in a playlist.NetStream.Play.Complete"status"Playback has completed.NetStream.Play.TransitionComplete"status"The subscriber is switching to a new stream as a result of stream bit-rate switching + + +
clientflash.events.NetStatusEvent.NET_STATUSasyncErroronMetaDataonCuePoint
onCuePoint + Establishes a listener to respond when an embedded cue point is reached while playing a video file. + Establishes a listener to respond when an embedded cue point is reached while playing a video file. You can use the listener to trigger actions in your + code when the video reaches a specific cue point, which lets you synchronize other actions in your application with video + playback events. For information about video file formats supported by Flash Media Server, see + the www.adobe.com/go/learn_fms_fileformats_en. + + +

onCuePoint is actually a property of the NetStream.client + object. IThe property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class + description. You cannot use the addEventListener() method, or any + other EventDispatcher methods, to listen for, or process onCuePoint as an event. Define a + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added to a NetStream object + at runtime. Create a subclass of NetStream and define your event handler in the subclass. + You can also make the subclass dynamic and add the event handler function to an instance of the subclass.
+ +

The associated event listener is triggered after a call to the NetStream.play() method, but before the + video playhead has advanced.

+ +

You can embed the following types of cue points in a video file:

+ +
  • A navigation cue point specifies a keyframe within the video file + and the cue point's time property corresponds to that exact keyframe. Navigation cue points are often used as bookmarks + or entry points to let users navigate through the video file.
  • An event cue point specifies a time. The time may or may not correspond to a specific keyframe. + An event cue point usually represents a time in the video when something happens that could be used to trigger other application events.
+ +

The onCuePoint event object has the following properties:

+ + PropertyDescriptionnameThe name given to the cue point when it was embedded in the video file.parametersAn associative array of name and value pair strings specified for this cue point. Any valid string can be used for + the parameter name or value.timeThe time in seconds at which the cue point occurred in the video file during playback.typeThe type of cue point that was reached, either navigation or event. + +

You can define cue points in a video file when you first encode the file, or when you import a video clip in + the Flash authoring tool by using the Video Import wizard.

+ +

The onMetaData event also retrieves information about the cue points in a video file. + However the onMetaData event gets information about all of the cue points + before the video begins playing. The onCuePoint event receives information about a single cue point + at the time specified for that cue point during playback.

+ +

Generally, to have your code respond to a specific cue point at the time it occurs, use + the onCuePoint event to trigger some action in your code.

+ +

You can use the list of cue points provided to the onMetaData event to + let the user start playing the video at predefined points along the video stream. + Pass the value of the cue point's time property to the + NetStream.seek() method to play the video from that cue point.

+ +
The following example shows how you can load external FLV files and respond to metadata and cue points. + Example provided by + ActionScriptExamples.com. + +var video:Video = new Video(); +addChild(video); + +var nc:NetConnection = new NetConnection(); +nc.connect(null); + +var ns:NetStream = new NetStream(nc); +ns.client = {}; +ns.client.onMetaData = ns_onMetaData; +ns.client.onCuePoint = ns_onCuePoint; +ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); + +video.attachNetStream(ns); + +function ns_onMetaData(item:Object):void { + trace("metaData"); + // Resize video instance. + video.width = item.width; + video.height = item.height; + // Center video instance on Stage. + video.x = (stage.stageWidth - video.width) / 2; + video.y = (stage.stageHeight - video.height) / 2; +} + +function ns_onCuePoint(item:Object):void { + trace("cuePoint"); + trace(item.name + "\t" + item.time); +} +
clientonMetaData
onTextData + Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. + Establishes a listener to respond when Flash Player receives text data embedded in a media file that is playing. + The text data + is in UTF-8 format and can contain information about formatting based on the 3GP timed text specification. +

onTextData is actually a property of the NetStream.client + object. The property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. For more information, + see the NetStream class + description. You cannot use the addEventListener() method, or any + other EventDispatcher methods, to listen for, or process onTextData as an event. + Define a callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or + methods cannot be added to a NetStream object at runtime. Create a subclass of + NetStream and define your event handler in the subclass. You can also make the subclass dynamic and add the + event handler function to an instance of the subclass.
+ +

The associated event listener is triggered after a call to the NetStream.play() method, but before the + video playhead has advanced.

+ +

The onTextData event object contains one property for each piece of text data.

+ +
The code in this example uses the Netstream.client property to handle + the callback functions for onTextData and onImageData. + The onImageDataHandler() function uses the onImageData event object + imageData to store the byte array. And, the onTextDataHandler() + function uses the onTextData event object textData to store the pieces of + text data (each piece of data is a property of the textData object). +

You need to substitute a real location to a media file with text or image + metadata for the location "yourURL" in the code.

+

You can also handle image and text data using a custom class. See the article + Handling metadata and cue points in Flash video for more information and examples.

+ +package { + import flash.display.*; + import flash.net.*; + import flash.media.*; + import flash.system.*; + import flash.events.*; + + public class OnTextDataExample extends Sprite { + + public function OnTextDataExample():void { + + var customClient:Object = new Object(); + customClient.onImageData = onImageDataHandler; + customClient.onTextData = onTextDataHandler; + + var my_nc:NetConnection = new NetConnection(); + my_nc.connect(null); + var my_ns:NetStream = new NetStream(my_nc); + my_ns.play("yourURL"); + my_ns.client = customClient; + + var my_video:Video = new Video(); + my_video.attachNetStream(my_ns); + addChild(my_video); + + } + + public function onImageDataHandler(imageData:Object):void { + + trace("imageData length: " + imageData.data.length); + var imageloader:Loader = new Loader(); + imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object. + addChild(imageloader); + } + + + public function onTextDataHandler(textData:Object):void { + + trace("--- textData properties ----"); + var key:String; + + for (key in textData) { + trace(key + ": " + textData[key]); + } + } + + } + +} + +
NetConnectionclientasyncErrorplay()onImageData
onImageData + Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is + playing. + Establishes a listener to respond when Flash Player receives image data as a byte array embedded in a media file that is + playing. The image data can produce either JPEG, PNG, or GIF content. Use the + flash.display.Loader.loadBytes() method to load the byte array into a display object. +

onImageData is actually a property of the NetStream.client + object. The property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. For more information, see the NetStream class + description. You cannot use the addEventListener() method, or any + other EventDispatcher methods, to listen for, or process onImageData as an event. Define a single + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods cannot be added + to a NetStream object at runtime. Create a subclass of NetStream and define your event handler in the subclass. + You can also make the subclass dynamic and add the event handler function to an instance of the subclass.
+ +

The associated event listener is triggered after a call to the NetStream.play() method, but before the + video playhead has advanced.

+ +

The onImageData event object contains the image data as a byte array sent through an AMF0 data channel.

+ +
The code in this example uses the Netstream.client property to handle + the callback functions for onTextData and onImageData. + The onImageDataHandler() function uses the onImageData event object + imageData to store the byte array. And, the onTextDataHandler() + function uses the onTextData event object textData to store the pieces of + text data (each piece of data is a property of the textData object). +

You need to substitute a real location to a media file with text or image + metadata for the location "yourURL" in the code.

+

You can also handle image and text data using a custom class. See the article + Handling metadata and cue points in Flash video for more information and examples.

+ +package { + import flash.display.*; + import flash.net.*; + import flash.media.*; + import flash.system.*; + import flash.events.*; + + public class OnTextDataExample extends Sprite { + + public function OnTextDataExample():void { + + var customClient:Object = new Object(); + customClient.onImageData = onImageDataHandler; + customClient.onTextData = onTextDataHandler; + + var my_nc:NetConnection = new NetConnection(); + my_nc.connect(null); + var my_ns:NetStream = new NetStream(my_nc); + my_ns.play("yourURL"); + my_ns.client = customClient; + + var my_video:Video = new Video(); + my_video.attachNetStream(my_ns); + addChild(my_video); + + } + + public function onImageDataHandler(imageData:Object):void { + + trace("imageData length: " + imageData.data.length); + var imageloader:Loader = new Loader(); + imageloader.loadBytes(imageData.data); // imageData.data is a ByteArray object. + addChild(imageloader); + } + + + public function onTextDataHandler(textData:Object):void { + + trace("--- textData properties ----"); + var key:String; + + for (key in textData) { + trace(key + ": " + textData[key]); + } + } + + } + +} + +
NetConnectionflash.display.Loader.loadBytes()clientasyncErrorplay()onTextData
onMetaData + Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. + Establishes a listener to respond when Flash Player receives descriptive information embedded in the video being played. + For information about video file formats supported by Flash Media Server, see + the www.adobe.com/go/learn_fms_fileformats_en. + +

onMetaData is actually a property of the NetStream.client + object. The property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. + For more information, see the NetStream class description and the + NetStream.client property. You cannot use the addEventListener() + method, or any other EventDispatcher methods, to listen for or process + onMetaData as an event. Define a single + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods + cannot be added to a NetStream object at runtime. You can create a subclass of NetStream + and define your event handler in the subclass. You can also make the subclass dynamic and add the event handler function + to an instance of the subclass.
+ +

The Flash Video Exporter utility (version 1.1 or later) embeds + a video's duration, creation date, data rates, and other information into the video file itself. + Different video encoders embed different sets of meta data.

+ +

The associated event listener is triggered after a call to the NetStream.play() method, + but before the video playhead has advanced.

+ +

In many cases, the duration value embedded in stream metadata approximates the actual duration + but is not exact. In other words, it does not always match the value of the NetStream.time property + when the playhead is at the end of the video stream.

+

The event object passed to the onMetaData event handler contains one property for each piece of data.

+ +
The following example shows how you can load external FLV files and respond to metadata and cue points. + Example provided by + ActionScriptExamples.com. + +var video:Video = new Video(); +addChild(video); + +var nc:NetConnection = new NetConnection(); +nc.connect(null); + +var ns:NetStream = new NetStream(nc); +ns.client = {}; +ns.client.onMetaData = ns_onMetaData; +ns.client.onCuePoint = ns_onCuePoint; +ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); + +video.attachNetStream(ns); + +function ns_onMetaData(item:Object):void { + trace("metaData"); + // Resize video instance. + video.width = item.width; + video.height = item.height; + // Center video instance on Stage. + video.x = (stage.stageWidth - video.width) / 2; + video.y = (stage.stageHeight - video.height) / 2; +} + +function ns_onCuePoint(item:Object):void { + trace("cuePoint"); + trace(item.name + "\t" + item.time); +} +
NetConnectionclientasyncErroronCuePointplay()time
onXMPData + Establishes a listener to respond when Flash Player receives information specific to Adobe + Extensible Metadata Platform (XMP) embedded in the video being played. + Establishes a listener to respond when Flash Player receives information specific to Adobe + Extensible Metadata Platform (XMP) embedded in the video being played. + For information about video file formats supported by Flash Media Server, see + the www.adobe.com/go/learn_fms_fileformats_en. + +

onXMPData is actually a property of the NetStream.client + object. The property is listed in the Events section because it responds to a data + event, either when streaming media using Flash Media Server or during FLV file playback. + For more information, see the NetStream class description and the + NetStream.client property. You cannot use the addEventListener() + method, or any other EventDispatcher methods, to listen for or process + onMetaData as an event. Define a + callback function and attach it to one of the following objects:

+ +
  • The object that the client property of a NetStream instance references.
  • An instance of a NetStream subclass. NetStream is a sealed class, which means that properties or methods + cannot be added to a NetStream object at runtime. + However, you can create a subclass of NetStream and define your event handler in the subclass. + You can also make the subclass dynamic and add the event handler function to an instance of the subclass.
+ +

The associated event listener is triggered after a call to the NetStream.play() method, + but before the video playhead has advanced.

+ +

The object passed to the onXMPData() event handling function has one data + property, which is a string. The string is generated from + a top-level UUID box. (The 128-bit UUID of the top level box is BE7ACFCB-97A9-42E8-9C71-999491E3AFAC.) This + top-level UUID box contains exactly one XML document represented as a null-terminated UTF-8 string.

+ +
flash.net.NetConnectionclientasyncErroronCuePointplay()time
netStatus + Dispatched when a NetStream object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent + Dispatched when a NetStream object is reporting its status or error condition. + The netStatus event contains an info property, + which is an information object that contains specific information about the event, + such as if a connection attempt succeeded or failed. + flash.events.NetStatusEvent.infoioError + Dispatched when an input or output error occurs that causes a network operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input or output error occurs that causes a network operation to fail. + asyncError + Dispatched when an exception is thrown asynchronously &#x2014; that is, + from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent + Dispatched when an exception is thrown asynchronously — that is, + from native asynchronous code. + This event is dispatched when a server calls a method on the client that is not defined. + + onPlayStatusonMetaDatastatus + Dispatched when the application attempts to play content encrypted with digital rights management (DRM), + by invoking the NetStream.play() method.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when the application attempts to play content encrypted with digital rights management (DRM), + by invoking the NetStream.play() method. The value of the status code property will be + "DRM.encryptedFLV". + + play()NetStream + Creates a stream that you can use to play media files and send data over a NetConnection object.The NetConnection instance is not connected. + + ArgumentErrorArgumentErrorconnectionflash.net:NetConnectionA NetConnection object. + + peerIDStringconnectToFMSThis optional parameter is available in Flash Player 10 and later, for use with RTMFP connections. + (If the value of the NetConnection.protocol property + is not "rtmfp", this parameter is ignored.) Use one of the following values: + +
  • To connect to Flash Media Server, specify NetStream.CONNECT_TO_FMS.
  • To publish directly to peers, specify NetStream.DIRECT_CONNECTIONS.
  • To play directly from a specific peer, specify that peer's identity (see NetConnection.nearID + and NetStream.farID).
  • (Flash Player 10.1 or AIR 2 or later) To publish or play a stream in a peer-to-peer multicast group, + specify a groupspec string (see the GroupSpecifier class).
+ +

In most cases, a groupspec has the potential to use the network uplink on the local system. In this case, + the user is asked for permission to use the computer's network resources. If the user allows this + use, a NetStream.Connect.Success NetStatusEvent is sent to the NetConnection's event + listener. If the user denies permission, a NetStream.Connect.Rejected event is sent. + When specifying a groupspec, until a NetStream.Connect.Success event is received, it is an error to use any method + of the NetStream object, and an exception is raised.

+ + +

If you include this parameter in your constructor statement but pass a value of null, + the value is set to "connectToFMS".

+ +
+ Creates a stream that you can use to play media files and send data over a NetConnection object. + + The following code shows a connection to download and display, progressively, a video assigned to the + variable videoURL: + + var my_nc:NetConnection = new NetConnection(); + my_nc.connect(null); + var my_ns:NetStream = new NetStream(my_nc); + my_ns.play(videoURL); + var my_video:Video = new Video(); + my_video.attachNetStream(my_ns); + addChild(my_video); + The following code shows a connection to stream and display a video (assigned to the + variable videoURL) on a remote Flash Media Server instance specified in the connect() + command: + + var my_nc:NetConnection = new NetConnection(); + my_nc.connect("rtmp://www.yourfmsserver.com/someappname"); + var my_ns:NetStream = new NetStream(my_nc, NetStream.CONNECT_TO_FMS); + my_ns.play(videoURL); + var my_video:Video = new Video(); + my_video.attachNetStream(my_ns); + addChild(my_video); +
CONNECT_TO_FMSDIRECT_CONNECTIONSfarIDflash.media.Video.attachCamera()flash.net.GroupSpecifierflash.net.GroupSpecifier.groupspecWithAuthorizations()flash.net.GroupSpecifier.groupspecWithoutAuthorizations()flash.net.GroupSpecifier.multicastEnabledflash.net.NetConnectionflash.net.NetConnection.nearIDflash.net.NetConnection.protocolflash.net.NetGroupflash.events.NetStatusEvent.info.code="NetStream.Connect.Rejected"flash.events.NetStatusEvent.info.code="NetStream.Connect.Success"
appendBytesAction + Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag.netStreamAppendBytesActionString + Indicates a timescale discontinuity, flushes the FIFO, and tells the byte parser to expect a file header or the beginning of an FLV tag. + +

+ Calls to NetStream.seek() flush the NetStream buffers. The byte parser remains in flushing mode until you + call appendBytesAction() and pass the RESET_BEGIN or RESET_SEEK argument. + Capture the "NetStream.Seek.Notify" event to call appendBytesAction() after a seek. + A new file header can support playlists and seeking without calling NetStream.seek(). +

+ +

+ You can also call this method to reset the byte counter for the onSeekPoint()) callback. +

+ + +
appendBytes()seek()flash.net.NetStreamAppendBytesAction
appendBytes + Passes a ByteArray into a NetStream for playout.bytesflash.utils:ByteArray + Passes a ByteArray into a NetStream for playout. Call this method on a NetStream in "Data Generation Mode". To put a NetStream into + Data Generation Mode, call NetStream.play(null) on a NetStream created on a NetConnection connected to null. + Calling appendBytes() on a NetStream that isn't in Data Generation Mode is an error and raises an exception. + +

+ The byte parser understands an FLV file with a header. + After the header is parsed, appendBytes() expects all future calls to be continuations + of the same real or virtual file. Another header is not expected unless + appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) is called. +

+ +

+ A NetStream object has two buffers: the FIFO from appendBytes() to the NetStream, + and the playout buffer. The FIFO is the partial-FLV-tag reassembly buffer and contains no more than one incomplete FLV tag. + Calls to NetStream.seek() flush both buffers. + After a call to seek(), call appendBytesAction() to reset the timescale to begin at the timestamp of the next appended message. +

+ +

+ Each call to appendBytes() adds bytes into the FIFO until an FLV tag is complete. + When an FLV tag is complete, it moves to the playout buffer. A call to appendBytes() can write multiple FLV tags. + The first bytes complete an existing FLV tag (which moves to the playout buffer). Complete FLV tags move to the playout buffer. + Remaining bytes that don’t form a complete FLV tag go into the FIFO. Bytes in the FIFO are either completed by a call to appendBytes() + or flushed by a call to appendBytesAction() with the RESET_SEEK or RESET_BEGIN argument. +

+ +

Note: The byte parser may not be able to completely decode a call to appendBytes() until a + subsequent call to appendBytes() is made.

+ +
appendBytesAction()seek()
attachAudio + Attaches an audio stream to a NetStream object from a Microphone + object passed as the source."null" + microphoneflash.media:MicrophoneThe source of the audio stream to be transmitted. + + + Attaches an audio stream to a NetStream object from a Microphone + object passed as the source. This method is available + only to the publisher of the specified stream. + +

Use this method with Flash Media Server to send live audio to the server. + Call this method before or after you call the publish() method. +

+ +

Set the Microphone.rate property to match + the rate of the sound capture device. Call setSilenceLevel() to set the silence level threshold. + To control the sound properties (volume and panning) of + the audio stream, use the Microphone.soundTransform property.

+ +
+     var nc:NetConnection = new NetConnection();
+     nc.connect("rtmp://server.domain.com/app");
+     var ns:NetStream = new NetStream(nc);
+     
+     var live_mic:Microphone = Microphone.get();
+     live_mic.rate = 8;
+     live_mic.setSilenceLevel(20,200);
+     
+     var soundTrans:SoundTransform = new SoundTransform();
+     soundTrans.volume = 6;
+     live_mic.soundTransform = soundTrans;
+     
+     ns.attachAudio(live_mic);
+     ns.publish("mic_stream","live")
+     
+ +

To hear the audio, call the NetStream.play() method and call DisplayObjectContainer.addChild() + to route the audio to an object on the display list. +

+ +
play()flash.media.Microphoneflash.display.DisplayObjectContainer.addChild()
attachCamera + Starts capturing video from a camera, or stops capturing if + theCamera is set to null.theCameraflash.media:CameraThe source of the video transmission. Valid values are a Camera object + (which starts capturing video) and null. If you pass null, + the application stops capturing video, and any additional parameters you send are ignored. + + snapshotMillisecondsint-1Specifies whether the video stream is continuous, + a single frame, or a series of single frames used to create time-lapse photography. + +
  • If you omit this parameter, the application captures all video until you pass + a value of null to attachCamera.
  • If you pass 0, the application captures only a single video frame. Use this value + to transmit "snapshots" within a preexisting stream. Flash Player + or AIR interprets invalid, negative, or nonnumeric arguments as 0.
  • If you pass a positive number, the application captures a single video frame and then appends a pause + of the specified length as a trailer on the snapshot. Use this value to create time-lapse + photography effects.
+ + +
+ Starts capturing video from a camera, or stops capturing if + theCamera is set to null. + This method is available only to the publisher of the specified stream. + +

This method is intended for use with Flash Media Server; + for more information, see the class description.

+ +

After attaching the video source, you must call NetStream.publish() + to begin transmitting. Subscribers who want to display the video + must call the NetStream.play() and Video.attachCamera() methods + to display the video on the stage.

+ +

You can use snapshotMilliseconds to send a single snapshot + (by providing a value of 0) or a series of snapshots — in effect, + time-lapse footage — by providing a positive number that adds a trailer + of the specified number of milliseconds to the video feed. The trailer + extends the display time of the video message. By repeatedly + calling attachCamera() with a positive value for snapshotMilliseconds, + the sequence of alternating snapshots and trailers creates time-lapse footage. + For example, you could capture one frame per day and append it to a video file. + When a subscriber plays the file, each frame remains onscreen for the specified + number of milliseconds and then the next frame is displayed.

+ +

The purpose of the snapshotMilliseconds parameter is different + from the fps parameter you can set with Camera.setMode(). When you specify + snapshotMilliseconds, you control how much time elapses between recorded frames. When + you specify fps using Camera.setMode(), you are + controlling how much time elapses during recording and playback.

+ +

For example, suppose you want to take a snapshot every 5 minutes for a total + of 100 snapshots. You can do this in two ways:

+ +
  • You can issue a NetStream.attachCamera(myCamera, 500) command + 100 times, once every 5 minutes. This takes 500 minutes to record, but the resulting file + will play back in 50 seconds (100 frames with 500 milliseconds between frames).
  • You can issue a Camera.setMode() command with an fps value + of 1/300 (one per 300 seconds, or one every 5 minutes), and then issue a + NetStream.attachCamera(source) command, letting the camera capture continuously + for 500 minutes. The resulting file will play back in 500 minutes — the same length of time + that it took to record — with each frame being displayed for 5 minutes.
+ +

Both techniques capture the same 500 frames, and both approaches are useful; + the approach to use depends primarily on your playback requirements. For example, + in the second case, you could be recording audio the entire time. Also, both files + would be approximately the same size.

+ +
attach + Attaches a stream to a new NetConnection object.connectionflash.net:NetConnection + Attaches a stream to a new NetConnection object. Call this method to attach a NetStream to a new NetConnection object + after a connection has dropped and been reconnected. Flash Player and AIR resume streaming from the playback point when + the connection was lost.You can also use this method to implement load balancing. + +

This method requires Flash Media Server version 3.5.3 or later.

+ +

To use this method to implement stream reconnection, see the + Flash Media Server 3.5.3 documentation.

+ +

To use this method to implement load balancing, do the following:

+ +
  1. Attach a connected stream to a NetConnection object on another server.
  2. After the stream is successfully attached to the new connection, call NetConnection.close() + on the prior connection to prevent data leaks.
  3. Call NetStream.play2() and set the value of NetStreamPlayOptions.transition to RESUME. + Set the rest of the NetStreamPlayOptions properties to the same values you used when you originally called + NetStream.play() or NetStream.play2() to start the stream.
+ + +
play2()NetStreamPlayOptions.transition
close + Stops playing all data on the stream, sets the time property to 0, + and makes the stream available for another use. + Stops playing all data on the stream, sets the time property to 0, + and makes the stream available for another use. This method also deletes the local copy + of a video file that was downloaded through HTTP. Although the application deletes the + local copy of the file that it creates, a copy might persist in the + cache directory. If you must completely prevent caching or local storage of the video file, + use Flash Media Server. + +

+ When using Flash Media Server, this method is invoked implicitly when you call + NetStream.play() from a publishing stream or + NetStream.publish() from a subscribing stream. + Please note that: +

+ +
  • + If close() is called from a publishing stream, the stream + stops publishing and the publisher can now use the stream for another purpose. + Subscribers no longer receive anything that was being published on the stream, + because the stream has stopped publishing. +
  • + If close() is called from a subscribing stream, the stream + stops playing for the subscriber, and the subscriber can use the stream for + another purpose. Other subscribers are not affected. +
  • + You can stop a subscribing stream from playing, without closing the stream + or changing the stream type by using flash.net.NetStream.play(false). +
+ + + +
pause()play()publish()
onPeerConnect + + Invoked when a peer-publishing stream matches a peer-subscribing stream.Booleansubscriberflash.net:NetStream + + Invoked when a peer-publishing stream matches a peer-subscribing stream. Before the subscriber is + connected to the publisher, call this method to allow the ActionScript code fine access control for + peer-to-peer publishing. The following code shows an example of how to create a callback function for this method: + + var c:Object = new Object; + c.onPeerConnect = function(subscriber:NetStream):Boolean { + if (accept) + return true; + else + return false; + }; + m_netStream.client = c; + + +

If a peer-publisher does not implement this method, all peers are allowed to play any published content.

+ + +
pause + Pauses playback of a video stream. + Pauses playback of a video stream. Calling this method does nothing if the video + is already paused. To resume play after pausing a video, call resume(). + To toggle between pause and play (first pausing the video, then resuming), call + togglePause(). + +

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer when NetStream.pause() is called. + This behavior is called "smart pause". Before Flash Player 9.0.115.0, Flash Player waited for the buffer to fill up before resuming + playback, which often caused a delay.

+

Note: For backwards compatibility, the "NetStream.Buffer.Flush" event (see the NetStatusEvent.info + property) still fires, although the server does not flush the buffer.

+

For a single pause, the NetStream.bufferLength property has a limit of either 60 seconds + or twice the value of NetStream.bufferTime, whichever value is higher. For example, if + bufferTime is 20 seconds, Flash Player buffers until NetStream.bufferLength + is the higher value of either 20~~2 (40), or 60, so in this case it buffers until bufferLength is 60. + If bufferTime is 40 seconds, Flash Player buffers until bufferLength is the higher value + of 40~~2 (80), or 60, so in this case it buffers until bufferLength is 80 seconds.

+ +

The bufferLength property also has an absolute limit. + If any call to pause() causes bufferLength + to increase more than 600 seconds or the value of bufferTime ~~ 2, whichever is higher, Flash Player + flushes the buffer and resets bufferLength to 0. For example, if + bufferTime is 120 seconds, Flash Player flushes the buffer + if bufferLength reaches 600 seconds; if bufferTime is 360 seconds, + Flash Player flushes the buffer if bufferLength reaches 720 seconds.

+ +

Tip: You can use NetStream.pause() in code to buffer data while viewers are watching + a commercial, for example, and then unpause when the main video starts.

+ + +
close()play()resume()togglePause()bufferLengthbufferTimeflash.events.NetStatusEvent.info
play2 + Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected.paramflash.net:NetStreamPlayOptions + Switches seamlessly between files with multiple bit rates and allows a NetStream to resume when a connection is dropped and reconnected. + +

This method is an enhanced version of NetStream.play(). Like the play() method, the play2() method begins + playback of a media file or queues up media files to create a playlist. When used with Flash Media Server, it can also + request that the server switch to a different media file. The transition occurs seamlessly in the client application. The following features + use play2() stream switching:

+ +

Dynamic streaming

+ +

Dynamic streaming (supported in Flash Media Server 3.5 and later) lets you serve a stream encoded at multiple bit rates. As a viewer's network conditions change, + they receive the bitrate that provides the best viewing experience. Use the NetStreamInfo class to monitor network conditions and + switch streams based on the data. You can also switch streams for clients with different capabilities. + For more information, see "Dynamic streaming" in the + "Adobe Flash Media Server Developer Guide".

+ +

Adobe built a custom ActionScript class called DynamicStream that extends the NetStream class. You can use the DynamicStream class + to implement dynamic streaming in an application instead of writing your own code to detect network conditions. Even if you choose to write your own + dynamic streaming code, use the DynamicStream class as a reference implementation. Download the class and the class documentation at the + Flash Media Server tools and downloads page.

+ +

Stream reconnecting

+ +

Stream reconnecting (supported in Flash Media Server 3.5.3 and later) lets users to experience media uninterrupted even when they lose their connection. + The media uses the buffer to play while your ActionScript logic reconnects to Flash Media Server. After reconnection, call NetStream.attach() + to use the same NetStream object with the new NetConnection. Use the NetStream.attach(), NetStreamPlayTransitions.RESUME, + and NetStreamPlayTrasitions.APPEND_AND_WAIT APIs to reconnect a stream. For more information, + see the Flash Media Server 3.5.3 documentation.

+ +
play()attach()NetStreamPlayOptionsNetStreamPlayTransitions
play + Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server.Local untrusted SWF files cannot communicate with + the Internet. You can work around this restriction by reclassifying this SWF file + as local-with-networking or trusted. + + SecurityErrorSecurityErrorAt least one parameter must be specified. + + ArgumentErrorArgumentErrorThe NetStream Object is invalid. This may be due to a failed NetConnection. + + ErrorErrorarguments

Play a local file

+ + +

+ The location of a media file. Argument can be a String, a URLRequest.url + property, or a variable referencing either. In Flash Player and in AIR content outside the application + security sandbox, you can play local video files that are stored in the same directory as the SWF file or in a + subdirectory; however, you can't navigate to a higher-level directory. +

+ +

+ With AIR content in the application security sandbox, the path you specify for the media file is relative to the SWF + file's directory. However, you cannot navigate above the SWF file's directory. Do not specify a full path since + AIR treats it as a relative path. +

+ +

Play a file from Flash Media Server

+ + NameRequiredDescriptionname:ObjectRequired The name of a recorded file, + an identifier for live data published by NetStream.publish(), + or false. + If false, the stream stops playing and any additional parameters + are ignored. For more information on the filename syntax, see the file format table following this table.start:NumberOptional The start time, in seconds. Allowed values are -2, -1, 0, + or a positive number. The default value is -2, which looks + for a live stream, then a recorded stream, and if it finds + neither, opens a live stream. If -1, plays only a live stream. + If 0 or a positive number, plays a recorded stream, beginning + start seconds in. + len:Number Optional if start is specified. The duration of the playback, in seconds. + Allowed values are -1, 0, or a positive number. + The default value is -1, + which plays a live or recorded stream until it ends. + If 0, plays a single frame that is + start + seconds from the beginning of a recorded stream. + If a positive number, plays a live or recorded stream for + len seconds. + reset:Object Optional if len is specified. Whether to clear a playlist. + The default value is 1 or true, which clears any previous + play calls and plays name immediately. + If 0 or false, adds the stream to a playlist. + If 2, maintains the playlist and returns all stream + messages at once, rather than at intervals. + If 3, clears the playlist and returns all stream messages + at once. + + +

+ You can play back the file formats described in the following table. The syntax differs depending on the file format. +

+ + File formatSyntaxExampleFLVSpecify the stream name (in the "samples" directory) as a string without a filename extension.ns.play("samples/myflvstream");mp3 or ID3Specify the stream name (in the "samples" directory) as a string with the prefix mp3: or id3: without a filename extension.

ns.play("mp3:samples/mymp3stream");

+

ns.play("id3:samples/myid3data");

MPEG-4-based files (such as F4V and MP4)Specify the stream name (in the "samples" directory) as a string with the prefix mp4: + The prefix indicates to the server that the file contains H.264-encoded video and AAC-encoded audio within + the MPEG-4 Part 14 container format. If the file on the server has a file extension, specify it.

ns.play("mp4:samples/myvideo.f4v");

+

ns.play("mp4:samples/myvideo.mp4");

+

ns.play("mp4:samples/myvideo");

+

ns.play("mp4:samples/myvideo.mov");

RAWSpecify the stream name (in the "samples" directory) as a string with the prefix raw:ns.play("raw:samples/myvideo");
+ +

Enable Data Generation Mode

+ +

+ To enable "Data Generation Mode", pass the value null to a NetStream created on a NetConnection connected to null. + In this mode, call appendBytes() to deliver data to the NetStream. + (Passing null also resets the byte counter for the onSeekPoint() callback.) +

+ + +
+ Plays a media file from a local directory or a web server; plays a media file or a live stream from Flash Media Server. + Dispatches a NetStatusEvent object to report status and error messages. + +

For information about supported codecs and file formats, see the following:

+ +
  • Flash Media Server documentation
  • Exploring Flash Player support for high-definition H.264 video and AAC audio
  • FLV/F4V open specification documents
+ +

Workflow for playing a file or live stream

+ +
  1. Create a NetConnection object and call NetConnection.connect(). +

    To play a file from a local directory or web server, pass null.

    +

    To play a recorded file or live stream from Flash Media Server, pass the URI of a Flash Media Server application.

  2. Call NetConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler) to listen for NetStatusEvent events.
  3. On "NetConnection.Connect.Success", create a NetStream object and pass the NetConnection object to the constructor.
  4. Create a Video object and call Video.attachNetStream() and pass the NetStream object.
  5. Call NetStream.play(). +

    To play a live stream, + pass the stream name passed to the NetStream.publish() method.

    +

    To play a recorded file, pass the file name.

  6. Call addChild() and pass the Video object to display the video.
+ +

Note:To see sample code, scroll to the example at the bottom of this page.

+ +

Enable Data Generation Mode

+ +

+ Call play(null) to enable "Data Generation Mode". In this mode, call the appendBytes() method to deliver + data to the NetStream. Use Data Generation Mode to stream content over HTTP from the Adobe HTTP Dynamic Streaming Origin Module on an Apache HTTP Server. + HTTP Dynamic Streaming lets clients seek quickly to any point in a file. The Open Source Media Framework (OSMF) + supports HTTP Dynamic Streaming for vod and live streams. For examples of how to use NetStream Data Generation Mode, download the + OSMF source. + For more information about HTTP Dynamic Streaming, see + HTTP Dynamic Streaming. +

+ +

+ When you use this method without Flash Media Server, there are security considerations. A file in the local-trusted or + local-with-networking sandbox can load and play a video file from the remote sandbox, but cannot access + the remote file's data without explicit permission in the form of a URL policy file. + Also, you can prevent a SWF file running in Flash Player from using this method + by setting the allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content. For more information related to security, see the Flash Player Developer Center Topic: + Security. +

+ +
Flash Media Server + This example plays a recorded F4V file from the "samples" directory, starting at + the beginning, for up to 100 seconds. With MPEG-4 files, if the file on the server has a filename extension + the play() method must specify a filename extension. + + ns.play("mp4:samples/record1.f4v", 0, 100, true); + + + Flash Media Server + This example plays a live FLV stream published by a client, from beginning to end, starting + immediately: + + ns.play("livestream"); + + + + The following example shows how to load an external FLV file: + +var MyVideo:Video = new Video(); +addChild(MyVideo); + +var MyNC:NetConnection = new NetConnection(); +MyNC.connect(null); + +var MyNS:NetStream = new NetStream(MyNC); +MyNS.play("http://www.helpexamples.com/flash/video/clouds.flv"); + +MyVideo.attachNetStream(MyNS); + +//the clouds.flv video has metadata we're not using, so create +//an error handler to ignore the message generated by the runtime +//about the metadata +MyNS.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); + +function asyncErrorHandler(event:AsyncErrorEvent):void +{ + //ignore metadata error message +} +
DisplayObjectContainer.addChild()checkPolicyFileappendBytes()statusflash.events:StatusEventDispatched when attempting to play content encrypted with + digital rights management (DRM). The value of the code property is + "DRM.encryptedFLV". + + Dispatched when attempting to play content encrypted with + digital rights management (DRM).
preloadEmbeddedData + Extracts any DRM metadata from a locally stored media file.paramflash.net:NetStreamPlayOptionsA NetStreamPlayOptions describing the options to use while processing the content file. + + + Extracts any DRM metadata from a locally stored media file. + +

Use preloadEmbeddedMetaData() as the first step in downloading and caching the DRM vouchers + needed for offline playback. When embedded DRM metadata is detected in a media file, a DRMContentData object is passed + to the NetStream client onDRMContentData function. This DRMContentData object contains the information + needed to obtain the voucher required to play the content. Pass the DRMContentDataObject to the DRMManager + loadVoucher() method to download the voucher.

+ +

The steps for preloading a DRM voucher include:

+
  • +

    Create a new NetStream object for preloading the metadata.

    +
  • Assign a callback function to the onDRMContentData property of the NetStream client.
  • Create a new NetStreamPlayOptions object and set its streamName property to the the URL string of the local video file.
  • Call preloadEmbeddedMetadata(), passing in the NetStreamPlayOptions object.
  • In response to the onDRMContentData callback, call the DRMManager loadVoucher() method, passing + in the DRMContentData object. If the authenticationMethod property of the DRMContentData object has the value, + userNameAndPassWord, authenticate the user on the media rights server before loading the voucher.
  • Close the NetStream used for preloading.
+ +

Note: To use the same NetStream object to both preload metadata and play content, + wait for the onPlayStatus call generated by the preload operation before starting playback.

+ +

Downloaded vouchers are stored in a local cache. Playing content online also downloads and + caches vouchers. When a DRM-protected content file is viewed, a cached + voucher is retrieved from the local store automatically. Use the DRMManager to manage the + voucher cache.

+ +

Notes: Preloading DRM metadata through HTTP, HTTPS, or RTMP connections is not supported. You can only + preload metadata from files stored on the file system.

+ +
onDRMContentDataflash.net.drm.DRMContentDataflash.net.drm.DRMManager.loadVoucher()flash.net.drm.DRMVoucherclient
publish + Sends streaming audio, video, and data messages from a client to Flash Media Server, + optionally recording the stream during transmission.nameStringnullA string that identifies the stream. Clients that subscribe to this stream pass + this name when they call NetStream.play(). Don't follow the stream name with a "/". For example, don't use + the stream name "bolero/". + +

+ You can record files in the formats described in the following table (you cannot use publish() for MP3 format files). + The syntax differs depending on the file format.

+

+ File formatSyntaxExampleFLVSpecify the stream name as a string without a filename extension.ns.publish("myflvstream");MPEG-4-based files (such as F4V or MP4)Specify the stream name as a string with the prefix mp4: with or without the filename extension. + Flash Player doesn't encode using H.264, but Flash Media Server can record any codec in the F4V container. Flash Media Live Encoder + can encode using H.264. + ns.publish("mp4:myvideo.f4v") + ns.publish("mp4:myvideo");RAWSpecify the stream name as a string with the prefix raw:ns.publish("raw:myvideo"); +

+ +
typeStringnullA string that specifies how to publish the stream. + Valid values are "record", "append", "appendWithGap", and "live". + The default value is "live". +
  • If you pass "record", the server publishes and records live data, + saving the recorded data to a new file with a name matching the value passed + to the name parameter. If the file exists, it is overwritten.
  • If you pass "append", the server publishes and records live data, + appending the recorded data to a file with a name that matches the value passed + to the name parameter. If no file matching the name parameter is found, it is created.
  • If you pass "appendWithGap", additional + information about time coordination is passed to help the server determine the correct transition point when dynamic streaming.
  • If you omit this parameter or pass "live", the server publishes live data without + recording it. If a file with a name that matches the value passed + to the name parameter exists, it is deleted.
+ + + +
+ Sends streaming audio, video, and data messages from a client to Flash Media Server, + optionally recording the stream during transmission. This method dispatches a NetStatusEvent object with information about the stream. + Before you call NetStream.publish(), capture the "NetConnection.Connect.Success" event + to verify that the application has successfully connected to Flash Media Server. + +

While publishing, you can record files in FLV or F4V format. If you record a file in F4V format, + use a flattener tool to edit or play the file in another application. + To download the tool, see + www.adobe.com/go/fms_tools.

+ +

Note:Do not use this method to play a stream. To play a stream, call the NetStream.play() method.

+ +

Workflow for publishing a stream

+ +
  1. Create a NetConnection object and call NetConnection.connect().
  2. Call NetConnection.addEventListener() to listen for NetStatusEvent events.
  3. On the "NetConnection.Connect.Success" event, create a NetStream object and pass the NetConnection object to the constructor.
  4. To capture audio and video, call the NetStream.attachAudio()method + and the NetStream.attachCamera() method.
  5. To publish a stream, call the NetStream.publish() method. + You can record the data as you publish it so that users can play it back later.
+ +

Note: A NetStream can either publish a stream or play a stream, it cannot do both. To publish a stream and view the playback + from the server, create two NetStream objects. You can send multiple NetStream objects over one NetConnection object.

+ +

When Flash Media Server records a stream it creates a file. + By default, the server creates a directory with the + application instance name passed to NetConnection.connect() and stores the file in the directory. + For example, the following code connects to the default instance of the "lectureseries" application and records a stream called "lecture". + The file "lecture.flv" is recorded in the applications/lectureseries/streams/_definst_ directory: +

+ + + var nc:NetConnection = new NetConnection(); + nc.connect("rtmp://fms.example.com/lectureseries"); + nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + + function netStatusHandler(event:NetStatusEvent):void{ + if (event.info.code == "NetConnection.Connect.Success"){ + var ns:NetStream = new NetStream(nc); + ns.publish("lecture", "record"); + } + } + + +

The following example connects to the "monday" instance of the same application. + The file "lecture.flv" is recorded in the directory /applications/lectureseries/streams/monday:

+ + + var nc:NetConnection = new NetConnection(); + nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + nc.connect("rtmp://fms.example.com/lectureseries/monday"); + + function netStatusHandler(event:NetStatusEvent):void{ + if (event.info.code == "NetConnection.Connect.Success"){ + var ns:NetStream = new NetStream(nc); + ns.publish("lecture", "record"); + } + } + + +
The following example captures video from a camera and publishes it over a NetStream to Flash Media Server. + The example displays the video as it's played back from Flash Media Server. +

To run this example, you need a camera attached to your computer. You also need to add a Button + component and a Label component to the Library.

+

The application has a button that publishes a stream (sends it to Flash Media Server) only after + the application has successfully connected to the server. The application plays back the stream from the server + only after the stream has been successfully published. The NetStatusEvent returns an info object with a code + property that specifies these cases. The netStatusHandler function handles these events for the NetConnection and NetStream classes.

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.media.Video; + import flash.media.Camera; + import flash.net.NetConnection; + import flash.net.NetStream; + import fl.controls.Button; + import fl.controls.Label; + + public class NetStream_publish extends Sprite { + private var connectionURL:String = "rtmp://localhost/live/"; + private var videoURL:String = "liveVideo"; + private var nc:NetConnection; + private var ns_publish:NetStream; + private var ns_playback:NetStream; + private var video_publish:Video; + private var video_playback:Video; + private var cam:Camera; + private var b:Button; + private var l:Label; + + public function NetStream_publish() { + setUpUI(); + + nc = new NetConnection(); + nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + + // Add bandwidth detection handlers on the NetConnection Client to + // prevent Reference Errors at runtime when using the "live" and "vod" applications. + var clientObj:Object = new Object(); + clientObj.onBWDone = onBWDone; + clientObj.onBWCheck = onBWCheck; + nc.client = clientObj; + + // Connect to the "live" application on Flash Media Server. + nc.connect(connectionURL); + } + + private function netStatusHandler(event:NetStatusEvent):void { + trace(event.info.code + " | " + event.info.description); + switch (event.info.code) { + case "NetConnection.Connect.Success": + // Enable the "Publish" button after the client connects to the server. + b.enabled = true; + break; + case "NetStream.Publish.Start": + playbackVideo(); + break; + } + } + + private function publishVideo(event:MouseEvent):void{ + // Disable the button so that you can only publish once. + b.enabled = false; + // Create a NetStream to send video to FMS. + ns_publish = new NetStream(nc); + ns_publish.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + // Publish (send) the video to FMS. + cam = Camera.getCamera(); + ns_publish.attachCamera(cam); + ns_publish.publish(videoURL); + } + + private function playbackVideo():void { + // Create a NetStream to receive the video from FMS. + ns_playback = new NetStream(nc); + ns_playback.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + ns_playback.play(videoURL); + // Display the video that was published to FMS. + video_playback = new Video(cam.width, cam.height); + video_playback.x = cam.width + 20; + video_playback.y = 10; + video_playback.attachNetStream(ns_playback); + addChild(video_playback); + } + + + private function setUpUI():void { + b = new Button(); + b.addEventListener(MouseEvent.CLICK, publishVideo); + b.width = 150; + b.label = "Publish video to server"; + b.move(10, 150); + b.enabled = false; + + l = new Label(); + l.width = 150; + l.text = "Playing back from server" + l.move(190, 150); + + addChild(b); + addChild(l); + } + + // Handlers called by the Flash Media Server "live" and "vod" applications. + public function onBWDone(... rest):Boolean { + return true; + } + + public function onBWCheck(... rest):Number { + return 0; + } + } +} +
flash.net.NetConnection.connect()flash.events.NetStatusEvent.info
receiveAudio + Specifies whether incoming audio plays on the stream.flagBooleanSpecifies whether incoming audio plays on the stream (true) or not (false). The default value is true. + If the specified stream contains only audio data, NetStream.time stops incrementing when you pass false. + + + + Specifies whether incoming audio plays on the stream. + This method is available only to clients subscribed to the specified stream. + It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. + For example, attach this method to a button to allow users to mute and unmute the audio. + Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams + or when using the NetStream.appendBytes() method. + + + receiveVideoFPS + Specifies the frame rate for incoming video.FPSNumberSpecifies the frame rate per second at which the incoming video plays. + + + Specifies the frame rate for incoming video. This method is available only to clients subscribed to the specified stream. + It is not available to the publisher of the stream. + Call this method before or after you call the NetStream.play() method. For example, call this method to allow users + to set the video frame rate. To determine the current frame rate, use NetStream.currentFPS. To stop receiving video, pass 0. +

When you pass a value to the FPS parameter to limit the frame rate of the video, Flash Media Server attempts to reduce the frame rate while preserving + the integrity of the video. Between every two keyframes, the server sends the minimum number of frames needed to satisfy the desired rate. + Please note that I-frames (or intermediate frames) must be sent contiguously, otherwise the video is corrupted. Therefore, the desired number of frames + is sent immediately and contiguously following a keyframe. Since the frames are not evenly distributed, the motion appears smooth in segments punctuated by stalls.

+

Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams or when using the + NetStream.appendBytes() method.

+ +
receiveVideo + Specifies whether incoming video plays on the stream.flagBooleanSpecifies whether incoming video plays on this stream (true) or not (false). The default value is true. + If the specified stream contains only video data, NetStream.time stops incrementing when you pass false. + + + Specifies whether incoming video plays on the stream. This method is available only to clients subscribed to the specified stream. + It is not available to the publisher of the stream. Call this method before or after you call the NetStream.play() method. + For example, attach this method to a button to allow users to show and hide the video. + Use this method only on unicast streams that are played back from Flash Media Server. This method doesn't work on RTMFP multicast streams + or when using the NetStream.appendBytes() method. + + resetDRMVouchers + Deletes all locally cached digital rights management (DRM) voucher data.The voucher data cannot be deleted. + + IOErrorflash.errors:IOError + Deletes all locally cached digital rights management (DRM) voucher data. +

+ The application must re-download any required vouchers from the media rights server for the user + to be able to access protected content. Calling this function is equivalent to calling the + resetDRMVouchers() function of the DRMManager object.

+ +
The following example resets all DRM vouchers: + + +NetStream.resetDRMVouchers(); +
flash.net.drm.DRMManager.resetDRMVouchers()
resume + Resumes playback of a video stream that is paused. + Resumes playback of a video stream that is paused. If the video is already playing, calling this method + does nothing. + + close()pause()play()togglePause()seek + + Seeks the keyframe (also called an I-frame in the video industry) closest to + the specified location.offsetNumberThe approximate time value, in seconds, to move to in a video file. + With Flash Media Server, if <EnhancedSeek> is set to true in the Application.xml + configuration file (which it is by default), the server + generates a keyframe at offset. + +
  • To return to the beginning of the stream, pass 0 for offset.
  • To seek forward from the beginning of the stream, pass the number of seconds to advance. + For example, to position the playhead at 15 seconds from the beginning (or the keyframe + before 15 seconds), use myStream.seek(15).
  • To seek relative to the current position, pass NetStream.time + n + or NetStream.time - n + to seek n seconds forward or backward, respectively, from the current position. + For example, to rewind 20 seconds from the current position, use + NetStream.seek(NetStream.time - 20).
+ + +
+ + Seeks the keyframe (also called an I-frame in the video industry) closest to + the specified location. The keyframe is placed at an offset, in seconds, from + the beginning of the stream. + +

+ Video streams are usually encoded with two types of frames, keyframes (or I-frames) + and P-frames. A keyframe contains an entire image, while a P-frame is an + interim frame that provides additional video information between keyframes. + A video stream typically has a keyframe every 10-50 frames. +

+ +

Flash Media Server has several types of seek behavior: enhanced seeking and smart seeking.

+ +

Enhanced seeking

+ +

Enhanced seeking is enabled by default. To disable enhanced seeking, on Flash Media Server set the EnhancedSeek + element in the Application.xml configuration file to false. +

+ +

If enhanced seeking is enabled, the server generates + a new keyframe at offset based on the previous keyframe and any + intervening P-frames. However, generating keyframes creates a high processing load on the server + and distortion might occur in the generated keyframe. + If the video codec is On2, the keyframe before the seek point and any + P-frames between the keyframe and the seek point are sent to the client. +

+ +

+ If enhanced seeking is disabled, the server starts streaming + from the nearest keyframe. For example, suppose a video has keyframes at 0 seconds + and 10 seconds. A seek to 4 seconds causes playback to start at 4 seconds + using the keyframe at 0 seconds. The video stays frozen until it reaches the + next keyframe at 10 seconds. To get a better seeking experience, you need to + reduce the keyframe interval. In normal seek mode, you cannot start the video + at a point between the keyframes. +

+ +

Smart seeking

+ +

To enable smart seeking, set NetStream.inBufferSeek to true.

+ +

Smart seeking allows Flash Player to seek within an existing back buffer and forward buffer. When smart seeking is disabled, + each time seek() is called Flash Player flushes the buffer and requests data from the server. + For more information, see NetStream.inBufferSeek.

+ +

Seeking in Data Generation Mode

+ +

When you call seek() on a NetStream in Data Generation Mode, all bytes passed to + appendBytes() are discarded (not placed in the buffer, accumulated in the partial message FIFO, or parsed for seek points) + until you call appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN) or appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK) + to reset the parser. For information about Data Generation Mode, see NetStream.play().

+ + +
inBufferSeekbackBufferLengthbackBufferTimestep()timeplay()
send + Sends a message on a published stream to all subscribing clients.handlerNameStringThe message to send; also the name of the ActionScript + handler to receive the message. The handler name can be only one level deep + (that is, it can't be of the form parent/child) and is relative to the stream object. + Do not use a reserved term for a handler name. + For example, using "close" as a handler name causes + the method to fail. + With Flash Media Server, use @setDataFrame to add a + keyframe of metadata to a live stream + or @clearDataFrame to remove a keyframe. + + argumentsOptional arguments that can be of any type. They are + serialized and sent over the connection, and the receiving handler receives + them in the same order. If a parameter is a circular object (for example, + a linked list that is circular), the serializer handles the references correctly. + With Flash Media Server, + if @setDataFrame is the first argument, + use onMetaData as the second argument; for the third + argument, pass an instance of Object + or Array that has the metadata set as properties. + See the + Flash Media Server Developer Guide + for a list of suggested + property names. + With @clearDataFrame as the first argument, + use onMetaData as the second argument and no third argument. + + + Sends a message on a published stream to all subscribing clients. + This method is available only to the publisher of the specified stream. + This method is available for use with Flash Media Server only. + To process and respond to this message, create a handler on the + NetStream object, for example, ns.HandlerName. + +

+ Flash Player or AIR does not serialize methods + or their data, object prototype variables, or non-enumerable variables. For display objects, + Flash Player or AIR serializes the path but none of the data. +

+ +

+ You can call the send() method to add data keyframes to a live stream + published to Flash Media Server. A data keyframe is a message a publisher adds + to a live stream. Data keyframes are typically used to add metadata to a live stream + before data is captured for the stream from camera and microphone. + A publisher can add a data keyframe at any time while the live stream is being published. + The data keyframe is saved in the server's memory as long + as the publisher is connected to the server. +

+

+ Clients who are subscribed to the live stream before a data keyframe is + added receive the keyframe as soon as it is added. Clients who subscribe + to the live stream after the data keyframe is added receive the keyframe + when they subscribe. +

+

+ To add a keyframe of metadata to a live stream sent to Flash Media Server, use + @setDataFrame as the handler name, + followed by two additional arguments, for example: +

+ + + var ns:NetStream = new NetStream(nc); + ns.send("@setDataFrame", "onMetaData", metaData); + + + + +

+ The @setDataFrame argument + refers to a special handler built in to Flash Media Server. + The onMetaData argument is the + name of a callback function in your client application that + listens for the onMetaData event and retrieves the metadata. + The third item, metaData, is an instance + of Object or Array + with properties that define the metadata values. +

+ +

Use @clearDataFrame to clear a keyframe + of metadata that has already been set in the stream: +

+ + ns.send("@clearDataFrame", "onMetaData"); + + + +
The following example creates two NetStream objects. + One is used to publish a live stream to the server, while the other + subscribes to the stream. + +package { + import flash.display.Sprite; + import flash.net.NetConnection; + import flash.net.NetStream; + import flash.events.NetStatusEvent; + import flash.media.Video; + import flash.utils.setTimeout; + + + public class TestExample extends Sprite + { + var nc:NetConnection = new NetConnection(); + var ns1:NetStream; + var ns2:NetStream; + var vid:Video = new Video(300,300); + var obj:Object = new Object(); + + public function TestExample() { + nc.objectEncoding = 0; + nc.addEventListener("netStatus", onNCStatus); + nc.connect("rtmp://localhost/FlashVideoApp"); + addChild(vid); + } + + function onNCStatus(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + trace("You've connected successfully"); + ns1 = new NetStream(nc); + ns2 = new NetStream(nc); + + ns1.client = new CustomClient(); + ns1.publish("dummy", "live"); + + ns2.play("dummy"); + ns2.client = new CustomClient(); + vid.attachNetStream(ns2); + setTimeout(sendHello, 3000); + break; + + case "NetStream.Publish.BadName": + trace("Please check the name of the publishing stream" ); + break; + } + } + + function sendHello():void { + ns1.send("myFunction", "hello"); + } + } + } + + class CustomClient { + public function myFunction(event:String):void { + trace(event); + } + } + The following example creates metadata and adds it + to a live stream: + +private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetStream.Publish.Start": + var metaData:Object = new Object(); + metaData.title = "myStream"; + metaData.width = 400; + metaData.height = 200; + ns.send("&#64;setDataFrame", "onMetaData", metaData); + ns.attachCamera( Camera.getCamera() ); + ns.attachAudio( Microphone.getMicrophone() ); + } +} + To respond to a data keyframe added to a video, the client needs to define + an onMetaData event handler. + The onMetaData event handler is not registered + with addEventListener(), but instead is a callback function + with the name onMetaData, for example: + + public function onMetaData(info:Object):void { + trace("width: " + info.width); + trace("height: " + info.height); + } + This example shows how to create a playlist on the server: + + // Create a NetStream for playing + var my_ns:NetStream = new NetStream(my_nc); + my_video.attachNetStream(my_ns); + + // Play the stream record1 + my_ns.play("record1", 0, -1, true); + + // Switch to the stream live1 and play for 5 seconds. + // Since reset is false, live1 will start to play after record1 is done. + my_ns.play("live1", -1 , 5, false); + If the recorded video file contains only data messages, you can either + play the video file at the speed at which it was originally recorded, or + you can get the data messages all at once. + + //To play at normal speed + var my_ns:NetStream = new NetStream(my_nc); + my_ns.play("log", 0, -1); + + //To get the data messages all at once + my_ns.play("log", 0, -1, 3); +
clientdataReliableplay()
setDRMAuthenticationCredentials + Sets the DRM authentication credentials needed for viewing the underlying encrypted content.userNameStringA valid user name credential. + passwordStringThe password credential corresponding to the user name provided. + typeStringA string that specifies what type of authentication credentials are provided. + Valid values are "drm" and "proxy". The default value is "drm". +
  • With "drm" authentication type, the credentials provided are authenticated against + Flash Access.
  • With "proxy" authentication type, the credentials provided are authenticated against + the proxy server and must match those required by the proxy server. For example, the "proxy" + option allows the application to authenticate against a proxy server if an enterprise requires such a step + before the user can access the Internet. Unless anonymous authentication is used, after the proxy authentication, + the user still needs to authenticate against Flash Access in order to obtain the voucher and play the content. + You can use setDRMAuthenticationcredentials() a second time, with "drm" option, + to authenticate against Flash Access.
+ +
+ Sets the DRM authentication credentials needed for viewing the underlying encrypted content. +

+ The setDRMAuthenticationCredentials() method must provide credentials that + match those known and accepted by the content provider or the proxy server. These are the same credentials used + by the user when obtaining the permission to view the content. +

+ +
flash.events.DRMAuthenticateEvent
step + Steps forward or back the specified number of frames, relative to the currently displayed frame.framesint + Steps forward or back the specified number of frames, relative to the currently displayed frame. + Specify a positive number to step forward and a negative number to step in reverse. + Call this method to create accurate fast forward or rewind functionality. + +

This method is available only when data is streaming from Flash Media Server 3.5.3 or higher + and when NetStream.inBufferSeek is true. Also, the target frame must be in the buffer. + For example, if the currently displayed frame is frame number 120 and you specify a value + of 1000, the method fails if frame number 1120 is not in the buffer.

+ +

This method is intended to be used with the pause() or togglePause() methods. If you + step 10 frames forward or backward during playback without pausing, you may not notice the steps or they'll look like a glitch. + Also, when you call pause() or togglePause the audio is suppressed.

+ +

If the call to NetStream.step() is successful, a NetStatusEvent is sent with "NetStream.Step.Notify" + as the value of the info object's code property.

+ +

+ +
inBufferSeekbackBufferTimebackBufferLengthbufferTimebufferLengthstep()seek()
togglePause + Pauses or resumes playback of a stream. + Pauses or resumes playback of a stream. + The first time you call this method, it pauses play; the next time, it resumes play. + You could use this method to let users pause or resume playback by pressing + a single button. + + close()play()pause()resume()CONNECT_TO_FMS + A static object used as a parameter to + the constructor for a NetStream instance.connectToFMSString + A static object used as a parameter to + the constructor for a NetStream instance. It is the default value of the second parameter + in the NetStream constructor; it is + not used by the application for progressive media playback. When used, this parameter causes the constructor to + make a connection to a Flash Media Server instance. + + DIRECT_CONNECTIONS + Creates a peer-to-peer publisher connection.directConnectionsString + Creates a peer-to-peer publisher connection. Pass this string for the second (optional) parameter to + the constructor for a NetStream instance. With this string, an application can create + a NetStream connection for the purposes of publishing audio and video to clients. + + audioReliable + + For RTMFP connections, specifies whether audio is sent with full reliability.Boolean + + For RTMFP connections, specifies whether audio is sent with full reliability. When TRUE, all audio transmitted over this NetStream is fully reliable. + When FALSE, the audio transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. + You can use the FALSE value to reduce latency at the expense of audio quality. + +

If you try to set this property to FALSE on a network protocol that does not support partial reliability, + the attempt is ignored and the property is set to TRUE.

+ +
dataReliablevideoReliable
audioSampleAccess + + For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream.Boolean + + For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the audio stream. + When FALSE, subscriber attempts to capture the audio stream show permission errors. + + videoSampleAccessbackBufferLength + The number of seconds of previously displayed data that currently cached for rewinding and playback.Number + The number of seconds of previously displayed data that currently cached for rewinding and playback. + +

This property is available only when data is streaming from Flash Media Server 3.5.3 or higher; + for more information on Flash Media Server, see the class description.

+ +

To specify how much previously displayed data is cached, use the Netstream.backBufferTime property.

+ +

To prevent data from being cached, set the Netstream.inBufferSeek property to FALSE.

+ + +
backBufferTimeinBufferSeek
backBufferTime + Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds.Number + Specifies how much previously displayed data Flash Player tries to cache for rewinding and playback, in seconds. + The default value is 30 seconds for desktop applications and 3 seconds for mobile applications. + +

This property is available only when data is streaming from Flash Media Server version 3.5.3 or later; + for more information on Flash Media Server, see the class description.

+ +

Using this property improves performance for rewind operations, as data that has already been displayed + isn't retrieved from the server again. Instead, the stream begins replaying from the buffer. + During playback, data continues streaming from the server until the buffer is full.

+ +

If the rewind position is farther back than the data in the cache, the buffer is flushed; + the data then starts streaming from the server at the requested position.

+ +

To use this property set the Netstream.inBufferSeek property to TRUE.

+ + +
backBufferLengthbufferTimeinBufferSeek
bufferLength + The number of seconds of data currently in the buffer.Number + The number of seconds of data currently in the buffer. You can use this property with + the bufferTime property to estimate how close the buffer is to being full — for example, + to display feedback to a user who is waiting for data to be loaded into the buffer. + + backBufferLengthbufferTimebytesLoadedbufferTimeMax + Specifies a maximum buffer length for live streaming content, in seconds.Number + Specifies a maximum buffer length for live streaming content, in seconds. The default value is 0. + Buffer length can grow over time due to networking and device issues (such as clock drift between sender and receiver). + Set this property to cap the buffer length for live applications such as meetings and surveillance. + +

When bufferTimeMax > 0 and bufferLength >= bufferTimeMax, audio plays faster until + bufferLength reaches bufferTime. If a live stream is video-only, video plays faster + until bufferLength reaches bufferTime.

+ +

Depending on how much playback is lagging (the difference between bufferLength and bufferTime), + Flash Player controls the rate of catch-up between 1.5% and 6.25%. + If the stream contains audio, faster playback is achieved by frequency domain downsampling which minimizes audible distortion.

+ +

Set the bufferTimeMax property to enable live buffered stream catch-up in the following cases:

+ +
  • Streaming live media from Flash Media Server.
  • Streaming live media in Data Generation Mode (NetStream.appendBytes()).
+ + +
bufferLengthbufferTime
bufferTime + Specifies how long to buffer messages before starting to display the stream.Number + Specifies how long to buffer messages before starting to display the stream. + +

The default value is 0.1 (one-tenth of a second). To determine the number of seconds + currently in the buffer, use the bufferLength property.

+ +

To play a server-side playlist, set bufferTime to at least 1 second. If + you experience playback issues, increase the length of bufferTime. +

+ +

Recorded content To avoid distortion when streaming pre-recorded (not live) content, + do not set the value of Netstream.bufferTime to 0. By default, the application + uses an input buffer for pre-recorded content that queues the media data and plays the media properly. + For pre-recorded content, use the default setting or increase the buffer time.

+ +

Live content When streaming live content, set the bufferTime property to 0.

+ +

Starting with Flash Player 9.0.115.0, Flash Player no longer clears the buffer + when NetStream.pause() is called. Before Flash Player 9.0.115.0, Flash Player + waited for the buffer to fill up before resuming playback, which often caused a delay.

+ +

For a single pause, the NetStream.bufferLength property has a limit of either 60 seconds + or twice the value of NetStream.bufferTime, whichever value is higher. For example, if + bufferTime is 20 seconds, Flash Player buffers until NetStream.bufferLength + is the higher value of either 20~~2 (40), or 60. In this case it buffers until bufferLength is 60. + If bufferTime is 40 seconds, Flash Player buffers until bufferLength is the higher value + of 40~~2 (80), or 60. In this case it buffers until bufferLength is 80 seconds.

+ +

The bufferLength property also has an absolute limit. + If any call to pause() causes bufferLength + to increase more than 600 seconds or the value of bufferTime ~~ 2, whichever is higher, Flash Player + flushes the buffer and resets bufferLength to 0. For example, if + bufferTime is 120 seconds, Flash Player flushes the buffer + if bufferLength reaches 600 seconds; if bufferTime is 360 seconds, + Flash Player flushes the buffer if bufferLength reaches 720 seconds.

+ +

Tip: You can use NetStream.pause() in code to buffer data while viewers are watching + a commercial, for example, and then unpause when the main video starts.

+ +

For more information about the new pause behavior, + see http://www.adobe.com/go/learn_fms_smartpause_en.

+

+ Flash Media Server. The buffer behavior depends on whether the buffer time is + set on a publishing stream or a subscribing stream. + For a publishing stream, bufferTime specifies how long the outgoing buffer can + grow before the application starts dropping frames. + On a high-speed connection, buffer time is not a concern; data is sent + almost as quickly as the application can buffer it. On a slow connection, however, there can + be a significant difference between how fast the application buffers the data and how fast it + is sent to the client. +

+ +

+ For a subscribing stream, bufferTime specifies how long to buffer incoming + data before starting to display the stream. +

+ +

+ When a recorded stream is played, if bufferTime is 0, Flash sets it to a small + value (approximately 10 milliseconds). If live streams are later played + (for example, from a playlist), this buffer time persists. That is, bufferTime + remains nonzero for the stream. +

+ +
backBufferTimebufferLengthbufferTimeMaxtime
bytesLoaded + The number of bytes of data that have been loaded into the application.uint + The number of bytes of data that have been loaded into the application. You can use this property + with the bytesTotal property to estimate how close the buffer is to being full — for example, + to display feedback to a user who is waiting for data to be loaded into the buffer. + + bytesTotalbufferLengthbytesTotal + The total size in bytes of the file being loaded into the application.uint + The total size in bytes of the file being loaded into the application. + + bytesLoadedbufferTimecheckPolicyFile + Specifies whether the application tries to download a cross-domain policy file from the + loaded video file's server before beginning to load the video file.Boolean + Specifies whether the application tries to download a cross-domain policy file from the + loaded video file's server before beginning to load the video file. Use this property for progressive video download, + and to load files that are outside the calling SWF file's own domain. + This property is ignored when you are using RTMP. + +

Set this property to true to call BitmapData.draw() on a video file loaded from a + domain outside that of the calling SWF. The BitmapData.draw() method provides pixel-level access to the video. + If you call BitmapData.draw() without setting the checkPolicyFile property + to true at loading time, you can get a SecurityError exception + because the required policy file was not downloaded.

+ +

Do not set this property to true unless you want pixel-level access to the video you are loading. + Checking for a policy file consumes network bandwidth and can delay the start of your download.

+ +

When you call the NetStream.play() method with checkPolicyFile set to true, + Flash Player or the AIR runtime + must either successfully download a relevant cross-domain policy file or determine + that no such policy file exists before it begins downloading. To verify the existence of a policy file, + Flash Player or the AIR runtime + performs the following actions, in this order:

+ +
  1. The application considers policy files that have already been downloaded.
  2. The application tries to download any pending policy files specified in calls to the + Security.loadPolicyFile() method.
  3. The application tries to download a policy file from the default + location that corresponds to the URL you passed to NetStream.play(), which is + /crossdomain.xml on the same server as that URL.
+ +

In all cases, Flash Player or Adobe AIR + requires that an appropriate policy file exist on the video's server, + that it provide access to the object at the URL you passed to play() based on the + policy file's location, and that it allow the domain of the calling code's file to access the video, + through one or more <allow-access-from> tags.

+ +

If you set checkPolicyFile to true, the application waits until the policy file + is verified before downloading the video. Wait to perform any pixel-level + operations on the video data, such as calling BitmapData.draw(), until + you receive onMetaData or NetStatus events from your + NetStream object.

+ +

If you set checkPolicyFile to true but no relevant policy file is found, + you won't receive an error until you perform an operation that requires a policy file, and then + the application throws a SecurityError exception.

+ +

Be careful with checkPolicyFile if you are downloading a file from a URL that + uses server-side HTTP redirects. The application tries to retrieve policy files + that correspond to the initial URL that you specify in NetStream.play(). If the + final file comes from a different URL because of HTTP redirects, the initially + downloaded policy files might not be applicable to the file's final URL, which is the URL + that matters in security decisions.

+ +

For more information on policy files, see "Website controls (policy files)" in + the ActionScript 3.0 Developer's Guide and the Flash Player Developer Center Topic: + Security.

+ +
flash.display.BitmapData.draw()flash.system.Security.loadPolicyFile()netStatusonMetaDataplay()
client + Specifies the object on which callback methods are invoked to handle streaming or F4V/FLV + file data.ObjectThe client property must be set to a non-null object. + + TypeErrorTypeError + Specifies the object on which callback methods are invoked to handle streaming or F4V/FLV + file data. The default object is this, the + NetStream object being created. If you set the client property to another + object, callback methods are invoked on that other object. The NetStream.client + object can call the following functions and receive an associated data object: + onCuePoint(), + onImageData(), + onMetaData(), onPlayStatus(), onSeekPoint(), + onTextData(), and onXMPData(). +

To associate the client property with an event handler:

+

  1. Create an object and assign it to the client property of the + NetStream object: + + var customClient:Object = new Object(); + my_netstream.client = customClient; + +
  2. Assign a handler function for the desired data event as a property of the client + object: + + customClient.onImageData = onImageDataHandler; + +
  3. Write the handler function to receive the data event object, such as: + + public function onImageDataHandler(imageData:Object):void { + trace("imageData length: " + imageData.data.length); + } +

+

When data is passed through the stream or during playback, the data event object (in + this case the imageData object) is populated with the data. See the onImageData + description, which includes a full example of an object assigned to the client property.

+

To associate the client property with a subclass:

+

  1. Create a subclass with a handler function to receive the data event object: + + class CustomClient { + public function onMetaData(info:Object):void { + trace("metadata: duration=" + info.duration + " framerate=" + info.framerate); + } + +
  2. Assign an instance of the subclass to the client property of the + NetStream object: + + my_netstream.client = new CustomClient(); + +

+

When data is passed through the stream or during playback, the data event object (in + this case the info object) is populated with the data. See the class example at + the end of the NetStream class, which shows the assignment of a subclass instance + to the client property.

+ +
onCuePointonImageDataonMetaDataonPlayStatusonSeekPointonTextData
currentFPS + The number of frames per second being displayed.Number + The number of frames per second being displayed. If you are exporting video files to be played back on a number + of systems, you can check this value during testing to help you determine how much compression to apply when + exporting the file. + + dataReliable + + For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability.Boolean + + For RTMFP connections, specifies whether NetStream.send() calls are sent with full reliability. + When TRUE, NetStream.send() calls + that are transmitted over this NetStream are fully reliable. + When FALSE, NetStream.send() calls are not transmitted with full reliability, + but instead are retransmitted for a limited time and then dropped. + You can set this value to FALSE to reduce latency at the expense of data quality. + +

If you try to set this property to FALSE on a network protocol that does not support partial reliability, + the attempt is ignored and the property is set to TRUE.

+ +
audioReliablesend()videoReliable
farID + For RTMFP connections, the identifier of the far end that is connected to this NetStream instance.String + For RTMFP connections, the identifier of the far end that is connected to this NetStream instance. + + farNonce + For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection.String + For RTMFP and RTMPE connections, a value chosen substantially by the other end of this stream, unique to this connection. + This value appears to the other end of the stream as its nearNonce value. + + inBufferSeek + Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE).Boolean + Specifies whether displayed data is cached for smart seeking (TRUE), or not (FALSE). + The default value is FALSE. + +

Flash Media Server 3.5.3 and Flash Player 10.1 work together to support smart seeking. + Smart seeking uses back and forward buffers to seek without requesting data from the server. + Standard seeking flushes buffered data and asks the server to send new data based on the seek time.

+ +

Call NetStream.step() to step forward and backward a specified number of frames. Call + NetStream.seek() to seek forward and backward a specified number of seconds.

+ +

Smart seeking reduces server load and improves seeking performance. Set inBufferSeek=true and + call step() and seek() to create:

+ +
  • Client-side DVR functionality. Seek within the client-side buffer instead of going to the server for delivery of new video.
  • Trick modes. Create players that step through frames, fast-forward, fast-rewind, and advance in slow-motion.
+ +

When inBufferSeek=true and a call to NetStream.seek() is successful, + the NetStatusEvent info.description property contains the string "client-inBufferSeek".

+ +

When a call to NetStream.step() is successful, the NetStatusEvent info.code property + contains the string "NetStream.Step.Notify".

+ + +
backBufferTimebackBufferLengthbufferTimebufferLengthstep()seek()
info + Returns a NetStreamInfo object whose properties contain statistics about the quality of service.flash.net:NetStreamInfo + Returns a NetStreamInfo object whose properties contain statistics about the quality of service. + The object is a snapshot of the current state. + + flash.net.NetStreamInfoliveDelay + The number of seconds of data in the subscribing stream's + buffer in live (unbuffered) mode.Number + The number of seconds of data in the subscribing stream's + buffer in live (unbuffered) mode. This property specifies the current + network transmission delay (lag time). + +

This property is intended primarily for use with a server such as Flash Media Server; + for more information, see the class description.

+ +

You can get the value of this property to roughly gauge the transmission + quality of the stream and communicate it to the user.

+ +
maxPauseBufferTime + Specifies how long to buffer messages during pause mode, in seconds.Number + Specifies how long to buffer messages during pause mode, in seconds. This property can be used to limit how much buffering is done + during pause mode. As soon as the value of NetStream.bufferLength reaches + this limit, it stops buffering. + +

If this value is not set, it defaults the limit to 60 seconds or twice the value of NetStream.bufferTime on each pause, + whichever is higher.

+ +
bufferTime
multicastAvailabilitySendToAll + For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are + sent to all peers or to just one peer.Boolean + For RTMFP connections, specifies whether peer-to-peer multicast fragment availability messages are + sent to all peers or to just one peer. + A value of TRUE specifies that the messages are sent to all peers once + per specified interval. A value of FALSE specifies that the + messages are sent to just one peer per specified interval. The interval + is determined by the multicastAvailabilityUpdatePeriod property. + + multicastAvailabilityUpdatePeriodmulticastAvailabilityUpdatePeriod + For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that + the local node has new peer-to-peer multicast media fragments available.Number + For RTMFP connections, specifies the interval in seconds between messages sent to peers informing them that + the local node has new peer-to-peer multicast media fragments available. + Larger values can increase batching efficiency and reduce control overhead, + but they can lower quality on the receiving end by reducing the amount of time available to retrieve + fragments before they are out-of-window. Lower values can reduce latency and + improve quality, but they increase control overhead. + + multicastAvailabilitySendToAllmulticastFetchPeriodmulticastWindowDurationmulticastFetchPeriod + For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer + multicast media fragment is available and when it tries to fetch it from a peer.Number + For RTMFP connections, specifies the time in seconds between when the local node learns that a peer-to-peer + multicast media fragment is available and when it tries to fetch it from a peer. This value gives an opportunity for the + fragment to be proactively pushed to the local node before a fetch from a + peer is attempted. It also allows for more than one peer to announce availability + of the fragment, so the fetch load can be spread among multiple peers. + +

Larger values can improve load balancing and fairness in the peer-to-peer mesh, + but reduce the available multicastWindowDuration and increase latency. Smaller values can + reduce latency when fetching is required, but might increase duplicate data reception + and reduce peer-to-peer mesh load balance.

+ +
multicastAvailabilityUpdatePeriodmulticastWindowDuration
multicastInfo + For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service.flash.net:NetStreamMulticastInfo + For RTMFP connections, returns a NetStreamMulticastInfo object whose properties contain statistics about the quality of service. + The object is a snapshot of the current state. + + flash.net.NetStreamMulticastInfomulticastPushNeighborLimit + For RTMFP connections, specifies the maximum number of peers to which to proactively push + multicast media.Number + For RTMFP connections, specifies the maximum number of peers to which to proactively push + multicast media. + + multicastRelayMarginDuration + For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains + available to send to peers that request it beyond a specified duration.Number + For RTMFP connections, specifies the duration in seconds that peer-to-peer multicast data remains + available to send to peers that request it beyond a specified duration. The duration is specified + by the multicastWindowDuration property. + + multicastWindowDurationmulticastWindowDuration + For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly + window.Number + For RTMFP connections, specifies the duration in seconds of the peer-to-peer multicast reassembly + window. Shorter values reduce latency but may reduce quality by not + allowing enough time to obtain all of the fragments. Conversely, larger values may increase + quality by providing more time to obtain all of the fragments, with a corresponding + increase in latency. + + multicastRelayMarginDurationnearNonce + For RTMFP and RTMPE connections, a value chosen substantially by this end of the stream, unique to this connection.String + For RTMFP and RTMPE connections, a value chosen substantially by this end of the stream, unique to this connection. + This value appears to the other end of the stream as its farNonce value. + + objectEncoding + The object encoding (AMF version) for this NetStream object.uint + The object encoding (AMF version) for this NetStream object. The NetStream object + inherits its objectEncoding value from the associated NetConnection object. + It's important to understand this property if your ActionScript 3.0 SWF file needs to + communicate with servers released prior to Flash Player 9. + For more information, see the objectEncoding property description + in the NetConnection class. + +

The value of this property depends on whether the stream is local or + remote. Local streams, where null was passed to the + NetConnection.connect() method, return the value of + NetConnection.defaultObjectEncoding. Remote streams, where you + are connecting to a server, return the object encoding of the connection to the server.

+ +

If you try to read this property when not connected, or if you try to change this property, + the application throws an exception.

+ +
flash.net.NetConnection.objectEncoding
peerStreams + + An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance.Array + + An object that holds all of the subscribing NetStream instances that are listening to this publishing NetStream instance. + + soundTransform + Controls sound in this NetStream object.flash.media:SoundTransform + Controls sound in this NetStream object. For more information, see the SoundTransform class. + + flash.media.SoundTransformtime + The position of the playhead, in seconds.Number + The position of the playhead, in seconds. +

+ Flash Media Server For a subscribing stream, the number of seconds + the stream has been playing. For a publishing stream, the number of + seconds the stream has been publishing. + This number is accurate to the thousandths decimal place; multiply + by 1000 to get the number of milliseconds the stream has been playing. +

+

+ For a subscribing stream, if the server stops sending data but the stream remains open, + the value of the time property stops advancing. When the server begins sending data again, + the value continues to advance from the point at which it stopped (when the server stopped sending data). +

+

+ The value of time continues to advance when the stream + switches from one playlist element to another. This property is set to 0 when + NetStream.play() is called with reset set to 1 or + true, or when NetStream.close() is called. +

+ +
bufferLengthbytesLoaded
videoReliable + + For RTMFP connections, specifies whether video is sent with full reliability.Boolean + + For RTMFP connections, specifies whether video is sent with full reliability. When TRUE, all video transmitted over this NetStream is fully reliable. + When FALSE, the video transmitted is not fully reliable, but instead is retransmitted for a limited time and then dropped. + You can use the FALSE value to reduce latency at the expense of video quality. + +

If you try to set this property to FALSE on a network protocol that does not support partial reliability, + the attempt is ignored and the property is set to TRUE.

+ +
audioReliabledataReliable
videoSampleAccess + + For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream.Boolean + + For RTMFP connections, specifies whether peer-to-peer subscribers on this NetStream are allowed to capture the video stream. + When FALSE, subscriber attempts to capture the video stream show permission errors. + + audioSampleAccess
NetMonitor + The NetMonitor class allows you to monitor the NetStream objects used by an application.flash.events:EventDispatcher + The NetMonitor class allows you to monitor the NetStream objects used by an application. + +

Use the NetMonitor class to get the current list of NetStream objects in use in an application. An instance of this class + dispatches a netStreamCreate event whenever a new NetStream object is created.

+ +

You can use the NetMonitor class to help track video playback and related events without regard to the specific + video player being used. This facility can be helpful when implementing media measurement, analytics, and usage tracking + libraries.

+ +

Note: NetStream monitoring is not supported by Flash Player in the browser on Android and Blackberry Tablet OS or + by AIR on iOS.

+ +
This example demonstrates how the NetMonitor class can be used to gain access to + NetStream information without intimate knowledge of the specific video player in use. + Here, the MediaPlayerSprite class from the Open Screen Media Framework (OSMF) project is used, + but any video player could be substituted. + +

You can use the Space bar to pause and unpause the video in the example and the right and left arrows to seek + forward or back 30 seconds to see the effects these actions have on the dispatched events.

+ +package +{ + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.KeyboardEvent; + import flash.events.NetDataEvent; + import flash.events.NetMonitorEvent; + import flash.events.NetStatusEvent; + import flash.net.NetMonitor; + import flash.net.NetStream; + import flash.ui.Keyboard; + + import org.osmf.elements.VideoElement; + import org.osmf.media.MediaPlayer; + import org.osmf.media.MediaPlayerSprite; + import org.osmf.net.DynamicStreamingItem; + import org.osmf.net.DynamicStreamingResource; + + public class NetMonitorExample extends Sprite + { + private var netmon:NetMonitor; + private var mediaPlayer:MediaPlayer; + + public function NetMonitorExample() + { + //Configure stage + this.stage.align = StageAlign.TOP_LEFT; + this.stage.scaleMode = StageScaleMode.NO_SCALE; + + //Create NetMonitor object + netmon = new flash.net.NetMonitor(); + netmon.addEventListener(NetMonitorEvent.NET_STREAM_CREATE, newNetStream ); + + //Setup video player + var mediaPlayerSprite:MediaPlayerSprite = new MediaPlayerSprite(); + var videoElement:VideoElement = new VideoElement(); + var dynResource:DynamicStreamingResource = new DynamicStreamingResource( "rtmp://cp67126.edgefcs.net/ondemand" ); + + dynResource.streamItems = Vector.<DynamicStreamingItem>( + [ new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_768x428_24.0fps_408kbps.mp4", 408, 768, 428 ) + , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_768x428_24.0fps_608kbps.mp4", 608, 768, 428 ) + , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1024x522_24.0fps_908kbps.mp4", 908, 1024, 522 ) + , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1024x522_24.0fps_1308kbps.mp4", 1308, 1024, 522 ) + , new DynamicStreamingItem( "mp4:mediapm/ovp/content/demo/video/elephants_dream/elephants_dream_1280x720_24.0fps_1708kbps.mp4", 1708, 1280, 720 ) + ]); + + videoElement.resource = dynResource; + + addChild( mediaPlayerSprite ); + mediaPlayerSprite.media = videoElement; + mediaPlayer = mediaPlayerSprite.mediaPlayer; + this.stage.addEventListener( KeyboardEvent.KEY_DOWN, keyControl ); + } + + //On new NetStream + private function newNetStream( event:NetMonitorEvent ):void + { + trace( "New Netstream object "); + var stream:NetStream = event.netStream; + stream.addEventListener(NetDataEvent.MEDIA_TYPE_DATA, onStreamData); + stream.addEventListener(NetStatusEvent.NET_STATUS, onStatus); + } + + //On data events from a NetStream object + private function onStreamData( event:NetDataEvent ):void + { + trace( "Data event at " + event.timestamp ); + var netStream:NetStream = event.target as NetStream; + switch( event.info.handler ) + { + case "onMetaData": + trace( "--MetaData: " + stringify( netStream.info.metaData )); + break; + case "onXMPData": + trace( "--XMPData: " + stringify( netStream.info.xmpData )); + break; + default: + trace( "--" + event.info.handler + ": " + stringify(event.info.args[0]) ); + + } + } + + //On status events from a NetStream object + private function onStatus( event:NetStatusEvent ):void + { + trace( "Status: " + stringify( event.info ) ); + } + + //Utility function to print out object properties + private function stringify( object:Object ):String + { + var string:String = ""; + + var prop:String; + var comma:Boolean = false; + for ( prop in object ) + { + if( comma ) string += ", "; + else comma = true; + + if( typeof(object[prop]) == "object" ) + { + stringify( object[prop] ) + } else string += prop + " = " + object[prop]; + } + return string; + } + + //Simple keyboard control for the video player + private function keyControl( event:KeyboardEvent ):void + { + switch ( event.keyCode ) + { + case Keyboard.SPACE: + if( mediaPlayer.paused ) mediaPlayer.play(); + else mediaPlayer.pause(); + break; + case Keyboard.RIGHT: + mediaPlayer.seek( mediaPlayer.currentTime + 30 ); + break; + case Keyboard.LEFT: + mediaPlayer.seek( mediaPlayer.currentTime - 30 ); + break; + default: + //do nothing + } + } + } +} +
NetStreamnetStreamCreate + Dispatched when a new NetStream object is created within the security context of this NetMonitor instance.flash.events.NetMonitorEvent.NET_STREAM_CREATEflash.events.NetMonitorEvent + Dispatched when a new NetStream object is created within the security context of this NetMonitor instance. + +

Note: if the NetStream monitoring is not supported on the current platform, netStreamCreate events + are not dispatched.

+ +
listStreams + Retrieves all NetStream objects belonging to this NetMonitor object's security context.Vector of NetStream objects + + Retrieves all NetStream objects belonging to this NetMonitor object's security context. + +

Avoid caching the list of NetStream objects. Maintaining a reference to these NetStream objects + can introduce memory leaks into an application by preventing the garbage collector from reclaiming + an object's resources when it is no longer being used.

+ +

Note: if the NetStream monitoring is not supported on the current platform, the list returned by + this function is always empty.

+ +
NetStreamInfo + + The NetStreamInfo class specifies the various Quality of Service (QOS) statistics and other information related to a NetStream object + and the underlying streaming buffer for audio, video, and data.Object + + The NetStreamInfo class specifies the various Quality of Service (QOS) statistics and other information related to a NetStream object + and the underlying streaming buffer for audio, video, and data. A NetStreamInfo object is returned in response + to the NetStream.info call, which takes a snapshot of the current QOS state + and provides the QOS statistics through the NetStreamInfo properties. + + toString + Returns a text value listing the properties of the NetStreamInfo object.A string containing the values of the properties of the NetStreamInfo object + + + StringReturns a text value listing the properties of this NetStreamInfo object. + + Returns a text value listing the properties of the NetStreamInfo object. + + SRTT + The smoothed round trip time (SRTT) for the NetStream session, in milliseconds.Number + The smoothed round trip time (SRTT) for the NetStream session, in milliseconds. + This property contains a valid value only for RTMFP streams. For RTMP streams, the value is 0. + + flash.net.NetGroupaudioBufferByteLength + Provides the NetStream audio buffer size in bytes.Number + Provides the NetStream audio buffer size in bytes. + It specifies the buffer size for audio data in streaming media, both live and recorded. + This property is like Netstream.bytesLoaded, + which is used in progressive downloads. + audioBufferLength + Provides NetStream audio buffer size in seconds.Number + Provides NetStream audio buffer size in seconds. This property extends the NetStream.bufferLength property + and provides the buffer length in time specifically for audio data. + audioByteCount + Specifies the total number of audio bytes that have arrived in the queue, regardless of how many have been played or flushed.Number + Specifies the total number of audio bytes that have arrived in the queue, regardless of how many have been played or flushed. + You can use this value to calculate the incoming audio data rate, using the metric of your choice, by creating a timer and calculating the difference in values + in successive timer calls. Alternatively, use audioBytesPerSecond. + + audioBytesPerSecondaudioBytesPerSecond + Specifies the rate at which the NetStream audio buffer is filled in bytes per second.Number + Specifies the rate at which the NetStream audio buffer is filled in bytes per second. The value is calculated as a smooth + average for the audio data received in the last second. + + audioLossRate + Specifies the audio loss for the NetStream session.Number + Specifies the audio loss for the NetStream session. This value returns a valid value only for RTMFP streams and would return 0 for RTMP streams. + Loss rate is defined as the ratio of lost messages to total messages. + + byteCount + Specifies the total number of bytes that have arrived into the queue, regardless of how many have been played or flushed.Number + Specifies the total number of bytes that have arrived into the queue, regardless of how many have been played or flushed. + You can use this value to calculate the incoming data rate, using the metric of your choice, by creating a timer and calculating the difference in values + in successive timer calls. Alternatively, use currentBytesPerSecond. + + currentBytesPerSecondcurrentBytesPerSecond + Specifies the rate at which the NetStream buffer is filled in bytes per second.Number + Specifies the rate at which the NetStream buffer is filled in bytes per second. The value is calculated as a smooth + average for the total data received in the last second. + + dataBufferByteLength + Provides the NetStream data buffer size in bytes.Number + Provides the NetStream data buffer size in bytes. + It specifies the buffer size for data messages in streaming media, both live and recorded. + This property is like Netstream.bytesLoaded, + which is used in progressive downloads. + dataBufferLength + Provides NetStream data buffer size in seconds.Number + Provides NetStream data buffer size in seconds. This property extends the NetStream.bufferLength property + and provides the buffer length in time specifically for data messages. + dataByteCount + Specifies the total number of bytes of data messages that have arrived in the queue, regardless of how many have been played or flushed.Number + Specifies the total number of bytes of data messages that have arrived in the queue, regardless of how many have been played or flushed. + You can use this value to calculate the incoming data-messages rate, using the metric of your choice, + by creating a timer and calculating the difference in values in successive timer calls. + Alternatively, use dataBytesPerSecond. + + dataBytesPerSeconddataBytesPerSecond + Specifies the rate at which the NetStream data buffer is filled in bytes per second.Number + Specifies the rate at which the NetStream data buffer is filled in bytes per second. The value is calculated as a smooth + average for the data messages received in the last second. + + droppedFrames + Returns the number of video frames dropped in the current NetStream playback session.Number + Returns the number of video frames dropped in the current NetStream playback session. +

In recorded streaming or progressive download, if the video is a high-quality or high-resolution, high-bitrate video, + the decoder can lag behind in decoding the required number of frames per second if it does not have adequate + system CPU resources. In live streaming, the buffer drops video frames if the latency is too high. This property specifies + the number of frames that were dropped and not presented normally.

+ +
isLive + Whether the media being played is recorded or live.Boolean + Whether the media being played is recorded or live. This property is relevant for RTMP streaming only. For + progressive download and HTTP Dynamic Streaming the property is always false. + +

Note: This property is always false in Flash Player in the browser on Android and Blackberry Tablet OS or + in AIR on iOS.

+ +
maxBytesPerSecond + Specifies the maximum rate at which the NetStream buffer is filled in bytes per second.Number + Specifies the maximum rate at which the NetStream buffer is filled in bytes per second. This value provides information about the capacity of the + client network based on the last messages received by the NetStream object. Depending on the size of the buffer specified in + NetStream.bufferTime and the bandwidth available on the client, Flash Media Server fills the buffer in bursts. + This property provides the maximum rate at which the client buffer is filled. + + metaData + The most recent metadata object associated with the media being played.Object + The most recent metadata object associated with the media being played. + +

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or + in AIR on iOS.

+ +
playbackBytesPerSecond + Returns the stream playback rate in bytes per second.Number + Returns the stream playback rate in bytes per second. The playback buffer can contain content of various playlists. + This property provides the playback rate that closely matches the bit rate of the currently playing stream. + + resourceName + The resource name used when NetStream.play() was called.StringThe resource name used when NetStream.play() was called. + + The resource name used when NetStream.play() was called. This property contains the full URL for progressive + download, the resource name for RTMP streaming and null for HTTP streaming. + +

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or + in AIR on iOS.

+ +
flash.media.NetStream.play()
uri + The URI used when NetConnection.connect() was called.StringThe URI used when NetConnection.connect() was called. + + + The URI used when NetConnection.connect() was called. This is null for progressive download + or HTTP streaming. + +

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or + in AIR on iOS.

+ +
flash.media.NetConnection.uri
videoBufferByteLength + Provides the NetStream video buffer size in bytes.Number + Provides the NetStream video buffer size in bytes. + It specifies the buffer size for video data in streaming media, both live and recorded. + This property is like Netstream.bytesLoaded, + which is used in progressive downloads. + videoBufferLength + Provides NetStream video buffer size in seconds.Number + Provides NetStream video buffer size in seconds. This property extends the NetStream.bufferLength property + and provides the buffer length in time specifically for video data. + videoByteCount + Specifies the total number of video bytes that have arrived in the queue, regardless of how many have been played or flushed.Number + Specifies the total number of video bytes that have arrived in the queue, regardless of how many have been played or flushed. + You can use this value to calculate the incoming video data rate, using the metric of your choice, + by creating a timer and calculating the difference in values in successive timer calls. + Alternatively, use videoBytesPerSecond, + + videoBytesPerSecondvideoBytesPerSecond + Specifies the rate at which the NetStream video buffer is filled in bytes per second.Number + Specifies the rate at which the NetStream video buffer is filled in bytes per second. The value is calculated as a smooth + average for the video data received in the last second. + + videoLossRate + Provides the NetStream video loss rate (ratio of lost messages to total messages).Number + Provides the NetStream video loss rate (ratio of lost messages to total messages). + +

When the message size is smaller than the maximum transmission unit (MTU), this value corresponds to + the network packet loss rate.

+ +

This property returns a valid value only for RTMFP streams. For RTMP streams, it returns a value of zero. + For more information, see the + Flash Media Server documentation.

+ +
xmpData + The most recent XMP data object associated with the media being played.Object + The most recent XMP data object associated with the media being played. + +

Note: This property is always null in Flash Player in the browser on Android and Blackberry Tablet OS or + in AIR on iOS.

+ +
URLStream + The URLStream class provides low-level access to + downloading URLs.flash.utils:IDataInputflash.events:EventDispatcher + The URLStream class provides low-level access to + downloading URLs. Data is made available to application code + immediately as it is downloaded, instead of waiting until + the entire file is complete as with URLLoader. + The URLStream class also lets you close a stream + before it finishes downloading. + The contents of the downloaded file are made available as raw binary data. + +

The read operations in URLStream are nonblocking. + This means that you must use the bytesAvailable property to determine + whether sufficient data is available before reading it. An + EOFError exception is thrown if insufficient + data is available.

+ +

All binary data is encoded by default in big-endian format, with the + most significant byte first.

+ +

The security rules that apply to URL downloading with the URLStream class are identical + to the rules applied to URLLoader objects. + Policy files may be downloaded as needed. Local file security rules are enforced, + and security warnings are raised as needed.

+ + +
The following example loads a SWF file and parses the beginning of its header to indicate + compression and version number information. +

To run the example, place a file named URLStreamExample.swf in the same directory as your SWF file.

+ + +package { + import flash.display.Sprite; + import flash.errors.*; + import flash.events.*; + import flash.net.URLRequest; + import flash.net.URLStream; + + public class URLStreamExample extends Sprite { + private static const ZLIB_CODE:String = "CWS"; + private var stream:URLStream; + + public function URLStreamExample() { + stream = new URLStream(); + var request:URLRequest = new URLRequest("URLStreamExample.swf"); + configureListeners(stream); + try { + stream.load(request); + } catch (error:Error) { + trace("Unable to load requested URL."); + } + } + + private function configureListeners(dispatcher:EventDispatcher):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + } + + private function parseHeader():void { + trace("parseHeader"); + trace("isCompressed: " + isCompressed()); + trace("version: " + stream.readByte()); + } + + private function isCompressed():Boolean { + return (stream.readUTFBytes(3) == ZLIB_CODE); + } + + private function completeHandler(event:Event):void { + trace("completeHandler: " + event); + parseHeader(); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:Event):void { + trace("progressHandler: " + event); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function httpStatusHandler(event:HTTPStatusEvent):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + } +} +
URLLoaderURLRequestprogress + Dispatched when data is received as the download operation progresses.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched when data is received as the download operation progresses. + Data that has been received can be read immediately using the methods of the URLStream class. + URLStream.load()open + Dispatched when a load operation starts.flash.events.Event.OPENflash.events.Event + Dispatched when a load operation starts. + URLStream.load()ioError + Dispatched when an input/output error occurs that causes a load operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input/output error occurs that causes a load operation to fail. + URLStream.load()httpResponseStatus + Dispatched if a call to the URLStream.load() method attempts to access data over HTTP + and Adobe AIR is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUSflash.events.HTTPStatusEvent + Dispatched if a call to the URLStream.load() method attempts to access data over HTTP + and Adobe AIR is able to detect and return the status code for the request. + +

If a URLStream object registers for an httpStatusEvent event, error responses + are delivered as though they are content. So instead of dispatching an ioError + event, the URLStream dispatches progress and complete events as + the error data is loaded into the URLStream.

+ +
URLStream.load()
httpStatus + Dispatched if a call to URLStream.load() + attempts to access data over HTTP, and Flash Player or Adobe AIR + is able to detect and return the status code for the request.flash.events.HTTPStatusEvent.HTTP_STATUSflash.events.HTTPStatusEvent + Dispatched if a call to URLStream.load() + attempts to access data over HTTP, and Flash Player or Adobe AIR + is able to detect and return the status code for the request. (Some browser environments + may not be able to provide this information.) Note that the httpStatus + (if any) will be sent before (and in addition to) any complete + or error event. + + URLStream.load()securityError + Dispatched if a call to URLStream.load() + attempts to load data from a server outside the security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched if a call to URLStream.load() + attempts to load data from a server outside the security sandbox. + + URLStream.load()complete + Dispatched when data has loaded successfully.flash.events.Event.COMPLETEflash.events.Event + Dispatched when data has loaded successfully. + close + Immediately closes the stream and + cancels the download operation.The stream could not be closed, or the stream was not open. + + IOErrorflash.errors:IOError + Immediately closes the stream and + cancels the download operation. + No data can be read from the stream after the close() method is called. + + load + Begins downloading the URL specified in the request parameter.URLRequest.requestHeader objects may not contain + certain prohibited HTTP request headers. For more information, see the URLRequestHeader class + description. + + ArgumentErrorArgumentErrorThis error can occur for the following reasons: + +
  1. Flash Player or Adobe AIR cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is + applicable if the URLRequest object passed to load() is set to perform a GET operation + and if System.useCodePage is set to true.
  2. Flash Player or Adobe AIR cannot allocate memory for + the POST data. This error is applicable if the URLRequest object passed to load is set + to perform a POST operation.
+ +
MemoryErrorflash.errors:MemoryError
Local untrusted SWF files may not communicate with + the Internet. This may be worked around by reclassifying this SWF file + as local-with-networking or trusted. + + SecurityErrorSecurityErrorYou are trying to connect to a commonly reserved port. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorrequestflash.net:URLRequestA URLRequest object specifying the URL to download. If the value of + this parameter or the URLRequest.url property of the URLRequest object + passed are null, the application throws a null pointer error. + +
+ Begins downloading the URL specified in the request parameter. + +

Note: If a file being loaded contains non-ASCII characters + (as found in many non-English languages), it is recommended that you save the file + with UTF-8 or UTF-16 encoding, as opposed to a non-Unicode format like ASCII.

+ +

If the loading operation fails immediately, an IOError or SecurityError + (including the local file security error) exception is thrown describing the failure. + Otherwise, an open event is dispatched if the URL download + starts downloading successfully, or an error event is dispatched if an error occurs.

+ +

By default, the calling SWF file and the URL you load must be in exactly the same domain. + For example, a SWF file at www.adobe.com can load data only from sources that are also at www.adobe.com. + To load data from a different domain, place a URL policy file on the server hosting the data.

+ +

In Flash Player, you cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

In Flash Player, you can prevent a SWF file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content.

+ +

In Flash Player 10 and later, and in AIR 1.5 and later, if you use a multipart + Content-Type (for example "multipart/form-data") + that contains an upload (indicated by a "filename" parameter in a "content-disposition" header within the POST body), + the POST operation is subject to the security rules applied to uploads:

+
  • The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
  • If the POST operation is cross-domain (the POST target is not on the same server as the SWF file + that is sending the POST request), + the target server must provide a URL policy file that permits cross-domain access.
+

Also, for any multipart Content-Type, the syntax must be valid (according to the RFC2046 standards). + If the syntax appears to be invalid, the POST operation is subject to the security rules applied to uploads.

+ +

These rules also apply to AIR content in non-application sandboxes. + However, in Adobe AIR, content in the application sandbox (content installed with the AIR application) + are not restricted by these security limitations.

+ +

For more information related to security, see The Flash Player Developer Center Topic: + Security.

+ +

In AIR, a URLRequest object can register for the httpResponse status event. + Unlike the httpStatus event, the httpResponseStatus event is + delivered before any response data. Also, the httpResponseStatus event includes + values for the responseHeaders and responseURL properties (which are + undefined for an httpStatus event. Note that the httpResponseStatus event + (if any) will be sent before (and in addition to) any complete or error + event. +

+ + +

If there is an httpResponseStatus event listener, the body of the response + message is always sent; and HTTP status code responses always results in a complete event. + This is true in spite of whether the HTTP response status code indicates a success or an error.

+ +

In AIR, if there is + no httpResponseStatus event listener, the behavior differs + based on the SWF version:

+ +
  • For SWF 9 content, the body of + the HTTP response message is sent only if the HTTP response status code indicates success. + Otherwise (if there is an error), no body is sent and the URLRequest object dispatches an IOError event.
  • For SWF 10 content, the body of + the HTTP response message is always sent. If there is an error, the URLRequest object dispatches + an IOError event.
+ + +
completeflash.events:EventDispatched after data has loaded successfully. If there is a httpResponseStatus + event listener, the URLRequest object also dispatches a complete event whether the HTTP response status code + indicates a success or an error. + + Dispatched after data has loaded successfully.httpStatusflash.events:HTTPStatusEventIf access is by HTTP and + the current environment supports obtaining status codes, you may + receive these events in addition to any complete + or error event. + + If access is by HTTP and + the current environment supports obtaining status codes, you may + receive these events in addition to any complete + or error event.httpResponseStatusflash.events:HTTPStatusEventDispatched if a call to the load() method attempts + to access data over HTTP and Adobe AIR is able to detect and return the status code for the request. + + Dispatched if a call to the load() method attempts + to access data over HTTP and Adobe AIR is able to detect and return the status code for the request.ioErrorflash.events:IOErrorEventThe load operation could not be + completed. + + The load operation could not be + completed.openflash.events:EventDispatched when a load operation starts. + + Dispatched when a load operation starts.securityErrorflash.events:SecurityErrorEventA load operation attempted + to retrieve data from a server outside the caller's security sandbox. + This may be worked around using a policy file on the server. + + A load operation attempted + to retrieve data from a server outside the caller's security sandbox.
readBoolean + Reads a Boolean value from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorTrue is returned if the byte is nonzero, false otherwise. + + Boolean + Reads a Boolean value from the stream. A single byte is read, + and true is returned if the byte is nonzero, + false otherwise. + + readByte + Reads a signed byte from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range -128...127. + + int + Reads a signed byte from the stream. +

The returned value is in the range -128...127.

+ +
readBytes + Reads length bytes of data from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, or the stream is not open. + + IOErrorflash.errors:IOErrorbytesflash.utils:ByteArrayThe ByteArray object to read + data into. + offsetuint0The offset into bytes at which data + read should begin. Defaults to 0. + lengthuint0The number of bytes to read. The default value + of 0 will cause all available data to be read. + + + Reads length bytes of data from the stream. + The bytes are read into the ByteArray object specified + by bytes, starting offset bytes into + the ByteArray object. + + readDouble + Reads an IEEE 754 double-precision floating-point number from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorAn IEEE 754 double-precision floating-point number from the stream. + + Number + Reads an IEEE 754 double-precision floating-point number from the stream. + + readFloat + Reads an IEEE 754 single-precision floating-point number from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorAn IEEE 754 single-precision floating-point number from the stream. + + Number + Reads an IEEE 754 single-precision floating-point number from the stream. + + readInt + Reads a signed 32-bit integer from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range -2147483648...2147483647. + + int + Reads a signed 32-bit integer from the stream. +

The returned value is in the range -2147483648...2147483647.

+ +
readMultiByte + Reads a multibyte string of specified length from the byte stream using the + specified character set.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorUTF-8 encoded string. + StringlengthuintThe number of bytes from the byte stream to read. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift_jis", "CN-GB", + "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + +

Note: If the value for the charSet parameter is not recognized + by the current system, the application uses the system's default code page as the character set. + For example, a value for the charSet parameter, as in + myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of 1 + might work on your development machine, but not on another machine. On the other machine, + the application will use the system's default code page.

+ +
+ Reads a multibyte string of specified length from the byte stream using the + specified character set. + +
readObject + Reads an object from the socket, encoded in Action Message Format (AMF).There is insufficient data available + to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorThe deserialized object. + + Reads an object from the socket, encoded in Action Message Format (AMF). + + ObjectEncodingreadShort + Reads a signed 16-bit integer from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range -32768...32767. + + int + Reads a signed 16-bit integer from the stream. +

The returned value is in the range -32768...32767.

+ +
readUTFBytes + Reads a sequence of length UTF-8 + bytes from the stream, and returns a string.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorA UTF-8 string produced by the byte representation of characters of specified length. + + StringlengthuintA sequence of UTF-8 bytes. + + + Reads a sequence of length UTF-8 + bytes from the stream, and returns a string. + + readUTF + Reads a UTF-8 string from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorA UTF-8 string. + + String + Reads a UTF-8 string from the stream. The string + is assumed to be prefixed with an unsigned short indicating + the length in bytes. + + readUnsignedByte + Reads an unsigned byte from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range 0...255. + + uint + Reads an unsigned byte from the stream. +

The returned value is in the range 0...255.

+ +
readUnsignedInt + Reads an unsigned 32-bit integer from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range 0...4294967295. + + uint + Reads an unsigned 32-bit integer from the stream. +

The returned value is in the range 0...4294967295.

+ +
readUnsignedShort + Reads an unsigned 16-bit integer from the stream.There is insufficient + data available to read. If a local SWF file triggers a security warning, + Flash Player prevents the URLStream data from being available to ActionScript. + When this happens, the bytesAvailable property returns 0 even if data has been + received, and any of the read methods throws an EOFError exception. + + + EOFErrorflash.errors:EOFErrorAn I/O error occurred on the stream, + or the stream is not open. + + IOErrorflash.errors:IOErrorValue in the range 0...65535. + + uint + Reads an unsigned 16-bit integer from the stream. +

The returned value is in the range 0...65535.

+ +
bytesAvailable + Returns the number of bytes of data available for reading + in the input buffer.uint + Returns the number of bytes of data available for reading + in the input buffer. + Your code must call the bytesAvailable property to ensure + that sufficient data is available before you try to read + it with one of the read methods. + + connected + Indicates whether this URLStream object is + currently connected.Boolean + Indicates whether this URLStream object is + currently connected. A call to this property returns a value of true + if the URLStream object is connected, or false otherwise. + endian + Indicates the byte order for the data.StringEndian.BIG_ENDIAN + + Indicates the byte order for the data. Possible values are + Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN. + flash.utils.EndianobjectEncoding + Controls the version of Action Message Format (AMF) used when writing or reading an object.uint + Controls the version of Action Message Format (AMF) used when writing or reading an object. + + readObject()ObjectEncoding class
NetGroupSendMode +The NetGroupSendMode class is an enumeration of constant values used for the sendMode parameter of the NetGroup.sendToNeighbor() +method.An enumeration of constant values used for the sendMode parameter of the sendToNeighbor() method in the NetGroup class. +method of the NetGroup class + +Object +The NetGroupSendMode class is an enumeration of constant values used for the sendMode parameter of the NetGroup.sendToNeighbor() +method. + +flash.net.NetGroup.sendToNeighbor()NEXT_DECREASING + Specifies the neighbor with the nearest group address in the decreasing direction.nextDecreasingString + Specifies the neighbor with the nearest group address in the decreasing direction. + + NEXT_INCREASING + Specifies the neighbor with the nearest group address in the increasing direction.nextIncreasingString + Specifies the neighbor with the nearest group address in the increasing direction. + + SharedObject + The SharedObject class is used to read and store limited amounts of data on a user's computer + or on a server.flash.events:EventDispatcher + The SharedObject class is used to read and store limited amounts of data on a user's computer + or on a server. + Shared objects offer real-time data sharing between multiple client SWF files and objects + that are persistent on the local computer or remote server. Local shared objects are similar + to browser cookies and remote shared objects are similar to real-time data transfer devices. + To use remote shared objects, you need Adobe Flash Media Server. + +

Use shared objects to do the following:

+ +
  • Maintain local persistence. + This is the simplest way to use a shared object, and does not require Flash Media Server. + For example, you can call SharedObject.getLocal() to create a shared object in an + application, such as a calculator with memory. When the user closes the calculator, + Flash Player saves the last value in a shared object on the user's computer. + The next time the calculator is run, it contains the values it had previously. + Alternatively, if you set the shared object's properties to null before the + calculator application is closed, the next time the + application runs, it opens without any values. + + Another example of maintaining local persistence is tracking user preferences or + other data for a complex website, such as a record of which + articles a user read on a news site. Tracking this information allows you to display + articles that have already been read differently from new, unread articles. + Storing this information on the user's computer reduces server load.
  • Store and share data on Flash Media Server. + A shared object can store data on the server for other clients to retrieve. + For example, call SharedObject.getRemote() to create a remote shared object, + such as a phone list, that is persistent on the server. Whenever a client makes changes + to the shared object, the revised data is available to all clients currently + connected to the object or who later connect to it. If the object is also persistent locally, + and a client changes data while not connected to the server, the data is copied to the remote shared + object the next time the client connects to the object.
  • Share data in real time. + A shared object can share data among multiple clients in real time. + For example, you can open a remote shared object that stores + a list of users connected to a chat room that is visible to all clients + connected to the object. When a user enters or leaves the chat room, the object + is updated and all clients that are connected to the object see the revised list + of chat room users.
+ +

To create a local shared object, call SharedObject.getLocal(). To create + a remote shared object, call SharedObject.getRemote().

+ +

When an application closes, shared objects are flushed, or written to a disk. + You can also call the flush() method to explicitly write data to a disk.

+ +

Local disk space considerations. Local shared objects have some limitations + that are important to consider as you design your application. + Sometimes SWF files may not be allowed to write local shared objects, and sometimes the data + stored in local shared objects can be deleted without your knowledge. Flash Player users + can manage the disk space that is available to individual domains or + to all domains. When users decrease the amount of disk space available, some local shared + objects may be deleted. Flash Player users also have privacy controls that can prevent + third-party domains (domains other than the domain in the current browser address bar) from + reading or writing local shared objects.

+ +

Note: SWF files that are stored and run on a local computer, not from a remote server, + can always write third-party shared objects to disk. + For more information about third-party shared objects, see the + Global Storage Settings panel in Flash Player Help.

+ +

It's a good idea to check for failures related to the amount of disk space and to + user privacy controls. Perform these checks when you call getLocal() and + flush(): + +

  • SharedObject.getLocal() — Flash Player throws an exception when + a call to this method fails, such as when the user has disabled + third-party shared objects and the domain of your SWF file does not match the domain in the browser + address bar.
  • SharedObject.flush() — Flash Player throws an exception + when a call to this method fails. It returns SharedObjectFlushStatus.FLUSHED when it succeeds. + It returns SharedObjectFlushStatus.PENDING + when additional storage space is needed. Flash Player prompts the user to allow an increase + in storage space for locally saved information. Thereafter, the netStatus event + is dispatched with an information object indicating whether the flush failed or succeeded.

+ +

If your SWF file attempts to create or modify local shared objects, make sure + that your SWF file is at least 215 pixels wide and at least 138 pixels high (the + minimum dimensions for displaying the dialog box that prompts users to increase their + local shared object storage limit). If your SWF file is smaller than these dimensions and an + increase in the storage limit is required, SharedObject.flush() fails, + returning SharedObjectFlushedStatus.PENDING and dispatching the netStatus event.

+ +

+ Remote shared objects. + With Flash Media Server, you can create and use remote shared objects, + that are shared in real-time by all clients connected to your application. + When one client changes a property of a remote shared object, the property + is changed for all connected clients. + You can use remote shared objects to synchronize clients, for example, users + in a multi-player game. +

+ +

+ Each remote shared object has a data property which is an Object with properties + that store data. Call setProperty() + to change an property of the data object. + The server updates the properties, dispatches a sync event, and + sends the properties back to the connected clients. +

+ +

+ You can choose to make remote shared objects persistent on the client, the server, + or both. By default, Flash Player saves locally persistent remote shared objects up to 100K in size. + When you try to save a larger object, Flash Player displays the Local Storage dialog box, + which lets the user allow or deny local storage for the shared object. + Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash + requires to display the dialog box. +

+

+ If the user selects Allow, the server saves the shared object and + dispatches a netStatus event with a code property of + SharedObject.Flush.Success. + If the user select Deny, the server does not save the shared object and dispatches + a netStatus event + with a code property of SharedObject.Flush.Failed. +

+ +
The following code creates (and on subsequent executions, retrieves) a shared object + object using the ID "application-name". When the Save button is clicked, the + saveValue() method attempts to save a property named savedValue + to the data property of the SharedObject object. If Flash Player must ask for permission to save + the data, when the user grants or denies permission the onFlushStatus() method is + called. When the Clear button is clicked, the clearValue() method deletes the value + saved in savedValue; the next time the SWF file is loaded, the value that is retrieved + is undefined. + + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.events.NetStatusEvent; + import flash.net.SharedObject; + import flash.net.SharedObjectFlushStatus; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFieldType; + + public class SharedObjectExample extends Sprite { + + private var mySo:SharedObject; + + public function SharedObjectExample() { + buildUI(); + saveBtn.addEventListener(MouseEvent.CLICK, saveValue); + clearBtn.addEventListener(MouseEvent.CLICK, clearValue); + + mySo = SharedObject.getLocal("application-name"); + output.appendText("SharedObject loaded...\n"); + output.appendText("loaded value: " + mySo.data.savedValue + "\n\n"); + } + + private function saveValue(event:MouseEvent):void { + output.appendText("saving value...\n"); + mySo.data.savedValue = input.text; + + var flushStatus:String = null; + try { + flushStatus = mySo.flush(10000); + } catch (error:Error) { + output.appendText("Error...Could not write SharedObject to disk\n"); + } + if (flushStatus != null) { + switch (flushStatus) { + case SharedObjectFlushStatus.PENDING: + output.appendText("Requesting permission to save object...\n"); + mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus); + break; + case SharedObjectFlushStatus.FLUSHED: + output.appendText("Value flushed to disk.\n"); + break; + } + } + output.appendText("\n"); + } + + private function clearValue(event:MouseEvent):void { + output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n"); + delete mySo.data.savedValue; + } + + private function onFlushStatus(event:NetStatusEvent):void { + output.appendText("User closed permission dialog...\n"); + switch (event.info.code) { + case "SharedObject.Flush.Success": + output.appendText("User granted permission -- value saved.\n"); + break; + case "SharedObject.Flush.Failed": + output.appendText("User denied permission -- value not saved.\n"); + break; + } + output.appendText("\n"); + + mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus); + } + + // UI elements + private var inputLbl:TextField; + private var input:TextField; + private var output:TextField; + private var saveBtn:Sprite; + private var clearBtn:Sprite; + + private function buildUI():void { + // input label + inputLbl = new TextField(); + addChild(inputLbl); + inputLbl.x = 10; + inputLbl.y = 10; + inputLbl.text = "Value to save:"; + + // input TextField + input = new TextField(); + addChild(input); + input.x = 80; + input.y = 10; + input.width = 100; + input.height = 20; + input.border = true; + input.background = true; + input.type = TextFieldType.INPUT; + + // output TextField + output = new TextField(); + addChild(output); + output.x = 10; + output.y = 35; + output.width = 250; + output.height = 250; + output.multiline = true; + output.wordWrap = true; + output.border = true; + output.background = true; + + // Save button + saveBtn = new Sprite(); + addChild(saveBtn); + saveBtn.x = 190; + saveBtn.y = 10; + saveBtn.useHandCursor = true; + saveBtn.graphics.lineStyle(1); + saveBtn.graphics.beginFill(0xcccccc); + saveBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5); + var saveLbl:TextField = new TextField(); + saveBtn.addChild(saveLbl); + saveLbl.text = "Save"; + saveLbl.selectable = false; + + // Clear button + clearBtn = new Sprite(); + addChild(clearBtn); + clearBtn.x = 230; + clearBtn.y = 10; + clearBtn.useHandCursor = true; + clearBtn.graphics.lineStyle(1); + clearBtn.graphics.beginFill(0xcccccc); + clearBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5); + var clearLbl:TextField = new TextField(); + clearBtn.addChild(clearLbl); + clearLbl.text = "Clear"; + clearLbl.selectable = false; + } + } +} +
flush()getLocal()netStatussync + Dispatched when a remote shared object has been updated by the server.flash.events.SyncEvent.SYNCflash.events.SyncEvent + Dispatched when a remote shared object has been updated by the server. + + getRemote()netStatus + Dispatched when a SharedObject instance is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent + Dispatched when a SharedObject instance is reporting its status or error condition. + The netStatus event contains an info property, + which is an information object + that contains specific information about the event, such as whether a connection + attempt succeeded or whether the shared object was successfully written to the local disk. + + flash.events.NetStatusEvent.infoasyncError + Dispatched when an exception is thrown asynchronously &#x2014; that is, + from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent + Dispatched when an exception is thrown asynchronously — that is, + from native asynchronous code. + + clear + For local shared objects, purges all of the data and deletes the shared object from the disk. + For local shared objects, purges all of the data and deletes the shared object from the disk. + The reference to the shared object is still active, but its data properties are deleted. + +

+ For remote shared objects used with Flash Media Server, + clear() disconnects the object and purges + all of the data. If the shared object is locally persistent, this method also deletes the shared object + from the disk. The reference to the shared object is still active, but its data properties + are deleted. +

+ + +
The following code creates (and on subsequent executions, retrieves) a SharedObject + object using an id with the value of hostName. A property named username + is added to the data property of the SharedObject object. + The clear() method is finally called, which wipes out all information that was added + to the data object (in this case was a single property named username). + + +package { + import flash.net.SharedObject; + + public class SharedObject_clear { + private var hostName:String = "yourDomain"; + private var username:String = "yourUsername"; + + public function SharedObject_clear() { + var mySo:SharedObject = SharedObject.getLocal(hostName); + if(mySo.data.username == null) { + mySo.data.username = username; + trace("set: " + mySo.data.username); // yourUsername + } + else { + mySo.clear(); + trace("cleared: " + mySo.data.username); // undefined + } + } + } +} +
close + Closes the connection between a remote shared object and the server. + Closes the connection between a remote shared object and the server. + If a remote shared object is locally persistent, the user can make changes + to the local copy of the object after this method is called. Any changes made + to the local object are sent to the server the next time the user connects + to the remote shared object. + + connect + Connects to a remote shared object on a server through a specified NetConnection object.Flash Player could not connect to the specified remote shared object. + Verify that the NetConnection instance is valid and connected and that the + remote shared object was successfully created on the server. + + ErrorErrormyConnectionflash.net:NetConnectionA NetConnection object that uses the Real-Time Messaging Protocol (RTMP), + such as a NetConnection object used to communicate with Flash Media Server. + + paramsStringnullA string defining a message to pass to the remote shared object on the server. + Cannot be used with Flash Media Server. + + + Connects to a remote shared object on a server through a specified NetConnection object. + Use this method after calling getRemote(). + When a connection is successful, the sync event is dispatched. + +

Before attempting to work with a remote shared object, + first check for any errors using a try..catch..finally statement. + Then, listen for and handle the sync event before + you make changes to the shared object. Any changes made + locally — before the sync event is dispatched — might be lost. +

+ +

+ Call the connect() method + to connect to a remote shared object, for example: +

+ + + var myRemoteSO:SharedObject = SharedObject.getRemote("mo", myNC.uri, false); + myRemoteSO.connect(myNC); + + + + +
getRemote()synctry..catch..finallyNetConnection
flush + Immediately writes a locally persistent shared object to a local file.Flash Player cannot write the shared object to disk. This error might + occur if the user has permanently disallowed local information storage for + objects from this domain. + + +

Note: Local content can always write shared objects + from third-party domains (domains other than the domain in the current browser address bar) + to disk, even if writing of third-party shared objects to disk is disallowed.

+ +
ErrorError
Either of the following values: +
  • SharedObjectFlushStatus.PENDING: The user has permitted local information + storage for objects from this domain, but the + amount of space allotted is not sufficient to store the object. Flash Player prompts + the user to allow more space. + To allow space for the shared object to grow when it is saved, thus avoiding + a SharedObjectFlushStatus.PENDING return value, pass a value + for minDiskSpace. +
  • SharedObjectFlushStatus.FLUSHED: The shared object has been + successfully written to a file on the local disk.
+ +
String
minDiskSpaceint0The minimum disk space, in bytes, + that must be allotted for this object. + +
+ Immediately writes a locally persistent shared object to a local file. If you don't use this + method, Flash Player writes the shared object to a file when the shared object session ends — + that is, when the SWF file is closed, when the shared object is garbage-collected + because it no longer has any references to it, or when you call SharedObject.clear() + or SharedObject.close(). + +

If this method returns SharedObjectFlushStatus.PENDING, + Flash Player displays a dialog box asking + the user to increase the amount of disk space available to objects from this domain. To allow + space for the shared object to grow when it is saved in the future, which avoids return values + of PENDING, pass a value for minDiskSpace. When Flash Player + tries to write the file, it looks for the number of bytes passed to + minDiskSpace, instead of looking for enough space to save the shared + object at its current size.

+ +

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even + though it might start out much smaller, pass 500 for minDiskSpace. If + Flash asks the user to allot disk space for the shared object, it asks for 500 bytes. After + the user allots the requested amount of space, Flash won't have to ask for more space on future + attempts to flush the object (as long as its size doesn't exceed 500 bytes).

+ +

After the user responds to the dialog box, this method is called again. A + netStatus event is dispatched with a code property of + SharedObject.Flush.Success or SharedObject.Flush.Failed. +

+ +
The following code creates (and on subsequent executions, retrieves) a SharedObject + object using an id with the value of hostName. A property named username + is added to the data property of the SharedObject object. The flush() method is + then called, followed by a check to see if the string pending, or a boolean value + of true or false was returned. + One should be aware that all open SharedObject instances will automatically be flushed whenever the + current instance of the Flash Player is closed. + +package { + import flash.net.SharedObject; + + public class SharedObject_flush { + private var hostName:String = "yourDomain"; + private var username:String = "yourUsername"; + + public function SharedObject_flush() { + var mySo:SharedObject = SharedObject.getLocal(hostName); + mySo.data.username = username; + var flushResult:Object = mySo.flush(); + trace("flushResult: " + flushResult); + trace(mySo.data.username); // yourUsername + } + } +} +
clear()
getLocal + Returns a reference to a locally persistent shared object that is only available to the current client.Flash Player cannot create the shared object for whatever reason. + This error might occur is if persistent shared object creation + and storage by third-party Flash content is prohibited (does not apply to local content). + Users can prohibit third-party persistent shared objects on the Global Storage Settings panel of the + Settings Manager, located at + http://www.adobe.com/support/documentation/en/flashplayer/help/settings_manager03.html. + + ErrorErrorA reference to a shared object that is persistent locally and is available only to the + current client. If Flash Player can't create or find the shared object (for example, if + localPath was + specified but no such directory exists), this method throws an exception. + + flash.net:SharedObjectnameStringThe name of the object. The name can include forward slashes (/); for example, + work/addresses is a legal name. Spaces are not allowed in a shared + object name, nor are the following characters: +
+  ~ % & \ ; : " ' , < > ? # 
+  
+ +
localPathStringnullThe full or partial path to the SWF file that created the shared object, and that + determines where the shared object will be stored locally. If you do not specify this parameter, the + full path is used. + + secureBooleanfalseDetermines whether access to this shared object + is restricted to SWF files that are delivered over an HTTPS connection. + If your SWF file is delivered over HTTPS, this parameter's value has the following effects: +
  • If this parameter is set to true, Flash Player creates a new secure shared object or + gets a reference to an existing secure shared object. This secure shared object + can be read from or written to only by SWF files delivered over HTTPS that call + SharedObject.getLocal() with the secure parameter set to + true.
  • If this parameter is set to false, Flash Player creates a new shared object or + gets a reference to an existing shared object that can be read from + or written to by SWF files delivered over non-HTTPS connections.
+

If your SWF file is delivered over a non-HTTPS connection and you try to set this parameter + to true, the creation of a new shared object (or the access of a previously + created secure shared object) fails and null is returned. Regardless of the + value of this parameter, the created shared objects count toward the total amount + of disk space allowed for a domain.

+ +

The following diagram shows the use of the secure parameter:

+

+ +
+ Returns a reference to a locally persistent shared object that is only available to the current client. + If the shared object does not already exist, this method creates one. If any values + passed to getLocal() are invalid or if the call fails, Flash Player throws an exception. + +

The following code shows how you assign the returned shared object reference to a variable:

+

var so:SharedObject = SharedObject.getLocal("savedData");

+ +

Note: If the user has chosen to never allow local storage for this domain, + the object is not saved locally, even if a value for localPath is specified. The + exception to this rule is local content. Local content can always write shared objects + from third-party domains (domains other than the domain in the current browser address bar) + to disk, even if writing of third-party shared objects to disk is disallowed. +

+ +

To avoid name conflicts, Flash looks at the location of the SWF file creating the + shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a + shared object named portfolio, that shared object does not conflict with another + object named portfolio that was created by a SWF file at + www.yourCompany.com/photoshoot.swf because the SWF files originate from different directories.

+ +

Although the localPath parameter is optional, you should give some + thought to its use, especially if other SWF files need to access the shared object. If the + data in the shared object is specific to one SWF file that will not be moved to another location, + then use of the default value makes sense. If other SWF files need access to the shared object, or + if the SWF file that creates the shared object will later be moved, then the value of this parameter + affects how accessible the shared object will be. For example, if you create a shared object with + localPath set to the default value of the full path to the SWF file, no other SWF + file can access that shared object. If you later move the original SWF file to another location, + not even that SWF file can access the data already stored in the shared object.

+ +

To avoid inadvertently restricting access to a shared object, use + the localpath parameter. The most permissive approach is to set + localPath to / (slash), which makes the shared object available to all SWF files + in the domain, but increases the likelihood of name conflicts with other shared objects in + the domain. A more restrictive approach is to append localPath with folder names that are in + the full path to the SWF file. For example, for a portfolio shared object created by the SWF + file at www.myCompany.com/apps/stockwatcher.swf, you could set the localPath parameter to + /, /apps, or /apps/stockwatcher.swf. You must determine which + approach provides optimal flexibility for your application.

+ +

When using this method, consider the following security model: + +

  • You cannot access shared objects across sandbox boundaries.
  • Users can restrict shared object access by using the Flash Player Settings dialog box + or the Settings Manager. By default, an application can create shared objects of up 100 KB of data per domain. + Administrators and users can also place restrictions on the ability to write to the file system.

+ +

Suppose you publish SWF file content to be played back as local files (either locally installed SWF files or + EXE files), and you need to access a specific shared object from more than one local SWF file. In this situation, + be aware that for local files, two different locations might be used to store shared objects. The domain that is + used depends on the security permissions granted to the local file that created the shared object. Local files + can have three different levels of permissions: + +

  1. Access to the local filesystem only.
  2. Access to the network only.
  3. Access to both the network and the local filesystem.

+ +

Local files with access to the local filesystem (level 1 or 3) store their shared objects in one location. + Local files without access to the local filesystem (level 2) store their shared objects in another location.

+ +

You can prevent a SWF file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content.

+ +

For more information, see the Flash Player Developer Center Topic: + Security.

+ +
getRemote + Returns a reference to a shared object on Flash Media Server that multiple + clients can access.Flash Player can't create or find the shared object. This might occur if nonexistent paths were + specified for the remotePath and persistence parameters. + + + ErrorErrorA reference to an object that can be shared across multiple clients. + + flash.net:SharedObjectnameStringThe name of the remote shared object. The name can include forward slashes (/); + for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, + nor are the following characters: +
    ~ % & \ ; :  " ' , > ? ? #
+ +
remotePathStringnullThe URI of the server on which the shared object will be stored. + This URI must be identical to the URI of the NetConnection object passed to the + connect() method. + + persistenceObjectfalseSpecifies whether the attributes of the shared + object's data property are persistent locally, remotely, or both. This parameter can also specify + where the shared object will be stored locally. Acceptable values are as follows: +
  • A value of false specifies that the shared object is not persistent + on the client or server.
  • A value of true specifies that the shared object is persistent only on the server.
  • A full or partial local path to the shared object indicates that the shared + object is persistent on the client and the server. On the client, it is stored in the + specified path; on the server, it is stored in a subdirectory within the application + directory.
+ +

Note: If the user has chosen to never allow local storage + for this domain, the object will not be saved locally, even if a local path is + specified for persistence. For more information, see the class description.

+ +
secureBooleanfalseDetermines whether access to this shared object is restricted to SWF + files that are delivered over an HTTPS connection. For more information, see the + description of the secure parameter in the + getLocal method entry. + +
+ Returns a reference to a shared object on Flash Media Server that multiple + clients can access. + If the remote shared object does not already exist, this method creates one. + +

+ To create a remote shared object, call getRemote() the call + connect() to connect the remote shared object to the server, as in + the following:

+ + + var nc:NetConnection = new NetConnection(); + nc.connect("rtmp://somedomain.com/applicationName"); + var myRemoteSO:SharedObject = SharedObject.getRemote("mo", nc.uri, false); + myRemoteSO.connect(nc); + + + + +

+ To confirm that the local and remote copies of the shared object are synchronized, + listen for and handle the sync event. + All clients that want to share this object must pass the same values for + the name and remotePath parameters. +

+ +

To create a shared object that is available only to the current client, + use SharedObject.getLocal(). +

+ +
connect()getLocal()
send + Broadcasts a message to all clients connected to a remote shared object, + including the client that sent the message.argumentsOne or more arguments: A string that identifies the message, + the name of one or more handler functions to attach to the shared object, + and optional parameters of any type. + The handler name can be only one level deep (that is, it can't be of the + form parent/child) and is relative to the shared object. + The arguments are serialized and sent over the connection, and the + receiving handler receives them in the same order. If a parameter is a + circular object (for example, a linked list that is circular), the + serializer handles the references correctly. + +

Note: Do not use a reserved term for the function names. + For example, myRemoteSO.send("close") will fail.

+ +
+ Broadcasts a message to all clients connected to a remote shared object, + including the client that sent the message. To process and respond to the message, + create a callback function attached to the shared object. + +
setDirty + Indicates to the server that the value of a property + in the shared object has changed.propertyNameStringThe name of the property that has changed. + + + Indicates to the server that the value of a property + in the shared object has changed. + This method marks properties as dirty, which means changed. + +

+ Call the SharedObject.setProperty() to create properties for a shared object. +

+ +

+ The SharedObject.setProperty() method implements setDirty(). + In most cases, such as when the value of a property is a primitive type like String or Number, + you can call setProperty() instead of calling setDirty(). + However, when the value of a property is an object that contains its own properties, + call setDirty() to indicate when a value within the object has changed. +

+ +
SharedObject.data (client-side property)setProperty()
setProperty + Updates the value of a property in a shared object and indicates to the server + that the value of the property has changed.propertyNameStringThe name of the property in the shared object. + valueObjectnullThe value of the property (an ActionScript object), or null to delete the property. + + + Updates the value of a property in a shared object and indicates to the server + that the value of the property has changed. The setProperty() method + explicitly marks properties as changed, or dirty. + +

For more information about remote shared objects see the + + Flash Media Server documentation.

+ +

Note: The SharedObject.setProperty() method implements the setDirty() method. + In most cases, such as when the value of a property is a primitive type like String or Number, + you would use setProperty() instead of setDirty. + However, when the value of a property is an object that contains its own properties, + use setDirty() to indicate when a value within the object has changed. + In general, it is a good idea to call setProperty() rather than setDirty(), because + setProperty() updates a property value only when that value has changed, whereas setDirty() + forces synchronization on all subscribed clients.

+ +
SharedObject.data (client-side property)
client + Indicates the object on which + callback methods are invoked.ObjectThe client property must be set to a non-null object. + + TypeErrorTypeError + Indicates the object on which + callback methods are invoked. The default object is this. + You can set the client property to another object, and callback methods will be + invoked on that other object. + + data + The collection of attributes assigned to the data property of the object; these attributes can + be shared and stored.Object + The collection of attributes assigned to the data property of the object; these attributes can + be shared and stored. Each attribute can be an object of any ActionScript or JavaScript + type — Array, Number, Boolean, ByteArray, XML, and so on. For example, the following lines assign values to various aspects + of a shared object: + + + var items_array:Array = new Array(101, 346, 483); + var currentUserIsAdmin:Boolean = true; + var currentUserName:String = "Ramona"; + + var my_so:SharedObject = SharedObject.getLocal("superfoo"); + my_so.data.itemNumbers = items_array; + my_so.data.adminPrivileges = currentUserIsAdmin; + my_so.data.userName = currentUserName; + + for (var prop in my_so.data) { + trace(prop+": "+my_so.data[prop]); + } + + + + +

All attributes of a shared object's data property are saved if the object is persistent, and + the shared object contains the following information:

+ + + userName: Ramona + adminPrivileges: true + itemNumbers: 101,346,483 + + +

Note: Do not assign values directly to the data property of a shared + object, as in so.data = someValue; Flash Player ignores these assignments.

+ +

To delete attributes for local shared objects, use code such as + delete so.data.attributeName; setting an attribute to + null or undefined for a local shared object does not + delete the attribute.

+ +

To create private values for a shared object — values that are available only to the client + instance while the object is in use and are not stored with the object when it is closed — create properties + that are not named data to store them, as shown in the following example:

+ + + var my_so:SharedObject = SharedObject.getLocal("superfoo"); + my_so.favoriteColor = "blue"; + my_so.favoriteNightClub = "The Bluenote Tavern"; + my_so.favoriteSong = "My World is Blue"; + + for (var prop in my_so) { + trace(prop+": "+my_so[prop]); + } + + + + +

The shared object contains the following data:

+ + favoriteSong: My World is Blue + favoriteNightClub: The Bluenote Tavern + favoriteColor: blue + data: [object Object] + + +

+ For remote shared objects used with a server, all attributes of the data + property are available to all clients connected to the shared object, and all attributes + are saved if the object is persistent. + If one client changes the value of an attribute, all clients now see the new value. +

+ +
getLocal()
defaultObjectEncoding + The default object encoding (AMF version) for all local shared objects created in the SWF file.uint + The default object encoding (AMF version) for all local shared objects created in the SWF file. + When local shared objects are written to disk, the + SharedObject.defaultObjectEncoding property + indicates which Action Message Format version should be used: the ActionScript 3.0 format (AMF3) or the ActionScript 1.0 or 2.0 format (AMF0). + +

For more information about object encoding, including the difference between + encoding in local and remote shared objects, see the description of the + objectEncoding property.

+ +

The default value of SharedObject.defaultObjectEncoding is set to use the + ActionScript 3.0 format, AMF3. + If you need to write local shared objects that ActionScript 2.0 or 1.0 SWF files can read, + set SharedObject.defaultObjectEncoding to use the + ActionScript 1.0 or ActionScript 2.0 format, flash.net.ObjectEncoding.AMF0, + at the beginning of your script, before you create any local shared objects. + All local shared objects + created thereafter will use AMF0 encoding and can interact with older content. + You cannot change the objectEncoding value of existing local shared objects + by setting SharedObject.defaultObjectEncoding after the local shared + objects have been created.

+ +

To set the object encoding on a per-object basis, rather than for all shared objects + created by the SWF file, set the objectEncoding property of the local shared object instead.

+ +
objectEncoding propertyObjectEncoding class
objectEncoding + The object encoding (AMF version) for this shared object.uintYou attempted to set the value of the objectEncoding + property on a remote shared object. This property is read-only for remote shared objects because + its value is determined by the associated NetConnection instance. + + ReferenceErrorReferenceError + The object encoding (AMF version) for this shared object. When a local shared object is written to disk, + the objectEncoding property indicates which Action + Message Format version should be used: the ActionScript 3.0 format (AMF3) + or the ActionScript 1.0 or 2.0 format (AMF0). + +

Object encoding is handled differently depending if the shared object + is local or remote.

+
  • Local shared objects. You can get or set the value of the + objectEncoding property for local shared objects. + The value of objectEncoding + affects what formatting is used for writing this local shared object. + If this local shared object must be readable by + ActionScript 2.0 or 1.0 SWF files, set objectEncoding to + ObjectEncoding.AMF0. + Even if object encoding is set to write AMF3, Flash Player can still read AMF0 local shared objects. + That is, if you use the default value of this property, ObjectEncoding.AMF3, + your SWF file can still read shared objects created by ActionScript 2.0 or 1.0 SWF files. +
  • Remote shared objects. When connected to the server, a remote shared object + inherits its objectEncoding setting from the associated NetConnection + instance (the instance used to connect to the remote shared object). When not connected + to the server, a remote shared object inherits the defaultObjectEncoding + setting from the associated NetConnection instance. + Because the value of a remote shared object's objectEncoding property is + determined by the NetConnection instance, this property is read-only for remote shared objects. +
+ +
defaultObjectEncodingflash.net.ObjectEncoding
size + The current size of the shared object, in bytes.uint + The current size of the shared object, in bytes. + +

Flash calculates the size of a shared object by stepping through all of its data + properties; the more data properties the object has, the longer it takes to estimate its size. + Estimating object size can take significant processing time, so you + may want to avoid using this method unless you have a specific need for it.

+ +
The following code creates a SharedObject object using an id "thehobbit". + A property named username is added to the data property of the SharedObject object. + The size property is then traced, which returns the value indicated. + + +import flash.net.SharedObject; + +// if these get copied or not +var mySo:SharedObject = SharedObject.getLocal("thehobbit"); +mySo.data.username = "bilbobaggins"; +trace(mySo.size); // 55 +
fps + Specifies the number of times per second that a client's changes to a + shared object are sent to the server.Number + Specifies the number of times per second that a client's changes to a + shared object are sent to the server. + +

Use this method when you want to control the amount of traffic between + the client and the server. For example, if the connection between the client + and server is relatively slow, you may want to set fps + to a relatively low value. Conversely, if the client is connected to a multiuser + application in which timing is important, you may want to set fps + to a relatively high value.

+ +

Setting fps will trigger a sync event and update all changes to the server. + If you only want to update the server manually, set fps to 0.

+ +

Changes are not sent to the server until the sync event has been dispatched. + That is, if the response time from the server is slow, updates may be sent to + the server less frequently than the value specified in this property.

+ +
NetGroupInfo +The NetGroupInfo class specifies various Quality of Service (QoS) statistics +related to a NetGroup object's underlying RTMFP Peer-to-Peer data transport.Object +The NetGroupInfo class specifies various Quality of Service (QoS) statistics +related to a NetGroup object's underlying RTMFP Peer-to-Peer data transport. +The NetGroup.info property returns a NetGroupInfo object which is +a snapshot of the current QoS state. + +flash.net.NetGroup.infoflash.net.NetGroup.post()flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()flash.net.NetGroup.addWantObjects()flash.net.NetGroup.writeRequestedObject()toString + Returns a string containing the values of the properties of the NetGroupInfo object.A string containing the values of the properties of the NetGroupInfo object + + StringReturns a text value listing the properties of this NetGroupInfo object. + + Returns a string containing the values of the properties of the NetGroupInfo object. + + objectReplicationReceiveBytesPerSecond + Specifies the rate at which the local node is receiving objects from + peers via the Object Replication system, in bytes per second.Number + Specifies the rate at which the local node is receiving objects from + peers via the Object Replication system, in bytes per second. + + flash.net.NetGroup.writeRequestedObject()objectReplicationSendBytesPerSecond + Specifies the rate at which objects are being copied from the local node to peers + by the Object Replication system, in bytes per second.Number + Specifies the rate at which objects are being copied from the local node to peers + by the Object Replication system, in bytes per second. + + flash.net.NetGroup.writeRequestedObject()postingReceiveControlBytesPerSecond + Specifies the rate at which the local node is receiving posting control overhead messages from peers, in bytes per second.Number + Specifies the rate at which the local node is receiving posting control overhead messages from peers, in bytes per second. + + flash.net.NetGroup.post()postingReceiveDataBytesPerSecond + Specifies the rate at which the local node is receiving posting data from + peers, in bytes per second.Number + Specifies the rate at which the local node is receiving posting data from + peers, in bytes per second. + + flash.net.NetGroup.post()postingSendControlBytesPerSecond + Specifies the rate at which the local node is sending posting control overhead messages to peers, in bytes per second.Number + Specifies the rate at which the local node is sending posting control overhead messages to peers, in bytes per second. + + flash.net.NetGroup.post()postingSendDataBytesPerSecond + Specifies the rate at which the local node is sending posting data to + peers, in bytes per second.Number + Specifies the rate at which the local node is sending posting data to + peers, in bytes per second. + + flash.net.NetGroup.post()routingReceiveBytesPerSecond + Specifies the rate at which the local node is receiving directed routing messages + from peers, in bytes per second.Number + Specifies the rate at which the local node is receiving directed routing messages + from peers, in bytes per second. + + flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()routingSendBytesPerSecond + Specifies the rate at which the local node is sending directed routing messages to + peers, in bytes per second.Number + Specifies the rate at which the local node is sending directed routing messages to + peers, in bytes per second. + + flash.net.NetGroup.sendToNearest()flash.net.NetGroup.sendToNeighbor()flash.net.NetGroup.sendToAllNeighbors()URLLoaderDataFormat + The URLLoaderDataFormat class provides values that specify how downloaded data is received.Object + The URLLoaderDataFormat class provides values that specify how downloaded data is received. + + The following example uses the URLLoaderDataFormatExample class to display + data format and status information for a file loaded at runtime. This is accomplished + using the following steps: +
  1. The class constructor creates a URLLoader instance named loader and a URLRequest + instance named request, which is the location and name of the file to be loaded.
  2. The loader object is passed to the configureListeners() method, which adds + listeners for each of the supported URLLoader events: +
    • completeHandler(): listens for the complete event, which is dispatched + after TextFile.txt has successfully loaded.
    • openHandler(): listens for the open event, dispatched upon start of the + download (to the player) of TextFile.txt.
    • progressHandler(): listens for the progress events, dispatched when data + is received as the download operation progresses.
    • securityErrorHandler(): listens for securityError events, which would be + dispatched if the text file was accessed with the wrong local playback security setting.
    • httpStatusHandler(): listens for httpStatusHandler events, which will not be + dispatched in this case since TextFile.txt is local.
    • ioErrorHandler(): listens for ioError events, which would happen only + if there were a serious problem with the file, such as if it were missing.
  3. The request object is then passed to the loader.load() method, which loads the text file + into memory using a DisplayObject object.
+

Notes: +

  • You will need to compile the SWF file with "Local playback security" set to "Access local files only". +
  • This example requires that a file named TextFile.txt be placed in the same directory as your SWF file. + If you would like to see this example identify binary or URL-encoded data files, you will need to + provide the file in the proper data format and change TextFile.txt to the name and location of the new + file.
+

+ + +package { + import flash.display.Sprite; + import flash.events.*; + import flash.net.*; + + public class URLLoaderDataFormatExample extends Sprite { + private var source:String = "TextFile.txt"; + private var dataFormat:String = URLLoaderDataFormat.TEXT; + + public function URLLoaderDataFormatExample () { + var loader:URLLoader = new URLLoader(); + loader.dataFormat = dataFormat; + configureListeners(loader); + var request:URLRequest = new URLRequest(source); + try { + loader.load(request); + } catch (error:Error) { + trace("Error loading requested document: " + source); + } + } + + private function configureListeners(dispatcher:URLLoader):void { + dispatcher.addEventListener(Event.COMPLETE, completeHandler); + dispatcher.addEventListener(Event.OPEN, openHandler); + dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); + dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); + dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + var loader:URLLoader = URLLoader(event.target); + switch(loader.dataFormat) { + case URLLoaderDataFormat.TEXT : + trace("completeHandler (text): " + loader.data); + break; + case URLLoaderDataFormat.BINARY : + trace("completeHandler (binary): " + loader.data); + break; + case URLLoaderDataFormat.VARIABLES : + trace("completeHandler (variables): " + loader.data); + break; + } + } + + private function httpStatusHandler(event:Event):void { + trace("httpStatusHandler: " + event); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("ioErrorHandler: " + event); + } + + private function openHandler(event:Event):void { + trace("openHandler: " + event); + } + + private function progressHandler(event:ProgressEvent):void { + trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + } +} +
BINARY + Specifies that downloaded data is received as raw binary data.binaryString + Specifies that downloaded data is received as raw binary data. + TEXT + Specifies that downloaded data is received as text.textString + Specifies that downloaded data is received as text. + VARIABLES + Specifies that downloaded data is received as URL-encoded variables.variablesString + Specifies that downloaded data is received as URL-encoded variables. +
NetStreamPlayTransitions + + The NetStreamPlayTransitions class specifies the valid strings that you can use with the + NetStreamPlayOptions.transition property.Object + + The NetStreamPlayTransitions class specifies the valid strings that you can use with the + NetStreamPlayOptions.transition property. These strings control the + behavior that is used to transition to a new stream or to play a stream, depending on the + transition mode that is used. + + NetStreamPlayOptionsNetStream.play2()APPEND_AND_WAIT + + Builds a playlist without starting to play it from the first stream.appendAndWaitString + + Builds a playlist without starting to play it from the first stream. + +

The APPEND_AND_WAIT transition mode is used with the NetStream.play2() method to build a playlist without + immediately starting to play it from the first stream. Use this mode to load each item in the playlist except the last one. + When you load the last stream in the playlist, set the transition mode to RESUME. + At this point, Flash Player begins to stream and play the playlist.

+ +

You can use this mode to build a playlist from scratch, or to rebuild a playlist after a lost connection is recovered. + For a new playlist, when NetStream.play2() is called with RESUME, Flash Player begins streaming + and playing from the first stream, or from the start position specified. + To recover from a lost connection, when you call the NetStream.play2() method with + RESUME, Flash Player determines where the stream was interrupted and instructs the server to start streaming from that location. + The server in turn is able to determine which stream in the playlist corresponds to that location, and starts streaming from that location.

+ +

This transition mode is in contrast to the APPEND mode, where playback starts immediately with the first stream.

+ +
APPENDRESUMENetStream.play2()
APPEND + + Adds the stream to a playlist and begins playback with the first stream.appendString + + Adds the stream to a playlist and begins playback with the first stream. This mode does the same thing as the NetStream.play() + method with the reset flag set to false. + +

In this mode, Flash Media Server queues up the stream specified in NetStreamPlayOptions.streamName + at the end of the playlist and ignores the NetStreamPlayOptions.oldStreamName parameter.

+ +
APPEND_AND_WAITNetStream.play()NetStream.play2()NetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
RESET + + Clears any previous play calls and plays the specified stream immediately.resetString + + Clears any previous play calls and plays the specified stream immediately. + This mode does the same thing as the NetStream.play() method with the reset flag set to true + (the default behavior for NetStream.play()). + +

In this mode, the currently playing stream is flushed and the stream specified in NetStreamPlayOptions.streamName starts to play. + The NetStreamPlayOptions.oldStreamName parameter is ignored.

+ +
NetStream.play()NetStream.play2()NetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
RESUME + + Requests data from the new connection starting from the point at which the previous connection ended.resumeString + + Requests data from the new connection starting from the point at which the previous connection ended. + The RESUME mode aligns the stream across the two connections so no artifacts or jumps are observed + in the video playback. Use this mode when you reconnect a stream that was dropped due to server issues + or other connection problems. + + APPEND_AND_WAITNetStream.play2()STOP + + Stops playing the streams in a playlist.stopString + + Stops playing the streams in a playlist. This mode does the same thing as calling NetStream.play(false). + It stops and resets the playlist. + + NetStream.play()NetStream.play2()SWAP + Replaces a content stream with a different content stream and maintains the rest of the playlist.swapString + Replaces a content stream with a different content stream and maintains the rest of the playlist. + +

This mode replaces the stream specified in NetStreamPlayOptions.oldStreamName + with the stream specified in NetStreamPlayOptions.streamName. The rest of the playlist is maintained. + In this mode, Flash Media Server does not make assumptions about the content of the streams and treats + them like different content.

+ +

If oldStreamName has not yet been sent, the server performs the switch + at the stream boundary and sends the bits for streamName from the beginning. + If the server has already started sending the bits for oldStreamName, it doesn't switch to streamName, + and a NetStream.Play.Failed event is sent.

+ +

Use this mode if the streams you want to switch are not related to each other and have different content or lengths. For example, + use this mode when you want to swap one commercial for another based on user tracking and past commercial-viewing statistics.

+ +

To switch from one stream to another with the same content, use the SWITCH mode instead.

+ +
SWITCHNetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
SWITCH + Switches from playing one stream to another stream, typically with streams of the same content.switchString + Switches from playing one stream to another stream, typically with streams of the same content. + Specify the streams to switch in NetStreamPlayOptions.oldStreamName and NetStreamPlayOptions.streamName. + +

Use this mode when you want to switch to a stream that has the same content but is encoded + at a different bit rate or resolution. For example, use this mode when the application queues up streams in a playlist + or is playing a single stream at a particular bit rate, then calculates that the bandwidth availability + or the CPU capability is either lower or higher than the stream requirements. The application can then + update the streams with their higher or lower bit rate versions.

+ +

In this mode, Flash Media Server makes certain assumptions about the relationship between the + oldStreamName and streamName streams. + The server assumes that the streams contain the same content and have the same keyframe interval but have different + resolutions or bit rates.

+ +

When a playlist has been queued up and oldStreamName is one of the streams in the playlist or is currently playing, + oldStreamName is replaced by streamName.

+ +

If oldStreamName is null or undefined, or if it is not found in the playlist, + the server switches to streamName at the next logical point, to ensure a smooth switch.

+ +

To switch from one stream to another with different content, use the SWAP mode instead.

+ + +
SWAPNetStreamPlayOptions.oldStreamNameNetStreamPlayOptions.streamName
NetConnection + The NetConnection class creates a two-way connection between a client and a server.flash.events:EventDispatcher + The NetConnection class creates a two-way connection between a client and a server. + The client can be a Flash Player or AIR application. + The server can be a web server, Flash Media Server, an application server running Flash Remoting, + or the Adobe Stratus service. Call NetConnection.connect() to + establish the connection. Use the NetStream class to send streams of media and data over the connection. + +

For security information about loading content and data into Flash Player and AIR, see the following:

+ +
  • To load content and data into Flash Player from a web server or from a local location, see + Flash Player Developer Center: Security.
  • To load content and data into Flash Player and AIR from Flash Media Server, see the + Flash Media Server documentation.
  • To load content and data into AIR, see the + Adobe AIR Developer Center.
+ +

+ To write callback methods for this class, extend the class and define the + callback methods in the subclass, or assign the client + property to an object and define the callback methods on that object.

+ +
The following example uses a Video object with the NetConnection and + NetStream classes to load and play an FLV file. +

In this example, the code that creates the Video and NetStream objects and calls the + Video.attachNetStream() and NetStream.play() methods is placed + in a handler function. The handler is called only if the + attempt to connect to the NetConnection object is successful; that is, + when the netStatus event returns an info object with a code + property that indicates success. + It is recommended that you wait for a successful connection before you call + NetStream.play().

+ +package { + import flash.display.Sprite; + import flash.events.NetStatusEvent; + import flash.events.SecurityErrorEvent; + import flash.media.Video; + import flash.net.NetConnection; + import flash.net.NetStream; + import flash.events.Event; + + public class NetConnectionExample extends Sprite { + private var videoURL:String = "http://www.helpexamples.com/flash/video/cuepoints.flv"; + private var connection:NetConnection; + private var stream:NetStream; + private var video:Video = new Video(); + + public function NetConnectionExample() { + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.connect(null); + } + + private function netStatusHandler(event:NetStatusEvent):void { + switch (event.info.code) { + case "NetConnection.Connect.Success": + connectStream(); + break; + case "NetStream.Play.StreamNotFound": + trace("Stream not found: " + videoURL); + break; + } + } + + private function securityErrorHandler(event:SecurityErrorEvent):void { + trace("securityErrorHandler: " + event); + } + + private function connectStream():void { + var stream:NetStream = new NetStream(connection); + stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + stream.client = new CustomClient(); + video.attachNetStream(stream); + stream.play(videoURL); + addChild(video); + } + } +} + +class CustomClient { + public function onMetaData(info:Object):void { + trace("metadata: duration=" + info.duration + " width=" + info.width + " height=" + info.height + " framerate=" + info.framerate); + } + public function onCuePoint(info:Object):void { + trace("cuepoint: time=" + info.time + " name=" + info.name + " type=" + info.type); + } +} +
clientNetStreamconnect()flash.net.RespondernetStatus + Dispatched when a NetConnection object is reporting its status or error condition.flash.events.NetStatusEvent.NET_STATUSflash.events.NetStatusEvent + Dispatched when a NetConnection object is reporting its status or error condition. + The netStatus event contains an info property, + which is an information object that contains specific information about the event, + such as whether a connection attempt succeeded or failed. + flash.events.NetStatusEvent.infosecurityError + Dispatched if a call to NetConnection.call() + attempts to connect to a server outside the caller's security sandbox.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched if a call to NetConnection.call() + attempts to connect to a server outside the caller's security sandbox. + NetConnection.call()ioError + Dispatched when an input or output error occurs that causes a network operation to fail.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an input or output error occurs that causes a network operation to fail. + asyncError + Dispatched when an exception is thrown asynchronously &#x2014; that is, + from native asynchronous code.flash.events.AsyncErrorEvent.ASYNC_ERRORflash.events.AsyncErrorEvent + Dispatched when an exception is thrown asynchronously — that is, + from native asynchronous code. + + NetConnection + Creates a NetConnection object. + Creates a NetConnection object. Call the connect() method to make a connection. + +

If an application needs to communicate with servers released prior + to Flash Player 9, set the NetConnection object's + objectEncoding property.

+ +

The following code creates a NetConnection object:

+ +
+     var nc:NetConnection = new NetConnection();
+     
+ + +
flash.net.NetConnection.connect()objectEncoding
addHeader + Adds a context header to the Action Message Format (AMF) packet structure.operationStringIdentifies the header and the ActionScript object data associated with it. + + mustUnderstandBooleanfalseA value of true indicates that the server must understand + and process this header before it handles any of the following headers or messages. + paramObjectnullAny ActionScript object. + + + Adds a context header to the Action Message Format (AMF) packet structure. This header is sent with + every future AMF packet. If you call NetConnection.addHeader() + using the same name, the new header replaces the existing header, and the new header + persists for the duration of the NetConnection object. You can remove a header by + calling NetConnection.addHeader() with the name of the header to remove + an undefined object. + + call + Calls a command or method on Flash Media Server or on an application server running Flash Remoting.commandStringA method specified in the form [objectPath/]method. For example, + the someObject/doSomething command tells the remote server + to call the clientObject.someObject.doSomething() method, with all the optional + ... arguments parameters. If the object path is missing, + clientObject.doSomething() is invoked on the remote server. +

+ With Flash Media Server, command is the name of a function + defined in an application's server-side script. + You do not need to use an object path before command + if the server-side script is placed at the root level of + the application directory. +

+ +
responderflash.net:ResponderAn optional object that is used to handle return values from the server. + The Responder object can have two defined methods to handle the returned result: + result and status. If an error is returned as the result, + status is invoked; otherwise, result is invoked. The Responder object + can process errors related to specific operations, while the NetConnection object responds to + errors related to the connection status. + + argumentsOptional arguments that can be of any ActionScript type, + including a reference to another ActionScript object. These arguments are passed + to the method specified in the command parameter when the method is executed on the + remote application server. + +
+ Calls a command or method on Flash Media Server or on an application server running Flash Remoting. + + Before calling NetConnection.call() you must call NetConnection.connect() + to connect to the server. You must create a server-side function to pass to this method. + +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +
flash.net.RespondersecurityErrorflash.events:SecurityErrorEventA call attempted + to communicate with a server outside the caller's security sandbox. + You can avoid this problem by using a policy file on the server. + A call attempted + to communicate with a server outside the caller's security sandbox.
close + Closes the connection that was opened locally or to the server and dispatches + a netStatus event + with a code property of NetConnection.Connect.Closed. + Closes the connection that was opened locally or to the server and dispatches + a netStatus event + with a code property of NetConnection.Connect.Closed. + +

+ This method disconnects all NetStream objects running over the connection. + Any queued data that has not been sent is discarded. (To terminate + local or server streams without closing the connection, use NetStream.close().) + If you close the connection and then want to create a new one, + you must create a new NetConnection object and call the connect() method again. +

+ +

The close() method also disconnects all remote shared objects running + over this connection. + However, you don't need to recreate the shared object to reconnect. Instead, you can just + call SharedObject.connect() to reestablish the connection to the shared object. + Also, any data in the shared object that was queued when you issued + NetConnection.close() is sent after you reestablish a connection + to the shared object.

+ +

+ With Flash Media Server, the best development practice is to call close() + when the client no longer needs the connection to the server. Calling close() + is the fastest way to clean up unused connections. You can configure the server to close idle connections + automatically as a back-up measure. For more information, see + the Flash Media Server Configuration and Administration Guide. +

+ +
NetStreamflash.events.NetStatusEvent.info
connect + Creates a two-way connection to an application on Flash Media Server or to Flash Remoting, or creates a two-way network + endpoint for RTMFP peer-to-peer group communication.The URI passed to the command parameter is + improperly formatted. + + ArgumentErrorArgumentErrorThe connection failed. This can happen if you call connect() + from within a netStatus event handler, which is not allowed. + + IOErrorflash.errors:IOErrorLocal-with-filesystem SWF files cannot communicate with the Internet. + You can avoid this problem by reclassifying the SWF file as local-with-networking or trusted. + + SecurityErrorSecurityErrorYou cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide. + + SecurityErrorSecurityErrorcommandStringUse one of the following values for the command parameter: +
  • To play video and mp3 files from a local file system or from a web server, pass null.
  • To connect to an application server running Flash Remoting, pass a URL that uses the http protocol.
  • (Flash Player 10.1 or AIR 2 or later) To create a serverless network endpoint for RTMFP IP multicast communication, + pass the string "rtmfp:". Use this connection type to receive an IP multicast stream from a publisher without using a server. + You can also use this connection type to use IP multicast to discover peers on the same local area network (LAN).
  • This connection type has the following limitations:

    Only peers on the same LAN can discover each other.

    Using IP multicast, Flash Player can receive streams, it cannot send them.

    Flash Player and AIR can send and receive streams in a peer-to-peer group, but the peers + must be discovered on the same LAN using IP multicast.

    This technique cannot be used for one-to-one communication.

  • To connect to Flash Media Server, pass the URI of the + application on the server. Use the following + syntax (items in brackets are optional): + +

    protocol:[//host][:port]/appname[/instanceName]

    + +

    Use one of the following protocols: rtmp, + rtmpe, rtmps, rtmpt, rtmpte, or rtmfp. + If the connection is successful, a + netStatus event with a code property of + NetConnection.Connect.Success is returned. + See the NetStatusEvent.info property for a list of + all event codes returned in response to calling connect().

    + +

    If the file is served from the same host where the server is installed, + you can omit the //host parameter. If you omit the /instanceName parameter, + Flash Player or AIR connects to the application's default instance.

    + +

    (Flash Player 10.1 or AIR 2 or later)To create peer-to-peer applications, use the rtmfp protocol.

    + +
+ +
argumentsOptional parameters of any type passed to the application + specified in command. + With Flash Media Server, the additional arguments are passed to the + application.onConnect() event handler in the application's server-side + code. You must define and handle the arguments in onConnect(). + +
+ Creates a two-way connection to an application on Flash Media Server or to Flash Remoting, or creates a two-way network + endpoint for RTMFP peer-to-peer group communication. To report its status or an error condition, a + call to NetConnection.connect() dispatches a netStatus event. + +

Call NetConnection.connect() to do the following:

+ +
  • Pass "null" to play video and mp3 files from a local file system or from a web server.
  • Pass an "http" URL to connect to an application server running Flash Remoting. Use the NetServices class to call functions on and + return results from application servers over a NetConnection object. + For more information, see the Flash Remoting documentation.
  • Pass an "rtmp/e/s" URL to connect to a Flash Media Server application.
  • Pass an "rtmfp" URL to create a two-way network endpoint for RTMFP client-server, peer-to-peer, and IP multicast communication.
  • Pass the string "rtmfp:" to create a serverless two-way network endpoint for RTMFP IP multicast communication.
+ +

Consider the following security model:

+ +
  • By default, Flash Player or AIR denies access between sandboxes. + A website can enable access to a resource by using a URL policy file.
  • Your application can deny access to a resource on the server. + In a Flash Media Server application, use Server-Side ActionScript code to deny access. + See the Flash Media Server documentation.
  • You cannot call NetConnection.connect() if the calling file is in the + local-with-file-system sandbox.
  • You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.
  • To prevent a SWF file from calling this method, set the allowNetworking + parameter of the the object and embed tags in the HTML + page that contains the SWF content.
+ +

However, in Adobe AIR, content in the application security sandbox (content + installed with the AIR application) are not restricted by these security limitations.

+ +

For more information about security, see the Adobe Flash Player Developer Center: + Security.

+ +
flash.net.NetStreamflash.events.NetStatusEvent.info
client + Indicates the object on which callback methods are invoked.ObjectThe client property must be set to a non-null object. + + TypeErrorTypeError + Indicates the object on which callback methods are invoked. The default is + this NetConnection instance. If you set the client property to another object, + callback methods will be invoked on that object. + + connectedProxyType + The proxy type used to make a successful connection to Flash Media Server.StringAn attempt was made to access this property when the NetConnection instance + was not connected. + + ArgumentErrorArgumentError + The proxy type used to make a successful connection to Flash Media Server. Possible values are: + "none", "HTTP", "HTTPS", or "CONNECT". + +

The value is "none" if the connection is not tunneled or is a native SSL connection.

+ +

The value is "HTTP" if the connection is tunneled over HTTP.

+ +

The value is "HTTPS" if the connection is tunneled over HTTPS,

+ +

The value is "CONNECT" if the connection is tunneled using the CONNECT method through a proxy server.

+ +
connected + Indicates whether the application is connected to a server through + a persistent RTMP connection (true) or not (false).Boolean + Indicates whether the application is connected to a server through + a persistent RTMP connection (true) or not (false). + When connected through HTTP, this property is false, except + when connected to Flash Remoting services on an application server, + in which case it is true. + + defaultObjectEncoding + The default object encoding for NetConnection objects.uint + The default object encoding for NetConnection objects. + When an object is written to or read from binary data, the defaultObjectEncoding + property indicates which Action Message Format (AMF) version is used to serialize the data: + the ActionScript 3.0 format (ObjectEncoding.AMF3) + or the ActionScript 1.0 and ActionScript 2.0 format (ObjectEncoding.AMF0). + +

The default value is ObjectEncoding.AMF3. + Changing NetConnection.defaultObjectEncoding + does not affect existing NetConnection instances; it affects only instances that + are created subsequently.

+ +

To set an object's encoding separately (rather than setting object encoding for the entire + application), set the objectEncoding property of the NetConnection object instead.

+ +

For more detailed information, see the description of the objectEncoding + property.

+ +
NetConnection.objectEncodingflash.net.ObjectEncoding
farID + The identifier of the Flash Media Server instance to which this Flash Player or Adobe AIR instance is connected.String + The identifier of the Flash Media Server instance to which this Flash Player or Adobe AIR instance is connected. + This property is meaningful only for RTMFP connections. The value of this property is available only after an RTMFP connection is established. + + nearIDfarNonce + A value chosen substantially by Flash Media Server, unique to this connection.String + A value chosen substantially by Flash Media Server, unique to this connection. This value appears to the server + as its client.nearNonce value. This value is defined only for RTMFP, RTMPE, and RTMPTE connections. + + httpIdleTimeout + The time, in milliseconds, to wait for an HTTP response.NumberThe time in milliseconds to wait for an HTTP response. + + The time, in milliseconds, to wait for an HTTP response. The default value is zero. + +
  • The httpIdleTimeout value is a Number.
  • When using an HTTP connection, a positive value indicates the number of milliseconds an inactive connection should remain + open.
  • A value of zero indicates that the default networking idle timeout value for the platform should be used.
  • A negative value will result in a RangeError.
  • If the httpIdleTimeout value is exceeded, a netStatus event is dispatched.
  • This property will only affect NetConnection objects created with HTTP connections. + NetConnection objects created with RTMP, RTMFP, or other HTTP channels remain unaffected by this property.
+ + //Set the timeout to 5 seconds + connection = new NetConnection(); + connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); + connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); + connection.httpIdleTimeout = 5000; + + + In Linux-based systems, the NetConnection may take more seconds to timeout than what is specified using the + httpIdleTimeout value. + +
maxPeerConnections + The total number of inbound and outbound peer connections that this instance of Flash Player or Adobe AIR allows.uint + The total number of inbound and outbound peer connections that this instance of Flash Player or Adobe AIR allows. + The default value is 8. +

This value does not distinguish between publisher and subscriber connections. If this value is reduced while + peer connections are present, the new value affects new incoming connections only. Existing connections are not dropped.

+ + +
nearID + The identifier of this Flash Player or Adobe AIR instance for this NetConnection instance.String + The identifier of this Flash Player or Adobe AIR instance for this NetConnection instance. This property is meaningful only for RTMFP connections. + +

Every NetConnection instance has a unique nearID property. No Flash Player or Adobe AIR instance + or NetConnection instance has the same identifier.

+ +

Other Flash Player or Adobe AIR instances + use this identifier as the peerID for new NetStream connections to this client. + Subsequently, this identifier is the farID in any peer NetStream that connects to this instance.

+ +
farID
nearNonce + A value chosen substantially by this Flash Player or Adobe AIR instance, unique to this connection.String + A value chosen substantially by this Flash Player or Adobe AIR instance, unique to this connection. This value appears to the server + as its client.farNonce value. This value is defined only for RTMFP, RTMPE, and RTMPTE connections. + + objectEncoding + The object encoding for this NetConnection instance.uintAn attempt was made to set the value of the objectEncoding + property while the NetConnection instance was connected. + + ReferenceErrorReferenceErrorThis property was set to a value other than ObjectEncoding.AMF0 + or ObjectEncoding.AMF3. + + ArgumentErrorArgumentError + The object encoding for this NetConnection instance. + +

+ When an object is written to or read from binary data, the defaultObjectEncoding + property indicates which Action Message Format (AMF) version is used to serialize the data: the ActionScript 3.0 format (ObjectEncoding.AMF3) + or the ActionScript 1.0 and ActionScript 2.0 format (ObjectEncoding.AMF0). + Set the objectEncoding property to set an AMF version for a NetConnection instance. +

+ +

It's important to understand this property if your application needs to + communicate with servers released prior to Flash Player 9. The following three scenarios are possible: +

+ +
  • Connecting to a server that supports AMF3 (for example, Flex Data Services 2 or Flash Media Server 3). + The default value of defaultObjectEncoding is + ObjectEncoding.AMF3. All NetConnection instances created in this + file use AMF3 serialization, so you don't need to set the + objectEncoding property.
  • Connecting to a server that doesn't support AMF3 (for example, Flash Media Server 2). + In this scenario, set the static NetConnection.defaultObjectEncoding property to + ObjectEncoding.AMF0. All NetConnection instances created in this + SWF file use AMF0 serialization. You don't need to set the + objectEncoding property.
  • Connecting to multiple servers that use different encoding versions. Instead of + using defaultObjectEncoding, set the object encoding on a per-connection + basis using the objectEncoding property for each connection. + Set it to ObjectEncoding.AMF0 to connect to + servers that use AMF0 encoding, such as Flash Media Server 2, + and set it to ObjectEncoding.AMF3 to connect to + servers that use AMF3 encoding, such as Flex Data Services 2.
+ +

Once a NetConnection instance is connected, its objectEncoding + property is read-only.

+ +

If you use the wrong encoding to connect to a server, the NetConnection object + dispatches the netStatus event. The NetStatusEvent.info + property contains an information object with a code property value of + NetConnection.Connect.Failed, and a description explaining that the object + encoding is incorrect.

+ +
defaultObjectEncodingflash.net.ObjectEncoding
protocol + The protocol used to establish the connection.StringAn attempt was made to access this property when the NetConnection instance + was not connected. + + ArgumentErrorArgumentError + The protocol used to establish the connection. This property is relevant when using + Flash Media Server. Possible values are as follows: +
  • "rtmp": Real-Time Messaging Protocol (RTMP)
  • "rtmpe": Encrypted RTMP
  • "rtmpt": HTTP tunneling RTMP
  • "rtmpte": HTTP tunneling encrypted RTMP
  • "rtmps": HTTPS-based RTMP
  • "rtmfp": Real-Time Media Flow Protocol (RTMFP)
+ +
proxyType + Determines which fallback methods are tried if an + initial connection attempt to Flash Media Server fails.String + Determines which fallback methods are tried if an + initial connection attempt to Flash Media Server fails. Set the proxyType property before + calling the NetConnection.connect() method. + +

Acceptable values are "none", "HTTP", "CONNECT", + and "best".The default value is "none".

+ +

To use native SSL, set the property to "best". If the player cannot make a direct connection + to the server (over the default port of 443 or over another port that you specify) + and a proxy server is in place, the player tries to use the CONNECT method. If that attempt fails, the player tunnels over HTTPS. +

+ +

If the property is set to "HTTP" and a direct connection fails, HTTP tunneling is used. + If the property is set to "CONNECT" and a direct connection fails, + the CONNECT method of tunneling is used. If that fails, the connection does + not fall back to HTTP tunneling.

+ +

This property is applicable only when using RTMP, RTMPS, or RTMPT. The CONNECT + method is applicable only to users who are connected to the network by a proxy server.

+ +
unconnectedPeerStreams + + An object that holds all of the peer subscriber NetStream objects that are not associated with publishing NetStream objects.Array + + An object that holds all of the peer subscriber NetStream objects that are not associated with publishing NetStream objects. + Subscriber NetStream objects that are associated with publishing NetStream objects are in the NetStream.peerStreams + array. + NetStream.peerStreamsuri + The URI passed to the NetConnection.connect() method.String + The URI passed to the NetConnection.connect() method. + If NetConnection.connect() hasn't been called or if no URI was passed, + this property is undefined. + + usingTLS + Indicates whether a secure connection was made using native Transport Layer Security (TLS) + rather than HTTPS.BooleanAn attempt was made to access this property when the NetConnection instance + was not connected. + + ArgumentErrorArgumentError + Indicates whether a secure connection was made using native Transport Layer Security (TLS) + rather than HTTPS. This property is valid only when a NetConnection object is connected. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.printing.xml b/language-server/playerglobal_docs/flash.printing.xml new file mode 100644 index 0000000..05b3b80 --- /dev/null +++ b/language-server/playerglobal_docs/flash.printing.xml @@ -0,0 +1,1258 @@ +flash.printingPrintUIOptions + + The PrintUIOptions class is used to specify options for print dialogs that are displayed to the + user.Object + The PrintUIOptions class is used to specify options for print dialogs that are displayed to the + user. Create a PrintUIOptions instance, set its properties, and pass it as the + uiOptions parameter of the PrintJob.showPageSetupDialog() + or PrintJob.start2() method. + +

For example, the following code uses a PrintUIOptions instance to specify the + min and max page numbers when the Page Setup dialog is displayed:

+ + import flash.printing.PrintJob; + + var myPrintJob:PrintJob = new PrintJob(); + if (myPrintJob.supportsPageSetupDialog) + { + var uiOpt:PrintUIOptions = new PrintUIOptions(); + uiOpt.minPage = 1; + uiOpt.maxPage = 3; + myPrintJob.showPageSetupDialog(uiOpt); + } + +
PrintJobPrintJob.showPageSetupDialog()PrintJob.start2()PrintUIOptions + Creates a new PrintUIOptions object. + Creates a new PrintUIOptions object. You pass this object to the + uiOptions parameter of the PrintJob.showPageSetupDialog() + or PrintJob.start2() method. + + PrintJob.showPageSetupDialog()PrintJob.start2()disablePageRange + Specifies whether the page range in the print dialog is disabled (true) or + the user can edit it (false).falseBooleanfalse + + + Specifies whether the page range in the print dialog is disabled (true) or + the user can edit it (false). The default value is false, + indicating that there is no restriction on editing the page range. + + maxPage + The maxiumum page number the user can enter + in the print dialog.0uint0 + + + The maxiumum page number the user can enter + in the print dialog. The default value is 0, indicating that there is + no restriction on the maximum page number. + + minPage + The minimum page number a user can enter + in the print dialog.0uint0 + + + The minimum page number a user can enter + in the print dialog. The default value is 0, indicating that there is + no restriction on the minimum page number. + +
PrintMethod +This class provides values for the PrintJobOptions.printMethod property +to specify the method of printing a page.Object +This class provides values for the PrintJobOptions.printMethod property +to specify the method of printing a page. +PrintJobOptions.printMethodAUTO + Automatic selection of the best method of printing.autoString + Automatic selection of the best method of printing. This value indicates + that vector or bitmap printing is chosen automatically, based on + the content to print. Vector printing is used whenever the content + can be faithfully reproduced by that method. If transparency or certain + other effects are present, bitmap printing is used instead. + +

This constant is used with the PrintJobOptions.printMethod property. + Use the syntax PrintMethod.AUTO.

+ +
PrintJobOptions.printMethodVECTORBITMAP
BITMAP + The bitmap method of printing.bitmapString + The bitmap method of printing. + +

This constant is used with the PrintJobOptions.printMethod property. + Use the syntax PrintMethod.BITMAP.

+ +
PrintJobOptions.printMethodVECTORAUTO
VECTOR + The vector method of printing.vectorString + The vector method of printing. + +

This constant is used with the PrintJobOptions.printMethod property. + Use the syntax PrintMethod.VECTOR.

+ +
PrintJobOptions.printMethodBITMAPAUTO
PrintJobOptions + The PrintJobOptions class contains properties to use with the + options parameter of the PrintJob.addPage() method.Object + The PrintJobOptions class contains properties to use with the + options parameter of the PrintJob.addPage() method. + For more information about addPage(), see the PrintJob class. + PrintJobPrintJob.addPage()PrintJobOptions + Creates a new PrintJobOptions object.printAsBitmapBooleanfalseIf true, this object is printed as a bitmap. + If false, this object is printed as a vector. + +

If the content that you're printing includes a bitmap image, + set the printAsBitmap property to true to include any + alpha transparency and color effects. + If the content does not include bitmap images, omit this parameter to print + the content in higher quality vector format (the default option).

+ +

Note:Adobe AIR does not support vector printing on Mac OS.

+ +
+ Creates a new PrintJobOptions object. Pass this object + to the options parameter of the PrintJob.addPage() method. + +
PrintJob.addPage()
pixelsPerInch + Specifies the resolution to use for bitmaps, in pixels per inch.NaNNumber + Specifies the resolution to use for bitmaps, in pixels per inch. + The default value is Number.NaN, indicating that the native + printer resolution is used. + +

The resolution setting is for both bitmap and vector printing. For bitmap printing, + resolution controls how the entire page is rasterized. For vector printing, resolution + controls how specific content, such as bitmaps and gradients, is rasterized.

+ +
printAsBitmap + Specifies whether the content in the print job is printed as a bitmap or as a vector.falseBoolean + Specifies whether the content in the print job is printed as a bitmap or as a vector. + The default value is false, for vector printing. + +

If the content that you're printing includes a bitmap image, + set printAsBitmap to true to include any + alpha transparency and color effects. + If the content does not include bitmap images, print + the content in higher quality vector format (the default option).

+

For example, to print your content as a bitmap, use the following syntax:

+ + var options:PrintJobOptions = new PrintJobOptions(); + options.printAsBitmap = true; + myPrintJob.addPage(mySprite, null, options); + + +

Note:Adobe AIR does not support vector printing on Mac OS.

+ +
The following example first loads a picture and puts it in a rectangle frame, then print the picture as a bitmap. + +
  1. The constructor loads the picture (image.jpg) using the Loader and URLRequest objects. + It also checks if an error occurred during loading. Here the file is assumed to be in the same directory as the SWF file. + The SWF file needs to be compiled with Local Playback Secuirty set to Access Local Files Only.
  2. When the picture is loaded (the event is complete), the completeHandler() method is called.
  3. The completeHandler() method, creates a BitmapData object, and loads the picture (bitmap) in it. + A rectangle is drawn in the Sprite object (frame) and the beginBitmapFill() method is used + to fill the rectangle with the picture (a BitmapData object). A Matrix object also is used to scale the + image to fit the rectangle. (Note that this will distort the image. It is used in this example to make sure the image fits.) + Once the image is filled, the printPage() method is called.
  4. The printPage() method creates a new instance of the print job and starts the printing process, which invokes the + print dialog box for the user, and populates the properties of the print job. The addPage() method contains the + details about the print job. Here, the frame with the picture (a Sprite object) is set to print as a bitmap and not + as a vector. options is an instance of PrintJobOptions class and its property printAsBitmap + is set to true in order to print as a bitmap (default setting is false).
+

Note: There is very limited error handling defined for this example.

+ + +package { + import flash.display.Sprite; + import flash.display.Loader; + import flash.display.Bitmap; + import flash.display.BitmapData; + import flash.printing.PrintJob; + import flash.printing.PrintJobOptions; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.net.URLRequest; + import flash.geom.Matrix; + + public class printAsBitmapExample extends Sprite { + + private var frame:Sprite = new Sprite(); + private var url:String = "image.jpg"; + private var loader:Loader = new Loader(); + + public function printAsBitmapExample() { + + var request:URLRequest = new URLRequest(url); + + loader.load(request); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); + } + + private function completeHandler(event:Event):void { + + var picture:Bitmap = Bitmap(loader.content); + var bitmap:BitmapData = picture.bitmapData; + + var matrix:Matrix = new Matrix(); + + matrix.scale((200 / bitmap.width), (200 / bitmap.height)); + + frame.graphics.lineStyle(10); + frame.graphics.beginBitmapFill(bitmap, matrix, true); + frame.graphics.drawRect(0, 0, 200, 200); + frame.graphics.endFill(); + + addChild(frame); + + printPage(); + } + + private function ioErrorHandler(event:IOErrorEvent):void { + trace("Unable to load the image: " + url); + } + + private function printPage ():void { + var myPrintJob:PrintJob = new PrintJob(); + var options:PrintJobOptions = new PrintJobOptions(); + options.printAsBitmap = true; + + myPrintJob.start(); + + try { + myPrintJob.addPage(frame, null, options); + } + catch(e:Error) { + trace ("Had problem adding the page to print job: " + e); + } + + try { + myPrintJob.send(); + } + catch (e:Error) { + trace ("Had problem printing: " + e); + } + } + } +} + +
PrintJobOptions.printMethod
printMethod + Specifies that the Flash runtime chooses the most appropriate + printing method, or that the author wishes to explicitly select + vector or bitmap printing.StringThe printMethod specified is not one of the + values defined in the PrintMethod class. + + ArgumentErrorArgumentError + Specifies that the Flash runtime chooses the most appropriate + printing method, or that the author wishes to explicitly select + vector or bitmap printing. + +

Set the property to one of the following values defined in the + PrintMethod class:

+
  • PrintMethod.AUTO: Specifies that vector or bitmap printing + is chosen automatically, based on the content to be printed. Vector + printing will be used whenever the content can be faithfully reproduced by + that method. If transparency or certain other effects are present, bitmap + printing will be used instead.
  • PrintMethod.VECTOR: Speifies vector printing. + This setting is the same as setting printAsBitmap to false.
  • PrintMethod.BITMAP: Specifies bitmap printing. + Same as setting printAsBitmap to true.
+ +

If printMethod is set to one of these supported values, then printAsBitmap + is ignored.

+ +

The default value is null; the printAsBitmap property is + used.

+ +
PrintJobOptions.printAsBitmapPrintMethod class
PrintJob + The PrintJob class lets you create content and print it to one or + more pages.flash.events:EventDispatcher + The PrintJob class lets you create content and print it to one or + more pages. This class + lets you render content that is visible, dynamic or offscreen to the user, prompt users with a + single Print dialog box, and print an unscaled document with + proportions that map to the proportions of the content. This + capability is especially useful for rendering and printing dynamic + content, such as database content and dynamic text. + +

Mobile Browser Support: This class is not supported in mobile browsers.

+ +

AIR profile support: This feature is supported + on all desktop operating systems, but it is not supported on mobile devices or AIR for TV devices. You can test + for support at run time using the PrintJob.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

Use the PrintJob() constructor to create a print job.

+ +

Additionally, with the PrintJob class's properties, you can read your user's + printer settings, such as page height, width, and image orientation, and + you can configure your document to dynamically format Flash content + that is appropriate for the printer settings.

+ +

Note: ActionScript 3.0 does not restrict a PrintJob object + to a single frame (as did previous versions of ActionScript). However, since + the operating system displays print status information to the user after the + user has clicked the OK button in the Print dialog box, you should call + PrintJob.addPage() and PrintJob.send() as soon as + possible to send pages to the spooler. A delay reaching the frame containing + the PrintJob.send() call delays the printing process.

+

Additionally, a 15 second script timeout limit applies to the following intervals:

+
  • PrintJob.start() and the first PrintJob.addPage()
  • PrintJob.addPage() and the next PrintJob.addPage()
  • The last PrintJob.addPage() and PrintJob.send()
+ +

If any of the above intervals span more than 15 seconds, the next call to + PrintJob.start() on the PrintJob instance returns false, + and the next PrintJob.addPage() on the PrintJob instance causes + the Flash Player or Adobe AIR to throw a runtime exception.

+ +
The following example show the basics of printing. A new PrintJob is created, + and if started successfully, the addPage() method adds the sprite as a single page. + The send() method spools the page to the printer. + + +package +{ + import flash.printing.PrintJob; + import flash.display.Sprite; + + public class BasicPrintExample extends Sprite + { + var myPrintJob:PrintJob = new PrintJob(); + var mySprite:Sprite = new Sprite(); + mySprite.graphics.beginFill(0x336699); + mySprite.graphics.drawCircle(100, 100, 50); + + public function BasicPrintExample() + { + if (myPrintJob.start()) { + try { + myPrintJob.addPage(mySprite); + } + catch(e:Error) { + // handle error + } + myPrintJob.send(); + } + } +} + The following example uses the class PrintJobExample to create a small document and + then send the document to the printer. This is accomplished using the following steps: +
  1. Declare two variables of type Sprite named sheet1 and sheet2.
  2. Call init(), which assigns a new Sprite instance to both sheet1 and + sheet2 and then calls createSheet() using different arguments.
  3. createSheet() does the following: +
    1. The Sprite object passed in is used to draw a rectangle with a light-gray background, a + one-pixel black border, and that is 100 pixels wide by 200 pixels high at x = 0, y = 0.
    2. A new TextField object is created named txt with the same dimensions as + the Sprite, the wordWrap property set to true, and the text property set to + the String passed as an argument to createSheet().
    3. If the Object argument passed is not null, create a new Sprite instance named + img that is used to draw a white rectangle using the coordinate and dimension properties + of the Object passed. The white rectangle is added to the display list of the Sprite object using + addChild().
    4. The txt TextField is added to the display list of the Sprite object using + addChild().
  4. Back in the constructor, the print method that is enabled (not commented out) is called. Since the + methods are very similar, printOnePerPage() is described below.
  5. printOnePerPage() does the following: +
    1. Declare a new PrintJob object named pj and pagesToPrint as a uint.
    2. Open the operating system's native print dialog box and wait for user to click OK.
    3. Check the orientation and if Landscape is selected, throw an error and exit.
    4. Set up the page height and width for sheet1 and sheet2.
    5. Send sheet1 and sheet2 to the print spooler using addPage().
    6. If the number of pages to print is > 0, print all spooled pages.
  6. The draw() method is called, which re-sizes the two Sprite properties to fit on the stage + and re-positions sheet2 such that it is just right of sheet1.
+ +

Note: the constructor is set up such that one of three printing methods (one sheet per + page, two sheets per page, or printing on the top half of the page) can be selected, based on preference. + This example will not work correctly unless exactly two of the print methods are disabled using code + comments. The example is set up such that printOnePerPage() will be called.

+ +package { + import flash.printing.PrintJob; + import flash.printing.PrintJobOrientation; + import flash.display.Stage; + import flash.display.Sprite; + import flash.text.TextField; + import flash.geom.Rectangle; + + public class PrintJobExample extends Sprite { + private var sheet1:Sprite; + private var sheet2:Sprite; + + public function PrintJobExample() { + init(); + printOnePerPage(); +// printTwoPerPage(); +// printTopHalf(); + draw(); + } + + private function init():void { + sheet1 = new Sprite(); + createSheet(sheet1, "Once upon a time...", {x:10, y:50, width:80, height:130}); + + sheet2 = new Sprite(); + createSheet(sheet2, "There was a great story to tell, and it ended quickly.\n\nThe end.", null); + } + + private function createSheet(sheet:Sprite, str:String, imgValue:Object):void { + sheet.graphics.beginFill(0xEEEEEE); + sheet.graphics.lineStyle(1, 0x000000); + sheet.graphics.drawRect(0, 0, 100, 200); + sheet.graphics.endFill(); + + var txt:TextField = new TextField(); + txt.height = 200; + txt.width = 100; + txt.wordWrap = true; + txt.text = str; + + if(imgValue != null) { + var img:Sprite = new Sprite(); + img.graphics.beginFill(0xFFFFFF); + img.graphics.drawRect(imgValue.x, imgValue.y, imgValue.width, imgValue.height); + img.graphics.endFill(); + sheet.addChild(img); + } + sheet.addChild(txt); + } + + private function printOnePerPage():void { + var pj:PrintJob = new PrintJob(); + var pagesToPrint:uint = 0; + if(pj.start()) { + if(pj.orientation == PrintJobOrientation.LANDSCAPE) { + throw new Error("Without embedding fonts you must print one sheet per page with an orientation of portrait."); + } + + sheet1.height = pj.pageHeight; + sheet1.width = pj.pageWidth; + sheet2.height = pj.pageHeight; + sheet2.width = pj.pageWidth; + + try { + pj.addPage(sheet1); + pagesToPrint++; + } + catch(e:Error) { + // do nothing + } + + try { + pj.addPage(sheet2); + pagesToPrint++; + } + catch(e:Error) { + // do nothing + } + + if(pagesToPrint > 0) { + pj.send(); + } + } + } + + private function printTwoPerPage():void { + var pj:PrintJob = new PrintJob(); + var pagesToPrint:uint = 0; + if(pj.start()) { + if(pj.orientation == PrintJobOrientation.PORTRAIT) { + throw new Error("Without embedding fonts you must print two sheets per page with an orientation of landscape."); + } + + sheet1.height = pj.pageHeight; + sheet1.width = pj.pageWidth/2; + sheet2.height = pj.pageHeight; + sheet2.width = pj.pageWidth/2; + + var sheets:Sprite = new Sprite(); + sheets.addChild(sheet1); + sheets.addChild(sheet2); + sheets.getChildAt(1).x = sheets.getChildAt(0).width; + try { + pj.addPage(sheets); + pagesToPrint++; + } + catch(e:Error) { + // do nothing + } + + if(pagesToPrint > 0) { + pj.send(); + } + } + } + + private function printTopHalf():void { + var pj:PrintJob = new PrintJob(); + var pagesToPrint:uint = 0; + if(pj.start()) { + if(pj.orientation == PrintJobOrientation.PORTRAIT) { + throw new Error("Without embedding fonts you must print the top half with an orientation of landscape."); + } + + sheet1.height = pj.pageHeight; + sheet1.width = pj.pageWidth/2; + sheet2.height = pj.pageHeight; + sheet2.width = pj.pageWidth/2; + + var sheets:Sprite = new Sprite(); + sheets.addChild(sheet1); + sheets.addChild(sheet2); + sheets.getChildAt(1).x = sheets.getChildAt(0).width; + try { + pj.addPage(sheets, new Rectangle(0, 0, sheets.width, sheets.height/2)); + pagesToPrint++; + } + catch(e:Error) { + // do nothing + } + + if(pagesToPrint > 0) { + pj.send(); + } + } + } + + + private function draw():void { + var sheetWidth:Number = this.stage.stageWidth/2; + var sheetHeight:Number = this.stage.stageHeight; + + addChild(sheet1); + sheet1.width = sheetWidth; + sheet1.height = sheetHeight; + + addChild(sheet2); + sheet2.width = sheetWidth; + sheet2.height = sheetHeight; + sheet2.x = sheet1.width; + } + } +} +
The following example demonstrates additional printing features. + The example initializes the PrintJob settings for number of copies, + paper size (legal), and page orientation (landscape). It forces the + Page Setup dialog to be displayed first, then starts the print job + by displaying the Print dialog. + +package + { + import flash.display.Sprite; + import flash.display.Stage; + import flash.geom.Rectangle; + import flash.printing.PaperSize; + import flash.printing.PrintJob; + import flash.printing.PrintJobOrientation; + import flash.printing.PrintUIOptions; + import flash.text.TextField; + + public class PrintJobExample extends Sprite + { + private var bg:Sprite; + private var txt:TextField; + private var pj:PrintJob; + private var uiOpt:PrintUIOptions; + + public function PrintJobExample():void + { + var pj = new PrintJob(); + uiOpt = new PrintUIOptions(); + initPrintJob(); + initContent(); + draw(); + printPage(); + } + + private function printPage():void + { + if (pj.supportsPageSetupDialog) + { + pj.showPageSetupDialog(); + } + + if (pj.start2(uiOpt, true)) + { + try + { + pj.addPage(this, new Rectangle(0, 0, 100, 100)); + } + catch (error:Error) + { + // Do nothing. + } + pj.send(); + } + else + { + txt.text = "Print job terminated"; + pj.terminate(); + } + } + + private function initContent():void + { + bg = new Sprite(); + bg.graphics.beginFill(0x00FF00); + bg.graphics.drawRect(0, 0, 100, 200); + bg.graphics.endFill(); + + txt = new TextField(); + txt.border = true; + txt.text = "Hello World"; + } + + private function initPrintJob():void + { + pj.setPaperSize(PaperSize.LEGAL); + pj.orientation = PrintJobOrientation.LANDSCAPE; + pj.copies = 2; + pj.jobName = "Flash test print"; + } + + private function draw():void + { + addChild(bg); + addChild(txt); + txt.x = 50; + txt.y = 50; + } + } +} +
PrintJob + Creates a PrintJob object that you can use to print one or more pages. In Flash Player and AIR prior to AIR 2, throws an exception if another PrintJob object is still active. + + IllegalOperationErrorflash.errors:IllegalOperationError + Creates a PrintJob object that you can use to print one or more pages. + After you create a PrintJob object, you need to use (in the following sequence) the + PrintJob.start(), PrintJob.addPage(), and then + PrintJob.send() methods to send the print job to the printer. + +

For example, you can replace the [params] placeholder text for the + myPrintJob.addPage() method calls with custom parameters as shown in the + following code:

+ +
+ // create PrintJob object
+ var myPrintJob:PrintJob = new PrintJob();
+  
+ // display Print dialog box, but only initiate the print job
+ // if start returns successfully.
+ if (myPrintJob.start()) {
+  
+    // add specified page to print job
+    // repeat once for each page to be printed
+    try {
+      myPrintJob.addPage([params]);
+    }
+    catch(e:Error) {
+      // handle error 
+    }
+    try {
+      myPrintJob.addPage([params]);
+    }
+    catch(e:Error) {
+      // handle error 
+    }
+ 
+    // send pages from the spooler to the printer, but only if one or more
+    // calls to addPage() was successful. You should always check for successful 
+    // calls to start() and addPage() before calling send().
+    myPrintJob.send();
+ }
+ 
+ +

In AIR 2 or later, you can create and use multiple PrintJob instances. Properties set on + the PrintJob instance are retained after printing completes. This allows you to re-use a PrintJob + instance and maintain a user's selected printing preferences, while offering different printing + preferences for other content in your application. For content in Flash Player and in AIR prior to version 2, you cannot create a + second PrintJob object while the first one is still active. + If you create a second PrintJob object (by calling new PrintJob()) + while the first PrintJob object is still active, the second PrintJob object + will not be created. So, you may check for the myPrintJob value before + creating a second PrintJob.

+ +
PrintJob.addPage()PrintJob.send()PrintJob.start()
addPage + Sends the specified Sprite object as a single page to the print spooler.Throws an exception if you haven't called start() or the + user cancels the print job + + + ErrorErrorspriteflash.display:SpriteThe Sprite containing the content to print. + + printAreaflash.geom:Rectanglenull A Rectangle object that specifies the area to print. + +

A rectangle's width and height are pixel values. A printer uses points as print units + of measurement. Points are a fixed physical size (1/72 inch), but the size of a pixel, + onscreen, depends on the resolution of the particular screen. So, the conversion rate + between pixels and points depends on the printer settings and whether the sprite is + scaled. An unscaled sprite that is 72 pixels wide prints out one inch wide, with + one point equal to one pixel, independent of screen resolution.

+ +

You can use the following equivalencies to convert inches + or centimeters to twips or points (a twip is 1/20 of a point):

+ +
  • 1 point = 1/72 inch = 20 twips
  • 1 inch = 72 points = 1440 twips
  • 1 cm = 567 twips
+ +

If you omit the printArea parameter, or if it is passed incorrectly, + the full area of the sprite parameter is printed.

+ +

If you don't want to specify a value for printArea but want to specify a value for options + or frameNum, pass null for printArea.

+ +
optionsflash.printing:PrintJobOptionsnullAn optional parameter that specifies whether to print as vector or bitmap. + The default value is null, which represents a request for vector printing. + To print sprite as a + bitmap, set the printAsBitmap property of the PrintJobOptions object + to true. Remember the following suggestions when determining whether to + set printAsBitmap to true: + +
  • If the content you're printing includes a bitmap image, set + printAsBitmap to true to include any alpha transparency + and color effects.
  • If the content does not include bitmap images, omit this parameter + to print the content in higher quality vector format.
+ +

If options is omitted or is passed incorrectly, vector printing is used. + If you don't want to specify a value for + options but want to specify a value for frameNumber, + pass null for options.

+ +
frameNumint0An optional number that lets you specify which frame + of a MovieClip object to print. Passing a frameNum does not invoke + ActionScript on that frame. If you omit this parameter and the + sprite parameter is a MovieClip object, the current + frame in sprite is printed. + +
+ Sends the specified Sprite object as a single page to the print spooler. Before using this + method, you must create a PrintJob object and then use start() or + start2(). Then, + after calling addPage() one or more times for a print job, use + send() to send the spooled pages to the printer. In other words, after you create + a PrintJob object, use (in the following sequence) start() or + start2(), addPage(), and then send() to send + the print job to the printer. You can call addPage() multiple times after a + single call to start() to print several pages in a print job. + +

If addPage() causes Flash Player to throw an exception (for example, + if you haven't called start() or the user cancels the print job), any + subsequent calls to addPage() fail. However, if previous calls to + addPage() are successful, the concluding send() command sends + the successfully spooled pages to the printer.

+ +

If the print job takes more than 15 seconds to complete an addPage() + operation, Flash Player throws an exception on the next addPage() call.

+ +

If you pass a value for the printArea parameter, the + x and y coordinates of the + printArea Rectangle map to the upper-left corner (0, 0 coordinates) of the + printable area on the page. The read-only properties + pageHeight and pageWidth describe the printable area set by + start(). Because the printout aligns with the upper-left corner + of the printable area on the page, when the area defined in printArea + is bigger than the printable area on the page, the printout is cropped to the right + or bottom (or both) of the area defined by printArea. + In Flash Professional, if you don't pass a value for printArea and the + Stage is larger than the printable area, the same type of clipping + occurs. In Flex or Flash Builder, if you don't pass a value for + printArea and the screen is larger than the printable area, the + same type of clipping takes place.

+ +

If you want to scale a Sprite object before you print it, set scale + properties (see flash.display.DisplayObject.scaleX and + flash.display.DisplayObject.scaleY) before calling this method, + and set them back to their original values after printing. The scale of a Sprite + object has no relation to printArea. That is, if you specify a print + area that is 50 x 50 pixels, 2500 pixels are printed. If you scale the Sprite object, + the same 2500 pixels are printed, but the Sprite object is printed at the scaled size.

+ +

The Flash Player printing feature supports PostScript and non-PostScript printers. + Non-PostScript printers convert vectors to bitmaps.

+ +
PrintJob.send()PrintJob.start()DisplayObject class
selectPaperSize + Set the paper size.if the paperSize parameter is not one of the + acceptable values defined in the PaperSize class. + + ArgumentErrorArgumentErrorpaperSizeStringThe paper size to use for subsequent pages in the print job + + + Set the paper size. The acceptable values for the paperSize parameter + are constants in the PaperSize class. Calling this method affects print + settings as if the user chooses a paper size in the Page Setup or Print dialogs. + +

You can call this method at any time. Call this method before starting + a print job to set the default paper size in the Page Setup and Print dialogs. Call + this method while a print job is in progress to set the paper size for + a range of pages within the job.

+ + + import flash.printing.PrintJob; + import flash.printing.PaperSize; + + var myPrintJob:PrintJob = new PrintJob(); + myPrintJob.selectPaperSize(PaperSize.ENV_10); + + +
PaperSizePrintJob.send()
send + Sends spooled pages to the printer after successful calls to the start() or + start2() and addPage() methods. + Sends spooled pages to the printer after successful calls to the start() or + start2() and addPage() methods. + +

This method does not succeed if the call to the start() or start2() method fails, or + if a call to the addPage() method throws an exception. To avoid an error, + check that the start() or start2() method returns + true and catch any addPage() exceptions before calling + this method. The following example demonstrates how to properly check for errors + before calling this method:

+ + + var myPrintJob:PrintJob = new PrintJob(); + if (myPrintJob.start()) { + try { + myPrintJob.addPage([params]); + } + catch(e:Error) { + // handle error + } + + myPrintJob.send(); + } + + +
PrintJob.addPage()PrintJob.start()PrintJob.start2()
showPageSetupDialog + Displays the operating system's Page Setup dialog if the current environment + supports it.if the system does not support Page Setup. Use the + supportsPageSetupDialog property to determine if Page Setup is supported. + IllegalOperationErrorflash.errors:IllegalOperationErrorif any print job (including the current one) is active. + + IllegalOperationErrorflash.errors:IllegalOperationErrortrue if the user chooses "OK" in the Page Setup dialog. This + indicates that some PrintJob properties may have changed. Returns false + if the user chooses "Cancel" in the Page Setup dialog. + + Boolean + Displays the operating system's Page Setup dialog if the current environment + supports it. Use the supportsPageSetupDialog property to determine if Page Setup + is supported. + + + import flash.printing.PrintJob; + + var myPrintJob:PrintJob = new PrintJob(); + if (myPrintJob.supportsPageSetupDialog) + { + myPrintJob.showPageSetupDialog(); + } + + + PrintJob.supportsPageSetupDialogstart2 + Optionally displays the operating system's Print dialog box, starts spooling, and + possibly modifies the PrintJob read-only property values.If the Page Setup dialog is being displayed, or if + another print job is currently active + + IllegalOperationErrorflash.errors:IllegalOperationErrorA value of true if the user clicks OK when the Print dialog box appears, + or if the Print dialog is not shown and there is no error; + false if the user clicks Cancel or if an error occurs. + + BooleanuiOptionsflash.printing:PrintUIOptionsnullAn object designating which options are displayed in the Print dialog that + is shown to the user. If the showPrintDialog parameter is false, + this value is ignored. + + showPrintDialogBooleantrueWhether or not the Print dialog is shown to the user before starting + the print job + + + Optionally displays the operating system's Print dialog box, starts spooling, and + possibly modifies the PrintJob read-only property values. + +

The uiOptions parameter allows the caller to control which options are displayed in + the Print dialog. See the PrintUIOptions class. This parameter is ignored if + showPrintDialog is false.

+ +

Even when showPrintDialog is true, this method's behavior + can differ from the start() method. On some operating systems, + start() shows the Page Setup dialog followed by the Print dialog. + In contrast, start2() never shows the Page Setup dialog.

+ +

In the following example, the min and max page settings in the Print dialog are set + before the dialog is displayed to the user:

+ + + import flash.printing.PrintJob; + import flash.printing.PrintUIOptions; + + var myPrintJob:PrintJob = new PrintJob(); + var uiOpt:PrintUIOptions = new PrintUIOptions(); + uiOpt.minPage = 1; + uiOpt.maxPage = 3; + var accepted:Boolean = myPrintJob.start2(uiOpt); + + +
PrintJob.addPage()PrintJob.send()
start + Displays the operating system's Print dialog box and starts spooling.in AIR 2 or later, if another PrintJob is currently active + + IllegalOperationErrorflash.errors:IllegalOperationErrorA value of true if the user clicks OK when the Print dialog box appears; false if the user clicks Cancel or if an error occurs. + + Boolean + Displays the operating system's Print dialog box and starts spooling. The Print dialog box lets the user change print settings. When the + PrintJob.start() method returns successfully (the user clicks OK in the Print dialog + box), the following properties are populated, representing the user's chosen print settings: + + PropertyTypeUnitsNotesPrintJob.paperHeightNumberPointsOverall paper height.PrintJob.paperWidthNumberPointsOverall paper width.PrintJob.pageHeightNumberPointsHeight of actual printable area on the page; any user-set margins are ignored.PrintJob.pageWidthNumberPointsWidth of actual printable area on the page; any user-set margins are ignored.PrintJob.orientationString"portrait" (flash.printing.PrintJobOrientation.PORTRAIT) or "landscape" (flash.printing.PrintJobOrientation.LANDSCAPE). + +

Note: If the user cancels the Print dialog box, the properties are not populated.

+

After the user clicks OK in the Print dialog box, the player begins spooling a print job to the operating system. + Because the operating system then begins displaying information to the user about the printing progress, + you should call the PrintJob.addPage() and PrintJob.send() calls as soon as possible to send + pages to the spooler. You can use the read-only height, width, and orientation properties this method populates to + format the printout.

+

Test to see if this method returns true (when the user clicks OK in the operating system's Print + dialog box) before any subsequent calls to PrintJob.addPage() and PrintJob.send():

+ + var myPrintJob:PrintJob = new PrintJob(); + if(myPrintJob.start()) { + // addPage() and send() statements here + } + +

For the given print job instance, if any of the following intervals last more than + 15 seconds the next call to PrintJob.start() will return false:

+
  • PrintJob.start() and the first PrintJob.addPage()
  • One PrintJob.addPage() and the next PrintJob.addPage()
  • The last PrintJob.addPage() and PrintJob.send()
+
PrintJob.addPage()PrintJob.send()
terminate + Signals that the print job should be terminated without sending. + Signals that the print job should be terminated without sending. Use this method + when a print job has already been initiated by a call to start() or + start2(), but when it is not appropriate to send any pages to the printer. + Typically, terminate() is only used to recover from errors. + +

After calling this method, the PrintJob instance can be reused. Wherever possible, + the job's print settings are retained for subsequent use.

+ +
active + Indicates whether a print job is currently active.Boolean + Indicates whether a print job is currently active. A print job is active (the property + value is true) in either of two conditions: + +
  • A Page Setup or Print dialog is being displayed.
  • The start() or start2() method has been called with + a true return value, and the send() or + terminate() method has not been called.
+ +

If this property is true and you call the showPageSetupDialog(), + start(), or start2() method, the runtime throws an exception.

+ +
PrintJob.start()PrintJob.start2()PrintJob.send()PrintJob.terminate()
copies + The number of copies that the print system prints of any pages subsequently added to the + print job.int + The number of copies that the print system prints of any pages subsequently added to the + print job. This value is the number of copies entered by the user in the operating system's + Print dialog. If the the number of copies was not displayed in the + Print dialog, or the dialog was not presented to the user, the value is 1 (unless it has + been changed by application code). + + firstPage + The page number of the first page of the range entered by the user in the operating system's + Print dialog.int + The page number of the first page of the range entered by the user in the operating system's + Print dialog. This property is zero if the user requests that all pages be printed, or + if the page range was not displayed in the Print dialog, or if the Print dialog + has not been presented to the user. + + isColor + Indicates whether the currently selected printer at the current print settings prints + using color (true) or grayscale (false).Boolean + Indicates whether the currently selected printer at the current print settings prints + using color (true) or grayscale (false). + +

If a color-or-grayscale value can't be determined, the value is true.

+ +
isSupported + Indicates whether the PrintJob class is supported on the current platform (true) + or not (false).Boolean + Indicates whether the PrintJob class is supported on the current platform (true) + or not (false). + + jobName + The name or title of the print job.Stringif code attempts to set the property while the active + property is true. + + IllegalOperationErrorflash.errors:IllegalOperationError<code>null</code> + + + The name or title of the print job. The job name is typically used by + the operating system as the title of the job in the print queue, or + as the default name of a job that is printed to a file. + +

If you have not called start() or start2() and you haven't + set a value for the property, this property's value is null.

+ +

For each print job you execute with a PrintJob instance, set this property before + calling the start() or start2() method.

+ +
lastPage + The page number of the last page of the range entered by the user in the operating system's + Print dialog.int + The page number of the last page of the range entered by the user in the operating system's + Print dialog. This property is zero if the user requests that all pages be printed, or + if the page range was not displayed in the Print dialog, or if the Print dialog + has not been presented to the user. + + maxPixelsPerInch + The physical resolution of the selected printer, in pixels per inch.Number + The physical resolution of the selected printer, in pixels per inch. The value + is calculated according to the current print settings as reported by the operating system. + +

If the resolution cannot be determined, the value is a standard default value. + The default value is 600 ppi on Linux and 360 ppi on Mac OS. On Windows, + the printer resolution is always available, so no default value is necessary.

+ +
orientation + The image orientation for printing.String + The image orientation for printing. The acceptable values are defined as constants + in the PrintJobOrientation class. + +

Note: For AIR 2 or later, set this property before + starting a print job to set the default orientation in the Page Setup and Print dialogs. + Set the property while a print job is in progress (after calling start() or + start2() to set the orientation for a range of pages within the job.

+ +
PrintJobOrientation class
pageHeight + The height of the largest area which can be centered in the actual printable + area on the page, in points.int + The height of the largest area which can be centered in the actual printable + area on the page, in points. + Any user-set margins are ignored. This property is available only + after a call to the PrintJob.start() method has been made. + +

Note: For AIR 2 or later, this property is deprecated. Use + printableArea instead, which measures + the printable area in fractional points and describes off-center printable areas + accurately.

+ +
PrintJob.printableArea
pageWidth + The width of the largest area which can be centered in the actual printable + area on the page, in points.int + The width of the largest area which can be centered in the actual printable + area on the page, in points. + Any user-set margins are ignored. This property is available only + after a call to the PrintJob.start() method has been made. + +

Note: For AIR 2 or later, this property is deprecated. Use + printableArea instead, which measures + the printable area in fractional points and describes off-center printable areas + accurately.

+ +
PrintJob.printableArea
paperArea + The bounds of the printer media in points.flash.geom:Rectangle + The bounds of the printer media in points. This value uses the same coordinate system + that is used for subsequent addPage() calls. + + paperHeight + The overall paper height, in points.int + The overall paper height, in points. This property is available only + after a call to the PrintJob.start() method has been made. + +

Note: For AIR 2 or later, this property is deprecated. Use + paperArea instead, which measures the + paper dimensions in fractional points.

+ +
PrintJob.paperArea
paperWidth + The overall paper width, in points.int + The overall paper width, in points. This property is available only + after a call to the PrintJob.start() method has been made. + +

Note: For AIR 2 or later, this property is deprecated. Use + paperArea instead, which measures the + paper dimensions in fractional points.

+ +
PrintJob.paperArea
printableArea + The bounds of the printer media's printable area in points.flash.geom:Rectangle + The bounds of the printer media's printable area in points. This value uses the same + coordinate system that is used for subsequent addPage() calls. + + printer + Gets or sets the printer to use for the current print job.String + Gets or sets the printer to use for the current print job. The String passed + to the setter and returned by the getter should match one of the strings in the + Array returned by the printers() method. To indicate that the default + printer should be used, set the value to null. On operating systems + where the default printer cannot be determined, this property's value is null. + + + import flash.printing.PrintJob; + + var myPrintJob:PrintJob = new PrintJob(); + myPrintJob.printer = "HP_LaserJet_1"; + myPrintJob.start(); + + +

Setting the value of this property attempts to select the printer immediately. + If the printer selection fails, this property's value resets to the previous value. + You can determine if setting the printer value succeeds by reading the + value after attempting to set it, and confirming that it matches the value + that was set.

+ +

The printer property of an active print job cannot be changed. + Attempting to change it after calling the start() or start2() + method successfully and before calling send() or terminate() fails.

+ +
printers + Provides a list of the available printers as String name values. + Provides a list of the available printers as String name values. + The list is not precalculated; it is generated when the function is called. If + no printers are available or if the system does not support printing, the + value is null. If the system supports printing but is not capable of returning + a list of printers, the value is a Vector with a single element (its length + property is 1). In that case, the single element is the actual printer name + or a default name if the current printer name cannot be determined. + + supportsPageSetupDialog + Indicates whether the Flash runtime environment supports a separate + Page Setup dialog.Boolean + Indicates whether the Flash runtime environment supports a separate + Page Setup dialog. If this property is true, you can call + the showPageSetupDialog() method to display the operating + system's page setup dialog box. + + PrintJob.showPageSetupDialog()
PrintJobOrientation +This class provides values that are used by the PrintJob.orientation property for the image position of a printed page.Object +This class provides values that are used by the PrintJob.orientation property for the image position of a printed page. +PrintJob.orientationLANDSCAPE + The landscape (horizontal) image orientation for printing.landscapeString + The landscape (horizontal) image orientation for printing. + This constant is used with the PrintJob.orientation property. + Use the syntax PrintJobOrientation.LANDSCAPE. + + PrintJob.orientationPORTRAITPORTRAIT + The portrait (vertical) image orientation for printing.portraitString + The portrait (vertical) image orientation for printing. + This constant is used with the PrintJob.orientation property. + Use the syntax PrintJobOrientation.PORTRAIT. + + PrintJob.orientationLANDSCAPEPaperSize +This class provides the available values for the paperSize parameter of +the PrintJob.selectPaperSize() method.Object +This class provides the available values for the paperSize parameter of +the PrintJob.selectPaperSize() method. Each constant represents a paper size +that is used to print a page. + +

The following table shows the approximate size for each paper type. The size is approximate +because there is some variation among printer drivers. For example, the width of A4 paper +can be 595.0, 595.2, 595.22 or 595.28 points depending on the driver.

+ +ValueSize in pointsA4595 x 842A5420 x 595A6297 x 420CHOUKEI3GOU340 x 666CHOUKEI4GOU298 x 666ENV_10297 x 684ENV_B5499 x 709ENV_C5459 x 649ENV_DL312 x 624ENV_MONARCH279 x 540ENV_PERSONAL261 x 468EXECUTIVE522 x 756FOLIO612 x 936JIS_B5516 x 729LEGAL612 x 1008LETTER612 x 792STATEMENT396 x 612 + +
PrintJob.selectPaperSize()A4 + A4 + + a4String + A4 + + A5 + A5 + + a5String + A5 + + A6 + A6 + + a6String + A6 + + CHOUKEI3GOU + Japanese choukei 3 gou (envelope) + + choukei3gouString + Japanese choukei 3 gou (envelope) + + CHOUKEI4GOU + Japanese choukei 4 gou (envelope) + + choukei4gouString + Japanese choukei 4 gou (envelope) + + ENV_10 + Legal envelope + + env_10String + Legal envelope + + ENV_B5 + B5 envelope + + env_b5String + B5 envelope + + ENV_C5 + C5 envelope + + env_c5String + C5 envelope + + ENV_DL + DL envelope + + env_dlString + DL envelope + + ENV_MONARCH + Monarch envelope + + env_monarchString + Monarch envelope + + ENV_PERSONAL + Personal envelope + + env_personalString + Personal envelope + + EXECUTIVE + Executive size + + executiveString + Executive size + + FOLIO + Folio size + + folioString + Folio size + + JIS_B5 + Japanese B5 + + jis_b5String + Japanese B5 + + LEGAL + Traditional legal size + + legalString + Traditional legal size + + LETTER + Traditional letter size + + letterString + Traditional letter size + + STATEMENT + Statement size + + statementString + Statement size + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.profiler.xml b/language-server/playerglobal_docs/flash.profiler.xml new file mode 100644 index 0000000..2b33a3d --- /dev/null +++ b/language-server/playerglobal_docs/flash.profiler.xml @@ -0,0 +1,30 @@ +flash.profilershowRedrawRegions + + Shows or hides redraw regions.onBooleanSpecifies whether to show or hide + redraw regions. When set to true, the redraw rectangles are + shown. When set to false, the redraw rectangles are hidden. + coloruint0xFF0000Sets the color of the rectangles. If you do not specify this parameter, + 0xFF0000 is used. + + Shows or hides redraw regions. Enables the debugger version of Flash® Player to outline + the regions of the screen that are being redrawn (that is regions that are being + updated). + + \ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.sampler.xml b/language-server/playerglobal_docs/flash.sampler.xml new file mode 100644 index 0000000..291a64c --- /dev/null +++ b/language-server/playerglobal_docs/flash.sampler.xml @@ -0,0 +1,717 @@ +flash.samplerStackFrame + + The StackFrame class provides access to the properties of a data block + containing a function.Object + The StackFrame class provides access to the properties of a data block + containing a function. For Flash Player debugger version only. + toString + Converts the StackFrame to a string of its properties.A string containing the name property, and optionally the file + and line properties (if a SWF file is being debugged) of the StackFrame object. For Flash Player debugger version only. + String + Converts the StackFrame to a string of its properties. + file + The file name of the SWF file being debugged.String + The file name of the SWF file being debugged. For Flash Player debugger version only. + line + The line number for the function in the SWF file being debugged.uint + The line number for the function in the SWF file being debugged. For Flash Player debugger version only. + name + The function name in the stack frame.String + The function name in the stack frame. For Flash Player debugger version only. + scriptID + The identifier for the script function in the application being profiled.Number + The identifier for the script function in the application being profiled. + NewObjectSample + The NewObjectSample class represents objects that are created within a getSamples() stream.flash.sampler:Sample + The NewObjectSample class represents objects that are created within a getSamples() stream. + For Flash Player debugger version only. + The following example uses the stack and time properties of a Sample object + s to collect memory samples. The samples contain NewObjectSample objects (the + newSamples array), DeleteObjectSample objects (the delSamples array), and CPU memory sample + objects (the cpuSamples array). To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later installed. + +package +{ + import flash.sampler.* + import flash.system.* + import flash.utils.* + import flash.display.Sprite + public class sampleTypes extends Sprite + { + var b:Boolean = true + public function sampleTypes() { + flash.sampler.startSampling(); + for(var i:int=0;i<10000;i++) + new Object(); + + var cpuSamples:Array=[]; + var newSamples:Array=[]; + var delSamples:Array=[]; + var ids:Array=[] + + var lastTime:Number=0; + for each(var s:Sample in getSamples()) { + + assert(s.time > 0); // positive + assert(Math.floor(s.time) == s.time, s.time); // integral + assert(s.time >= lastTime, s.time + ":" + lastTime); // ascending + assert(s.stack == null || s.stack is Array) + if(s.stack) { + assert(s.stack[0] is StackFrame); + assert(s.stack[0].name is String); + } + + if(s is NewObjectSample) { + var nos = NewObjectSample(s); + assert(s.id > 0, s.id); + assert(s.type is Class, getQualifiedClassName(s.type)); + newSamples.push(s); + ids[s.id] = "got one"; + } else if(s is DeleteObjectSample) { + var dos = DeleteObjectSample(s); + delSamples.push(s); + assert(ids[dos.id] == "got one"); + } else if(s is Sample) + cpuSamples.push(s); + else { + assert(false); + } + lastTime = s.time; + } + + trace(b) + trace(newSamples.length > 0) + trace(cpuSamples.length > 0) + trace(delSamples.length > 0) + + } + + private function assert(e:Boolean, mess:String=null):void { + b = e && b; + if(true && !e) { + if(mess) trace(mess); + trace(new Error().getStackTrace()); + } + } + } +} +flash.sampler.getSamples()type + The Class object corresponding to the object created within a getSamples() stream.Class + The Class object corresponding to the object created within a getSamples() stream. + For Flash Player debugger version only. + object + The NewObjectSample object if it still exists. + The NewObjectSample object if it still exists. If the object has been garbage collected, this property is + undefined and a corresponding DeleteObjectSample exists. For Flash Player debugger version only. + flash.sampler.DeleteObjectSamplesize + The NewObjectSample object size.Number + The NewObjectSample object size. If the object has been garbagecollected, this property is + undefined and a corresponding DeleteObjectSample exists. For FlashPlayer debugger version only. + flash.sampler.DeleteObjectSampleclearSamples + Clears the current set of Sample objects. + Clears the current set of Sample objects. This method is usually called after calling getSamples() + and iterating over the Sample objects. + For Flash Player debugger version only. + getSamples()getGetterInvocationCount + Returns the number of times a get function was executed.The number of times a get method was executed. + NumberobjObjectA method instance or a class. + qnameQNameIf qname is undefined return the number of iterations of the constructor function. + + Returns the number of times a get function was executed. Use + isGetterSetter() to verify that you have a get/set function before you use + getGetterInvocationCount(). For Flash Player debugger version only. + isGetterSetter()getInvocationCount()getInvocationCount + Returns the number of times a method was executed.The number of times a method was executed. + NumberobjObjectA method instance or a class. A class can be used to get the invocation count of + instance functions when a method instance isn't available. If obj is undefined, + this method returns the count of the package-scoped function named by qname. + qnameQNameIf qname is undefined return the number of iterations of the constructor function. + + Returns the number of times a method was executed. If the parameter obj + is a Class and the parameter qname is undefined then this method + returns the number of iterations of the constructor function. For Flash Player debugger version only. + + + package +{ + public function exec3() {} + + import flash.sampler.*; + import flash.system.*; + import flash.display.Sprite; + import flash.utils.*; + public class getInvocationCountTest extends Sprite + { + public function getInvocationCountTest() + { + for(var i:int=0;i<10;i++) + exec(); + for(var i:int=0;i<10;i++) + exec2(); + for(var i:int=0;i<10;i++) + exec3(); + + // get exec QName + var execName:QName; + var name:QName; + var fooName:QName; + for each(name in getMemberNames(this)) { + if(name.localName == "exec") + execName = name; + if(name.localName == "foo") + fooName = name; + } + + var exec2Name:QName; + for each(name in getMemberNames(getInvocationCountTest)) { + if(name.localName == "exec2") + exec2Name = name; + } + + // execute get/set + foo = "bar"; + + trace(isGetterSetter(this, fooName)); + trace(getSetterInvocationCount(this, fooName) == 1); + trace(getGetterInvocationCount(this, fooName) == 0); + + foo; + + trace(getSetterInvocationCount(getInvocationCountTest, fooName) == 1); + trace(getGetterInvocationCount(getInvocationCountTest, fooName) == 1); + + trace(getInvocationCount(this, execName) == 10); + trace(getInvocationCount(getInvocationCountTest, execName) == 10); + trace(getInvocationCount(getInvocationCountTest, exec2Name) == 10); + trace(getInvocationCount(getInvocationCountTest, undefined) == 1); + + getTimer(); + getTimer(); + + trace(getInvocationCount(undefined, new QName("", "trace")) == 9); + trace(getInvocationCount(undefined, new QName("flash.utils", "getTimer")) == 2); + trace(getInvocationCount(undefined, new QName("", "exec3")) == 10); + + } + + private function exec():void {} + private static function exec2():void {} + + private function get foo():String { return "fo"; } + private function set foo(s:String) { } + + } +} +getLexicalScopes + Exposes the lexical scope of a Function so that captured scope objects (including activation + objects and with scopes) are seen by the profiler as being retained by the Function instance.An array containings all the lexical scope elements + ArrayobjFunctionA function + + Exposes the lexical scope of a Function so that captured scope objects (including activation + objects and with scopes) are seen by the profiler as being retained by the Function instance. + getMasterString + Returns the master string upon which this string depends, or null if this + string does not depend on another string.The string upon which the passed-in string depends, or null if the + passed-in string does not depend on another string + StringstrStringA string + + Returns the master string upon which this string depends, or null if this + string does not depend on another string. For example, if you call + String.substr(), the returned string will often actually be + implemented as just a pointer into the original string, for the sake of efficiency. + In normal usage, this is an implementation detail which is not visible to the user; + however, it can be confusing when using a profiler to analyze your program's + memory consumption, because the string may be shown as taking less memory + than would be needed for the string's value. In addition, a string might + be retained in memory solely because it is the master for other strings. + getMasterString() allows profilers to show the user an accurate + graph of string dependencies. + getMemberNames + Returns an object containing all members of a specified object, including private members.An Object that you must iterate over with a for each..in loop to retrieve the QNames for + each property. + ObjectoObjectThe object to analyze. + instanceNamesBooleanfalseIf object is a Class and instanceNames is true report the instance names as if o was an instance of class instead of the class's member names. + + Returns an object containing all members of a specified object, including private members. You can then + iterate over the returned object to see all values. This method is similar to the flash.utils.describeType() + method but also allows you to see private members and skips the intermediate step of creating an XML object. + For Flash Player debugger version only. + + The following example uses the getMemberNames() method to analyze an + object and display the buttonMode, filters and dispatchEvent + properties of its members, To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later installed. + + package +{ + import flash.sampler.*; + import flash.system.*; + import flash.display.Sprite; + public class getMemberNamesTest extends Sprite + { + public function getMemberNamesTest() + { + var name_iter = getMemberNames(this); + var o={}; + for each(var name:QName in name_iter) { + o[name.localName] = "got it"; + } + + name_iter = getMemberNames(this); + var count=0; + for(var dum in name_iter) { + count++; + } + trace(count == 1); + + // my member + trace("buttonMode" in o); + // inherited member + trace("filters" in o); + // inherited function + trace("dispatchEvent" in o); + + var name_iter = getMemberNames(getMemberNamesTest, true); + var o={}; + for each(var name:QName in name_iter) { + o[name.localName] = "got it"; + } + + // my member + trace("buttonMode" in o); + // inherited member + trace("filters" in o); + // inherited function + trace("dispatchEvent" in o); + + } + } +} +flash.utils.describeType()for each..ingetSampleCount + Returns the number of samples collected.An iterator of Sample instances. + Number + Returns the number of samples collected. For Flash Player debugger version only. + + flash.sampler.SamplegetSamples + Returns an object of memory usage Sample instances from the last sampling session.An iterator of Sample instances. + Object + Returns an object of memory usage Sample instances from the last sampling session. For Flash Player debugger version only. + + flash.sampler.SamplegetSavedThis + Returns the saved "this" from a Method closure that you normal can't see from AS.An object that is the "this" of the MethodClosure + ObjectobjFunctionA MethodClosure instance + + Returns the saved "this" from a Method closure that you normal can't see from AS. + getSetterInvocationCount + Returns the number of times a set function was executed.The number of times a set method was executed. + NumberobjObjectA method instance or a class. + qnameQNameIf qname is undefined return the number of iterations of the constructor function. + + Returns the number of times a set function was executed. Use + isGetterSetter() to verify that you have a get/set function before you use + getSetterInvocationCount(). For Flash Player debugger version only. + isGetterSetter()getInvocationCount()getSize + Returns the size in memory of a specified object when used with the Flash Player 9.0.115.0 or later debugger version.The byte count of memory used by the specified object. + NumberoThe object to analyze for memory usage. + + Returns the size in memory of a specified object when used with the Flash Player 9.0.115.0 or later debugger version. If + used with a Flash Player that is not the debugger version, this method returns 0. + The following example uses startSampling() and pauseSampling to collect + Sample objects. The example then iterates over the Sample objects for id values and + sizes. After calling System.gc() to stop the current process, the example compares the deletedObjectSample + objects to the original id values and displays their size. To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later installed. + + package { + import flash.sampler.*; + import flash.system.*; + import flash.display.Sprite; + import flash.utils.Dictionary; + public class deletedObjectSize extends Sprite { + public function deletedObjectSize() { + + startSampling(); + var obj = {}; + pauseSampling(); + + var id:Number; + var sampleIter = getSamples(); + for each(var s:Sample in sampleIter) { + id = s.id; + } + + sampleIter = getSamples(); + var count=0; + for(var dum in sampleIter) { + count++; + } + trace(count == 1); + + var size:Number = getSize(obj); + obj = undefined; + + startSampling(); + + // force DRC + for(var i:int=0;i<1000;i++) + new Object(); + + System.gc(); + + pauseSampling(); + + var sampleIter = getSamples(); + for each(var s:Sample in sampleIter) { + // trace(s); + if(s is DeleteObjectSample && s.id == id) { + trace(s.size == size); + } + } + + } + } +} +isGetterSetter + Checks to see if a property is defined by a get/set function.A Boolean value indicating if the property is defined by a get/set function (true) + or not (false). + BooleanobjObjectA method instance or a class. + qnameQNameIf qname is undefined return the number of iterations of the constructor function. + + Checks to see if a property is defined by a get/set function. If you want to use + getInvocationCount() on a get/set function for a property, + first call isGetterSetter() to check to see if it is a get/set function, + and then use either getSetterInvocationCount + or getGetterInvocationCount to get the respective counts. For Flash Player debugger version only. + + + package +{ + public function exec3() {} + + import flash.sampler.*; + import flash.system.*; + import flash.display.Sprite; + import flash.utils.*; + public class getInvocationCountTest extends Sprite + { + public function getInvocationCountTest() + { + for(var i:int=0;i<10;i++) + exec(); + for(var i:int=0;i<10;i++) + exec2(); + for(var i:int=0;i<10;i++) + exec3(); + + // get exec QName + var execName:QName; + var name:QName; + var fooName:QName; + for each(name in getMemberNames(this)) { + if(name.localName == "exec") + execName = name; + if(name.localName == "foo") + fooName = name; + } + + var exec2Name:QName; + for each(name in getMemberNames(getInvocationCountTest)) { + if(name.localName == "exec2") + exec2Name = name; + } + + // execute get/set + foo = "bar"; + + trace(isGetterSetter(this, fooName)); + trace(getSetterInvocationCount(this, fooName) == 1); + trace(getGetterInvocationCount(this, fooName) == 0); + + foo; + + trace(getSetterInvocationCount(getInvocationCountTest, fooName) == 1); + trace(getGetterInvocationCount(getInvocationCountTest, fooName) == 1); + + trace(getInvocationCount(this, execName) == 10); + trace(getInvocationCount(getInvocationCountTest, execName) == 10); + trace(getInvocationCount(getInvocationCountTest, exec2Name) == 10); + trace(getInvocationCount(getInvocationCountTest, undefined) == 1); + + getTimer(); + getTimer(); + + trace(getInvocationCount(undefined, new QName("", "trace")) == 9); + trace(getInvocationCount(undefined, new QName("flash.utils", "getTimer")) == 2); + trace(getInvocationCount(undefined, new QName("", "exec3")) == 10); + + } + + private function exec():void {} + private static function exec2():void {} + + private function get foo():String { return "fo"; } + private function set foo(s:String) { } + + } +} +getInvocationCount()getSetterInvocationCount()getGetterInvocationCount()pauseSampling + Stops the sampling process momentarily. + Stops the sampling process momentarily. Restart the sampling process using startSampling(). + For Flash Player debugger version only. + startSampling()sampleInternalAllocs + Tells the sampler if it should create NewObjectSamples for internal allocations from the flash player.bBoolean + Tells the sampler if it should create NewObjectSamples for internal allocations from the flash player. + If this is set to true, then every allocation will generate a NewObjectSample. These internal allocs will + not have a type, or a reference to the Object. They will have the ActionScript stack trace that triggered the + allocation. Defaults to false, which only collects allocations for ActionScript objects. + setSamplerCallback + Sets a callback function for the sampler - this function will be called when the sample stream is almost + exhausted.fFunction + Sets a callback function for the sampler - this function will be called when the sample stream is almost + exhausted. This should be used to process samples before the sample buffer is filled. pauseSampling will be called + before the callback is called, and startSampling will be called after the callback has been executed. + startSampling + Begins the process of collecting memory usage Sample objects. + Begins the process of collecting memory usage Sample objects. + For Flash Player debugger version only. + The following example initiates the sampling process and iterates over the collected objects. To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later. + +package +{ + import flash.sampler.* + import flash.system.* + import flash.display.Sprite + public class startSampling extends Sprite + { + public function startSampling() + { + flash.sampler.startSampling(); + for(var i:int=0;i<1000;i++) + new Object() + trace(getSampleCount() > 0) + } + } +} +Sample classstopSampling + Ends the process of collecting memory usage Sample objects and frees resources dedicated to the sampling process. + Ends the process of collecting memory usage Sample objects and frees resources dedicated to the sampling process. + You start the sampling process with startSampling(). + For Flash Player debugger version only. + Sample classSample + The Sample class creates objects that hold memory analysis information over distinct durations.Object + The Sample class creates objects that hold memory analysis information over distinct durations. + For Flash Player debugger version only. + + The following example uses the stack and time properties of a Sample object + s to collect memory samples. The samples contain NewObjectSample objects (the + newSamples array), DeleteObjectSample objects (the delSamples array), and CPU memory sample + objects (the cpuSamples array). To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later installed. + +package +{ + import flash.sampler.* + import flash.system.* + import flash.utils.* + import flash.display.Sprite + public class sampleTypes extends Sprite + { + var b:Boolean = true + public function sampleTypes() { + flash.sampler.startSampling(); + for(var i:int=0;i<10000;i++) + new Object(); + + var cpuSamples:Array=[]; + var newSamples:Array=[]; + var delSamples:Array=[]; + var ids:Array=[] + + var lastTime:Number=0; + for each(var s:Sample in getSamples()) { + + assert(s.time > 0); // positive + assert(Math.floor(s.time) == s.time, s.time); // integral + assert(s.time >= lastTime, s.time + ":" + lastTime); // ascending + assert(s.stack == null || s.stack is Array) + if(s.stack) { + assert(s.stack[0] is StackFrame); + assert(s.stack[0].name is String); + } + + if(s is NewObjectSample) { + var nos = NewObjectSample(s); + assert(s.id > 0, s.id); + assert(s.type is Class, getQualifiedClassName(s.type)); + newSamples.push(s); + ids[s.id] = "got one"; + } else if(s is DeleteObjectSample) { + var dos = DeleteObjectSample(s); + delSamples.push(s); + assert(ids[dos.id] == "got one"); + } else if(s is Sample) + cpuSamples.push(s); + else { + assert(false); + } + lastTime = s.time; + } + + trace(b) + trace(newSamples.length > 0) + trace(cpuSamples.length > 0) + trace(delSamples.length > 0) + + } + + private function assert(e:Boolean, mess:String=null):void { + b = e && b; + if(true && !e) { + if(mess) trace(mess); + trace(new Error().getStackTrace()); + } + } + } +} +flash.sampler.getSamples()stack + Contains information about the methods executed by Flash Player over a specified period of time.Array + Contains information about the methods executed by Flash Player over a specified period of time. The format for the + stack trace is similiar to the content shown in the exception dialog box of the Flash Player debugger version. + For Flash Player debugger version only. + time + The microseconds that define the duration of the Sample instance.Number + The microseconds that define the duration of the Sample instance. For Flash Player debugger version only. + + DeleteObjectSample + The DeleteObjectSample class represents objects that are created within a getSamples() stream; each + DeleteObjectSample object corresponds to a NewObjectSample object.flash.sampler:Sample + The DeleteObjectSample class represents objects that are created within a getSamples() stream; each + DeleteObjectSample object corresponds to a NewObjectSample object. For Flash Player debugger version only. + The following example uses the stack and time properties of a Sample object + s to collect memory samples. The samples contain NewObjectSample objects (the + newSamples array), DeleteObjectSample objects (the delSamples array), and CPU memory sample + objects (the cpuSamples array). To use + the memory profiler, you need to have Flash Player debugger version 9.0.115.0 or later installed. + +package +{ + import flash.sampler.* + import flash.system.* + import flash.utils.* + import flash.display.Sprite + public class sampleTypes extends Sprite + { + var b:Boolean = true + public function sampleTypes() { + flash.sampler.startSampling(); + for(var i:int=0;i<10000;i++) + new Object(); + + var cpuSamples:Array=[]; + var newSamples:Array=[]; + var delSamples:Array=[]; + var ids:Array=[] + + var lastTime:Number=0; + for each(var s:Sample in getSamples()) { + + assert(s.time > 0); // positive + assert(Math.floor(s.time) == s.time, s.time); // integral + assert(s.time >= lastTime, s.time + ":" + lastTime); // ascending + assert(s.stack == null || s.stack is Array) + if(s.stack) { + assert(s.stack[0] is StackFrame); + assert(s.stack[0].name is String); + } + + if(s is NewObjectSample) { + var nos = NewObjectSample(s); + assert(s.id > 0, s.id); + assert(s.type is Class, getQualifiedClassName(s.type)); + newSamples.push(s); + ids[s.id] = "got one"; + } else if(s is DeleteObjectSample) { + var dos = DeleteObjectSample(s); + delSamples.push(s); + assert(ids[dos.id] == "got one"); + } else if(s is Sample) + cpuSamples.push(s); + else { + assert(false); + } + lastTime = s.time; + } + + trace(b) + trace(newSamples.length > 0) + trace(cpuSamples.length > 0) + trace(delSamples.length > 0) + + } + + private function assert(e:Boolean, mess:String=null):void { + b = e && b; + if(true && !e) { + if(mess) trace(mess); + trace(new Error().getStackTrace()); + } + } + } +} +flash.sampler.getSamples()id + The unique identification number that matches up with a NewObjectSample's identification number.Number + The unique identification number that matches up with a NewObjectSample's identification number. + For Flash Player debugger version only. + flash.sampler.NewObjectSample.idsize + The size of the DeleteObjectSample object before it is deleted.Number + The size of the DeleteObjectSample object before it is deleted. For Flash Player debugger version only. + flash.sampler.NewObjectSample.id \ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.security.xml b/language-server/playerglobal_docs/flash.security.xml new file mode 100644 index 0000000..cba3077 --- /dev/null +++ b/language-server/playerglobal_docs/flash.security.xml @@ -0,0 +1,711 @@ +flash.securityXMLSignatureValidator + + The XMLSignatureValidator class validates whether an XML + signature file is well formed, unmodified, and, optionally, whether + it is signed using a key linked to a trusted digital certificate.flash.events:EventDispatcher + The XMLSignatureValidator class validates whether an XML + signature file is well formed, unmodified, and, optionally, whether + it is signed using a key linked to a trusted digital certificate. + +

AIR profile support: This feature is supported + on all desktop operating systems and AIR for TV devices, but it is not supported on mobile devices. You can test + for support at run time using the XMLSignatureValidator.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

XMLSignatureValidator implements a subset of the + W3C Recommendation for XML-Signature Syntax and Processing and + should not be considered a conforming implementation. + The supported subset of the recommendation includes:

+
  • All of the core signature syntax except KeyInfo element.
  • The KeyInfo element only supports the X509Data element.
  • The X509Data element only supports the X509Certificate element.
  • The SHA256 digest method algorithm.
  • The PKCS1 signing algorithm.
  • The "Canonical XML without comments" Canonicalization Method and Transform algorithm.
  • The Manifest element in additional signature syntax.
+ +

You must provide an IURIDereferencer implementation in order to verify an XML signature. This + implementation class is responsible for resolving the URIs specified in the SignedInfo + elements of the signature file and returning the referenced data in an object, such + as a ByteArray, that implements the IDataInput interface.

+ +

In order to verify that the signing certificate chains to a trusted certificate, either + the XML signature must contain the certificates required to build the chain in X509Certificate + elements, or you must supply the certificates required to build the chain using the + addCertificate() method.

+ +

To verify an XMLSignature:

+
  1. Create an instance of the XMLSignatureValidator class.
  2. Set the uriDereferencer property of the instance to an instance of your + IURIDereferencer implementation class.
  3. Supply DER-encoded certificates for building the certificate trust chain, if desired, + using the addCertificate() method.
  4. Call the XMLSignatureValidator verify method, passing in the signature to + be verified.
  5. Check the validityStatus property after the XMLSignatureValidator object + dispatches a complete event.
+ +

About signature status:

+

The validity of an XML signature can be valid, invalid, or unknown. The overall + status depends on the verification status of the individual components of the signature file:

+
  • digestStatus — The validity of the cryptographic of the signature computed over + the SignedInfo element. Can be valid, invalid, or unknown.
  • identityStatus — The validity of the signing certificate. If the certificate has + expired, has been revoked, or altered, the status is invalid. If the certificate cannot be chained + to a trusted root certificate, the status is unknown. The certificate is not checked if the + digest is invalid. If not checked, the status will be reported as unknown.
  • referencesStatus — The validity of the data addressed by the references in the + SignedInfo element of the signature file. Can be valid, invalid, or + unknown. The references are not checked if the digest or certificate is invalid. + Reference checking can also be skipped based on the setting of the referencesValidationSetting property. + If not checked, the status will be reported as unknown.
+

The signature validity reported by the validityStatus property can be:

+
  • valid — If referencesStatus, digestStatus, and + identityStatus are all valid.
  • invalid — If any individual status is invalid.
  • unknown — If referencesStatus, digestStatus, or + identityStatus is unknown.
+ +

Canonicalization limitations:

+

The XML engine in AIR does not always produce the expected XML string when canonicalizing an XML document. + For this reason, it is recommended that you avoid putting inter-element whitespace in enveloped or detached signature + documents and do not redefine namespaces inside a signature document. In both cases, AIR may not recreate the document + with the same character sequence as the original and, therefore, validation will fail.

+ +
The following example loads and verifies a file containing an XML signature. + + To use this example, you must implement an IURIDereferencer appropriate for the signatures + to be validated (replacing the SignedMessageDereferencer class used in the example). + Run the example by calling SignatureValidatorExample.validateSignature( signatureFile ), + passing in the file referencing the XML signature document to validate. + + +import flash.events.Event; +import flash.filesystem.File; +import flash.filesystem.FileStream; +import flash.security.ReferencesValidationSetting; +import flash.security.XMLSignatureValidator; + +import com.example.SignedMessageDereferencer; //A custom class implementing IURIDereferencer + +public class SignatureValidatorExample{ + private var xmlSig:XML; + private const signatureNS:Namespace = new Namespace( "http://www.w3.org/2000/09/xmldsig#" ); + + public static function validateSignature( signatureFile:File ):void{ + try{ + //Set up the XMLSignatureValidator + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + verifier.addEventListener( Event.COMPLETE, verificationComplete ); + verifier.uriDereferencer = new SignedMessageDereferencer(); + verifier.referencesValidationSetting = ReferencesValidationSetting.VALID_OR_UNKNOWN_IDENTITY; + + //Load the signed document + var sigFileStream:FileStream = new FileStream(); + sigFileStream.open( signatureFile, FileMode.READ ); + var xmlDoc:XML = XML( sigFileStream.readUTFBytes(sigFileStream.bytesAvailable) ); + + //Get the last Signature element in the document + if( xmlDoc.name().localName != "Signature" ){ + var signatureList:XMLList = xmlDoc..signatureNS::Signature; + xmlSig = XML( signatureList[ signatureList.length()-1 ] ); + } else{ + xmlSig = xmlDoc; + } + + //Validate the signature + verifier.verify( xmlSig ); + + }catch (e:Error){ + statusDisplay.text = "Verification error.\n" + e; + } + } + + private static function verificationComplete(event:Event):void{ + trace( "Signature Validity: " + verifier.validityStatus ); + trace( "Digest validity: " + verifier.digestStatus ); + trace( "Certificate validity: " + verifier.identityStatus ); + trace( "Data validity: " + verifier.referencesStatus ); + } +} +
IURIDereferencerXML-Signature Syntax and ProcessingCanonical XMLPKCS #1error + Dispatched if verification cannot complete because of errors.flash.events.ErrorEvent.ERRORflash.events.ErrorEvent + Dispatched if verification cannot complete because of errors. + + The following example listens for the error event dispatched by an XMLSignatureValidator + object and traces the error message: + +private function verificationError(event:ErrorEvent):void{ + trace("Verification error: " + event.text); +} +complete + Dispatched when verification is complete.flash.events.Event.COMPLETEflash.events.Event + Dispatched when verification is complete. + +

A complete event does not imply that the + signature is valid. Check the validityStatus property of + the XMLSignatureValidator object to + determine the outcome of the signature verification.

+ +
The following example listens for the complete event dispatched by an XMLSignatureValidator + object and traces the validation results: + +private function verificationComplete(event:Event):void{ + var validator:XMLSignatureValidator = event.target as XMLSignatureValidator; + trace("Digest status: " + validator.digestStatus); + trace("Identity status: " + validator.identityStatus); + trace("Reference status: " + validator.referencesStatus); + trace("Signature status: " + validator.validityStatus); +} +
validityStatus
XMLSignatureValidator + Creates an XMLSignatureValidator object. + Creates an XMLSignatureValidator object. + +

You must set the uriDereferencer property before calling the verify() + method of the new object.

+ +
The following example creates and sets up a new XMLSignatureValidator object: + +import com.example.EnvelopedDereferencer; //Your custom IURIDereferencer implementation + +//Create the object +var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + +//Provide the IURIDerferencer +verifier.uriDereferencer = new EnvelopedDereferencer(xmlDoc); + +//Set validation options +verifier.referencesValidationSetting = ReferencesValidationSetting.VALID_OR_UNKNOWN_IDENTITY; +verifier.revocationCheckSetting = RevocationCheckSettings.NEVER; +verifier.useSystemTrustStore = true; + +//Add listeners to handle results +verifier.addEventListener(Event.COMPLETE, verificationComplete); +verifier.addEventListener(ErrorEvent.ERROR, verificationError); +
uriDereferencer
addCertificate + Adds an x509 certificate for chain building.If called while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationErrorcertflash.utils:ByteArrayA ByteArray object containing a DER-encoded x509 digital certificate. + trustedBooleanSet to true to designate this certificate as a trust anchor. + + Adds an x509 certificate for chain building. + +

The certificate added must be a DER-encoded x509 certificate.

+ +

If the trusted parameter is true, the + certificate is considered a trust anchor.

+ +

Note: An XML signature may include certificates for building + the signer's certificate chain. The XMLSignatureValidator class uses + these certificates for chain building, but not as trusted roots (by default).

+ +
The following example loads a certificate from the file system + and adds it as a trusted anchor. + + import flash.utils.ByteArray; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + var certificate:ByteArray = new ByteArray(); + + var certFile:File = new File("certificate.cer"); + var certFileStream:FileStream = new FileStream(); + certFileStream.open(certFile, FileMode.READ); + certFileStream.readBytes(certificate, 0, certFileStream.bytesAvailable); + + verifier.addCertificate(certificate, true); +
verify + Verifies the specified signature.If called while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationErrorIf other errors are encountered, such as non-well-formed XML or + unsupported elements in the signature file. + ErrorErrorsignatureXMLThe XML signature to verify. + + Verifies the specified signature. + +

Verification is asynchronous. The XMLSignatureValidator object dispatches + a complete event when verification completes successfully or + an error event if verification cannot complete because of errors.

+ +

The verification process cannot be cancelled. While a verification process is under way, + subsequent calls to the verify() method fail. After the current verification + check is complete, you can call the verify() method again.

+ +

Note: Because the XMLSignatureValidator only implements a subset of the + W3C recommendation for XML Signature Syntax and Processing, not all valid + XML signatures can be verified.

+ + +
The following example reads a file containing an XML signature and validates it by + calling the verify() method. + (The example assumes that the IURIDereferencer implementation is appropriate for the signature.) + +import flash.filesystem.File; +import flash.filesystem.FileStream; +import com.example.SignedMessageDereferencer; //Your IURIDereferencer implementation + +const xmlSignatureNS:Namespace = new Namespace( "http://www.w3.org/2000/09/xmldsig#" ); + +var verifier:XMLSignatureValidator = new XMLSignatureValidator(); +verifier.uriDereferencer = new SignedMessageDereferencer(); + +var signatureFile:File = new File( "path/to/XMLSignatureDocument.xml" ); +var sigFileStream:FileStream = new FileStream(); +sigFileStream.open( signatureFile, FileMode.READ ); + +var xmlDoc:XML = XML( sigFileStream.readUTFBytes(sigFileStream.bytesAvailable) ); +var xmlSig:XML = XML( xmlDoc..xmlSignatureNS::Signature ); + +verifier.verify( xmlSig ); +
completeflash.events:EventDispatched when verification completes successfully. + Dispatched when verification completes successfully.errorflash.events:ErrorEventDispatched if the verification of references encounters an error. + Dispatched if the verification of references encounters an error.
digestStatus + The validity status of the cryptographic signature computed over the + signature SignedInfo element.StringIf accessed while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationError + The validity status of the cryptographic signature computed over the + signature SignedInfo element. + +

The status is:

+
  • valid — If signature is cryptographically valid.
  • invalid — If the digest has been altered after signing.
  • unknown — If the verify() method has not + been called.
+ +

Note: If the digestStatus is invalid, the identityStatus + and referencesStatus are not checked and will be reported as unknown.

+ +
identityStatus + The validity status of the signing certificate.StringIf accessed while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationError + The validity status of the signing certificate. + +

The status can be:

+
  • valid — The certificate has not expired, has not failed a revocation check and chains + to a trusted root certificate.
  • unknown — The certificate has not expired and has not failed a revocation check, + but does not chain to a trusted root certificate. A status of unknown will also + be reported when the status has not been verified, either because the verify() method has not + been called or because the cryptographic signature of the SignedInfo element (digestStatus) + is invalid.
  • invalid — The certificate has expired or fails a revocation check.
+

The certificates added using the addCertificate() method + and the settings of the revocationCheckSetting and the useSystemTrustStore + properties can change whether a certificate is considered valid.

+ +

Note: If the identityStatus is invalid, the referencesStatus is not checked + and will be reported as unknown. In addition, references are not checked when the identityStatus + is unknown unless the referencesValidationSetting is validOrUnknownIdentity

+ +
The following example gets the result of validating the signing certificate + (after a signature has been validated): + + import flash.security.XMLSignatureValidator; + + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var identityResult:String = verifier.identityStatus; +
addCertificate()revocationCheckSettinguseSystemTrustStorereferencesValidationSetting
isSupported + The isSupported property is set to true if the + XMLSignatureValidator class is supported on the current platform, otherwise it is + set to false.BooleanReports whether the XMLSignatureValidation class is supported on the client system. + + + The isSupported property is set to true if the + XMLSignatureValidator class is supported on the current platform, otherwise it is + set to false. + + referencesStatus + The validity status of the data in the references in the signature SignedInfo + element.StringIf accessed while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationError + The validity status of the data in the references in the signature SignedInfo + element. + +

The status can be:

+
  • valid — If all references are valid.
  • invalid — If any reference is invalid.
  • unknown — If not verified. + References can remain unverified in the following circumstances: +
    • the verify() method has not been called
    • the cryptographic signature of the SignedInfo element (digestStatus) is invalid.
    • the signing certificate (identityStatus) is invalid
    • referencesValidationSetting is validIdentity (which is the default setting) and + the identityStatus of the signing certificate is unknown.
    • the referencesValidationSetting is never.
    +
+ +

Important: External resources are not validated unless they are referenced directly + in a SignedInfo element within the signature document. External resources referred to by a secondary + reference are not validated. For example, if an XML signature signs a manifest element, only + the integrity of the manifest element itself is verified. The files listed in the manifest are not + checked.

+ +
The following example gets the result of validating the references in the signature + (after a signature has been validated): + + import flash.security.XMLSignatureValidator; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var dataResult:String = verifier.referencesStatus; +
referencesValidationSetting
referencesValidationSetting + Specifies the conditions under which references are checked.StringIf set while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationErrorif the setting parameter contains a value not defined in the ReferencesValidationSetting class. + + ArgumentErrorArgumentError + Specifies the conditions under which references are checked. + +

Use constants defined in the ReferencesValidationSetting class to set this property. The + settings include:

+
  • ReferencesValidationSetting.VALID_IDENTITY — Check references only + if the signing certificate is valid and chains to a trusted root. This is the default setting.
  • ReferencesValidationSetting.VALID_OR_UNKNOWN_IDENTITY — Check references + if the signing certificate is valid, even if it does not chain to a trusted root.
  • ReferencesValidationSetting.NEVER — Never check references.
+ +

+ Use the default, validIdentity, setting with signatures signed with a commercial certificate or when you + supply your own certificate as a trust anchor with the addCertificate() method. This + setting avoids the overhead of checking reference validity when the signed document will be rejected anyway. +

+

+ Use the validOrUnknownIdentity setting with signatures signed with self-signed certificates. This setting allows you to + validate that the signed data has not been altered, but does not provide any assurances about the identity + of the signer. +

+

+ Use the never setting to avoid the overhead of validating references when such validation is not important in the + context of your application. +

+
The following example sets the XMLSignatureValidator object to check references only + if the signing certificate chains to a trust anchor: + + import flash.security.ReferencesValidationSetting; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + verifier.referencesValidationSetting = ReferencesValidationSetting.VALID_OR_UNKNOWN_IDENTITY; +
ReferencesValidationSetting
revocationCheckSetting + Specifies how certificate revocation is checked.StringIf set while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies how certificate revocation is checked. + +

Use constants defined in the RevocationSettings class to set this property. The + settings include:

+
  • RevocationCheckSettings.NEVER — Do not check certificate revocation.
  • RevocationCheckSettings.BEST_EFFORT — Check certificate revocation, + if revocation information is available and the revocation status can be obtained. + If revocation status cannot be positively determined, the certificate is not rejected.
  • RevocationCheckSettings.REQUIRED_IF_AVAILABLE — If the certificate includes + revocation information, the revocation status must be positively determined to validate + the certificate.
  • RevocationCheckSettings.ALWAYS_REQUIRED — Always check certificate revocation. + Certificates without revocation information are rejected.
+ +
RevocationCheckSettings
signerCN + The Common Name field of the signing certificate.String + The Common Name field of the signing certificate. + + The following example reads the common name of the signing certificate + (after a signature has been validated): + + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var commonName:String = verifier.signerCN; +signerDN + The Distinguished Name field of the signing certificate.String + The Distinguished Name field of the signing certificate. + + The following example reads the distinguished name of the signing certificate + (after a signature has been validated): + + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var distinguishedName:String = verifier.signerDN; +signerExtendedKeyUsages + An array containing the Extended Key Usages OIDs listed in the signing certificate.ArrayIf accessed while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationError + An array containing the Extended Key Usages OIDs listed in the signing certificate. + +

Each extended key usage is reported in numeric OID form.

+ +
The following example reads the extended key OIDs of the signing certificate + (after a signature has been validated): + + import flash.security.XMLSignatureValidator; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var extendedKeyOIDs:Array = verifier.signerExtendedKeyUsages; +
signerTrustSettings + An array containing the trust settings of the signing certificate.ArrayIf accessed while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationError + An array containing the trust settings of the signing certificate. + +

Trust settings are derived from the system and the key usage OIDs embedded in + the certificate. Constants for the strings representing the recognized trust settings + are defined in the SignerTrustSettings class.

+ +

The signerTrustSettings array of an unknown or + invalid certificate is empty.

+ +

Modifying the array does not change the certificate trust settings.

+ +
The following example reads the trust settings of the signing certificate + (after a signature has been validated): + + import flash.security.XMLSignatureValidator; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate a signature... + + var certificateTrustedFor:Array = verifier.signerTrustSettings; +
SignerTrustSettings
uriDereferencer + The IURIDereferencer implementation.flash.security:IURIDereferencerIf set while a signature is being validated. + IllegalOperationErrorflash.errors:IllegalOperationError + The IURIDereferencer implementation. + +

An IURIDereferencer implementation must be provided before attempting to + verify a signature.

+ +
The following example creates an instance of SignedMessageDereferencer, which implements + the IURIDereferencer interface, and sets it as the dereferencer to use for signature validation: + + import com.example.SignedMessageDereferencer; //A custom class implementing IURIDereferencer + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + verifier.uriDereferencer = new SignedMessageDereferencer(); +
IURIDereferencer
useSystemTrustStore + Specifies that certificates in the system trust store are used for chain building.BooleanIf set while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies that certificates in the system trust store are used for chain building. + +

If true, then the trust anchors in the system trust store + are used as trusted roots. The system trust store is not used by default.

+ +
The following example creates an XMLSignatureValidator instance and sets it to use the + system repository of trusted certificates when validating an XML signature: + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + verifier.useSystemTrustStore = true; +
validityStatus + The validity status of a verified XML signature.StringIf accessed while a signature is being validated. + + IllegalOperationErrorflash.errors:IllegalOperationError + The validity status of a verified XML signature. + +

The XML signature is verified by validating the the cryptographic signature of the SignedInfo element, + the signing certificate, and the data addressed by the references in the SignedInfo element. + The validity of each of these elements is reported individually by the digestStatus, + identityStatus(), and referencesStatus properties, respectively.

+ +

The validity of an XML signature can be valid, invalid, or unknown. The overall + status depends on the verification status of the individual components of the signature file:

+
  • digestStatus — The validity of the cryptographic signature computed over + the SignedInfo element.
  • identityStatus — The validity of the signing certificate.
  • referencesStatus — The validity of the digest of the references in the + signature SignedInfo element.
+

The signature validity reported by the validityStatus property can be:

+
  • valid — If referencesStatus, digestStatus, and + identityStatus are all valid.
  • invalid — If any individual status is invalid.
  • unknown — If any individual status is unknown.
+ +
The following example gets the result of validating the XML signature + + import flash.security.XMLSignatureValidator; + + var verifier:XMLSignatureValidator = new XMLSignatureValidator(); + //validate the signature... + + var validationResult:String = verifier.validityStatus; +
digestStatusidentityStatusreferencesStatusSignatureStatus
IURIDereferencer + IURIDereferencer defines an interface for objects that resolve + URIs in an XML signature. + IURIDereferencer defines an interface for objects that resolve + URIs in an XML signature. + +

The IURIDereferencer implementation is responsible for resolving the + URIs specified in the SignedInfo elements of an XML signature file and + returning the referenced data in an object, such as a ByteArray, that implements + the IDataInput interface.

+ +

The interface has one method: dereference(). + A typical implementation might also require a method for passing + the XML signature object containing the URIs to be resolved to + the dereferencer.

+ +

The IURIDereferencer interface is used with the + XMLSignatureValidator class.

+ +
XMLSignatureValidatorXMLSignatureValidator.uriDereferencerdereference + Resolves and dereferences the specified URI.The data referenced by the URI. + flash.utils:IDataInputuriStringThe URI to dereference. + + Resolves and dereferences the specified URI. + +
SignerTrustSettings + The SignerTrustSettings class defines constants used with the + signerTrustSettings property of an XMLSignatureValidator object.Object + The SignerTrustSettings class defines constants used with the + signerTrustSettings property of an XMLSignatureValidator object. + + XMLSignatureValidator.signerTrustSettingsCODE_SIGNING + The certificate is trusted for code signing.codeSigningString + The certificate is trusted for code signing. This implies that + the certificate chains to a trusted root, the root is trusted for + code signing, and the signing certificate has the CodeSigning + OID in its Extended Key Usage extension. + + PLAYLIST_SIGNING + The certificate is trusted for signing playlists.playlistSigningString + The certificate is trusted for signing playlists. This implies that + the certificate chains to a trusted root and has the + playlist signing OID in its Extended Key Usage extension. + + SIGNING + The certificate is trusted for signing in general.signingString + The certificate is trusted for signing in general. + + SignatureStatus + The SignatureStatus class defines constants used by the validityStatus + property of an XMLSignatureValidator object.Object + The SignatureStatus class defines constants used by the validityStatus + property of an XMLSignatureValidator object. + + XMLSignatureValidator.validityStatusINVALID + Invalid status.invalidString + Invalid status. + + UNKNOWN + Unknown status.unknownString + Unknown status. + + VALID + Valid status.validString + Valid status. + + ReferencesValidationSetting + The ReferencesValidationSetting class defines constants used by the referencesValidationSetting + property of an XMLSignatureValidator object.Defines constants for the supported modes for validating referenced data in an XML signature. + + Object + The ReferencesValidationSetting class defines constants used by the referencesValidationSetting + property of an XMLSignatureValidator object. + + XMLSignatureValidator.ReferencesValidationSettingNEVER + Never check references.neverString + Never check references. + + VALID_IDENTITY + Only check references if the signing certificate is valid and trusted.validIdentityString + Only check references if the signing certificate is valid and trusted. + + VALID_OR_UNKNOWN_IDENTITY + Check references even if the signing certificate is untrusted (does not chain to a known trusted root).validOrUnknownIdentityString + Check references even if the signing certificate is untrusted (does not chain to a known trusted root). + + RevocationCheckSettings + The RevocationCheckSettings class defines constants used by the + revocationCheckSetting property of an XMLSignatureValidator object.Object + The RevocationCheckSettings class defines constants used by the + revocationCheckSetting property of an XMLSignatureValidator object. + + XMLSignatureValidator.revocationCheckSettingALWAYS_REQUIRED + Always check certificate revocation.alwaysRequiredString + Always check certificate revocation. Certificates without revocation information are rejected. + + BEST_EFFORT + Check certificate revocation, if revocation information is available and the revocation status + can be obtained.bestEffortString + Check certificate revocation, if revocation information is available and the revocation status + can be obtained. If revocation status cannot be positively determined, the certificate is not rejected. + NEVER + Do not check certificate revocation.neverString + Do not check certificate revocation. + + REQUIRED_IF_AVAILABLE + Check certificate revocation if the certificate includes revocation information.requiredIfInfoAvailableString + Check certificate revocation if the certificate includes revocation information. If the information + is available, but revocation status cannot be positively determined, the certificate is rejected. + + CertificateStatus + The CertificateStatus class defines constants used to report the + results of certificate validation processing by a SecureSocket object.Object + The CertificateStatus class defines constants used to report the + results of certificate validation processing by a SecureSocket object. + + SecureSocket.serverCertificateStatusEXPIRED + The certificate is outside its valid period.expiredString + The certificate is outside its valid period. + +

Indicates that certificate validation processing + was attempted, but failed because the validity period of the certificate is either before or + after the current date. On some operating systems, the notYetValid status is reported + when the current date is before the validity period of the cerificate. On other operating systems, + the expired status is reported in both cases.

+ +
INVALID_CHAIN + A root or intermediate certificate in this certificate's chain is invalid.invalidChainString + A root or intermediate certificate in this certificate's chain is invalid. + +

Indicates that certificate validation processing + was attempted, but failed because the certificate's trust chain was + invalid.

+ +
INVALID + An invalid certificate.invalidString + An invalid certificate. + +

Indicates that certificate validation processing + was attempted, but failed. This is the generic faliure status that + is reported when a more specific certificate status cannot be + determined.

+ +
NOT_YET_VALID + The certificate is not yet valid.notYetValidString + The certificate is not yet valid. + +

Indicates that a certificate is not yet valid. + The current date is before the notBefore date/time of the certificate

+ +
PRINCIPAL_MISMATCH + The certificate common name does not match the expected host name.principalMismatchString + The certificate common name does not match the expected host name. + +

Indicates that certificate validation + processing was attempted, but failed because the certificate's + common name does not match the fully qualified domain name of the host.

+ +
REVOKED + The certificate has been revoked.revokedString + The certificate has been revoked. + +

Indicates that certificate validation processing + was attempted, but failed because the certificate has been revoked. On + some operating systems, the revoked status is also reported + when the certificate (or its root certificate) has been added to the + list of untrusted certificates on the client computer.

+ +
TRUSTED + A valid, trusted certificate.trustedString + A valid, trusted certificate. + +

Indicates that a certificate has not expired, has not + failed a revocation check, and chains to a trusted root certificate.

+ +
UNKNOWN + The validity of the certificate is not known.unknownString + The validity of the certificate is not known. + +

Indicates that certificate validation processing + has not been performed yet on a certificate.

+ +
UNTRUSTED_SIGNERS + The certificate does not chain to a trusted root certificate.untrustedSignersString + The certificate does not chain to a trusted root certificate. + +

Indicates that certificate validation + processing was attempted, but that the certificate does not chain + to any of the root certificates in the client trust store. On + some operating systems, the untrustedSigners is also + reported if the certificate is in the list of untrusted certificates + on the client computer.

+ +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.sensors.xml b/language-server/playerglobal_docs/flash.sensors.xml new file mode 100644 index 0000000..6c95892 --- /dev/null +++ b/language-server/playerglobal_docs/flash.sensors.xml @@ -0,0 +1,344 @@ +flash.sensorsAccelerometer + + The Accelerometer class dispatches events based on activity detected by the device's motion sensor.Accelerometer class + + flash.events:EventDispatcher + The Accelerometer class dispatches events based on activity detected by the device's motion sensor. + This data represents the device's location or + movement along a 3-dimensional axis. When the device moves, the sensor detects this movement and + returns acceleration data. The Accelerometer class provides methods to query whether or not + accelerometer is supported, and also to set the rate at which acceleration events are dispatched. +

Note: Use the Accelerometer.isSupported property to test the runtime environment for the ability + to use this feature. While the Accelerometer class and its members are accessible to the Runtime Versions listed for + each API entry, the current environment for the runtime determines the availability of this feature. For example, you can + compile code using the Accelerometer class properties for Flash Player 10.1, but you need to use the Accelerometer.isSupported + property to test for the availability of the Accelerometer feature in the current deployment environment for the Flash Player runtime. If + Accelerometer.isSupported is true at runtime, then Accelerometer support currently exists.

+ +

AIR profile support: This feature is supported + only on mobile devices. It is not supported on desktop or AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles. +

+ +
In the following example, the application moves a Sprite + based on accelerometer update events. The accelerometer + update events indicate movement of the device. + +package +{ + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.Event; + import flash.events.AccelerometerEvent; + import flash.sensors.Accelerometer; + + public class AccelerometerTest extends Sprite + { + private var ball:Sprite; + private var accelerometer:Accelerometer; + private var xSpeed:Number = 0; + private var ySpeed:Number = 0; + private const RADIUS = 20; + + public final function AccelerometerTest() + { + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + + createBall(); + + if (Accelerometer.isSupported) + { + accelerometer = new Accelerometer(); + accelerometer.addEventListener(AccelerometerEvent.UPDATE, accUpdateHandler); + stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler); + } + } + + private final function createBall():void + { + ball = new Sprite(); + ball.graphics.beginFill(0xFF0000); + ball.graphics.drawCircle(0, 0, RADIUS); + ball.cacheAsBitmap = true; + ball.x = stage.stageWidth / 2; + ball.y = stage.stageHeight / 2; + addChild(ball); + } + + private final function enterFrameHandler(event:Event):void + { + event.stopPropagation(); + moveBall(); + } + private final function moveBall():void + { + var newX:Number = ball.x + xSpeed; + var newY:Number = ball.y + ySpeed; + if (newX < 20) + { + ball.x = RADIUS; + xSpeed = 0; + } + else if (newX > stage.stageWidth - RADIUS) + { + ball.x = stage.stageWidth - RADIUS; + xSpeed = 0; + } + else + { + ball.x += xSpeed; + } + + if (newY < RADIUS) + { + ball.y = RADIUS; + ySpeed = 0; + } + else if (newY > stage.stageHeight - RADIUS) + { + ball.y = stage.stageHeight - RADIUS; + ySpeed = 0; + } + else + { + ball.y += ySpeed; + } + } + + private final function accUpdateHandler(event:AccelerometerEvent):void + { + xSpeed -= event.accelerationX * 2; + ySpeed += event.accelerationY * 2; + } + } +} +
isSupportedflash.events.AccelerometerEventMichael Chaize: AIR and the AccelerometerMichael Chaize: Become an AIR Pilotstatus + Dispatched when an accelerometer changes its status.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when an accelerometer changes its status. + +

Note: On some devices, the accelerometer is always available. + On such devices, an Accelerometer object never dispatches a status + event.

+ +
update + The update event is dispatched in response to updates from the accelerometer sensor.flash.events.AccelerometerEvent.UPDATEflash.events.AccelerometerEvent + The update event is dispatched in response to updates from the accelerometer sensor. + The event is dispatched in the following circumstances: + +

  • When a new listener function is attached through addEventListener(), this event is + delivered once to all the registered listeners for providing the current value of the accelerometer.
  • Whenever accelerometer updates are obtained from the platform at device determined intervals.
  • Whenever the application misses a change in the accelerometer (for example, the runtime + is resuming after being idle).

+ +
Accelerometer + Creates a new Accelerometer instance. + Creates a new Accelerometer instance. + + setRequestedUpdateInterval + The setRequestedUpdateInterval method is used to set the desired time interval + for updates.The specified interval is less than zero. + + ArgumentErrorArgumentErrorintervalNumberThe requested update interval. If interval is set to 0, then the minimum supported update interval is used. + + + + The setRequestedUpdateInterval method is used to set the desired time interval + for updates. The time interval is measured in milliseconds. The update interval is only used as a + hint to conserve the battery power. The actual time between acceleration updates may be greater + or lesser than this value. Any change in the update interval affects all registered listeners. + You can use the Accelerometer class without calling the setRequestedUpdateInterval() + method. In this case, the application receives updates based on the device's default interval. + + isSupported + The isSupported property is set to true if the accelerometer sensor is + available on the device, otherwise it is set to false.Boolean + The isSupported property is set to true if the accelerometer sensor is + available on the device, otherwise it is set to false. + + The following example uses the Accelerometer.isSupported property to test for Accelerometer support at runtime. + If the current environment supports the Accelerometer feature, then an event listener is added to the Accelerometer object, and the associated handler + populates the text field with the timestamp and acceleration values. Otherwise, the text field indicates that the feature is not supported in the current + environment. + +var myTextField:TextField = new TextField(); +myTextField.width = 200; +addChild(myTextField); +var acc1:Accelerometer = new Accelerometer(); +var isSupported:Boolean = Accelerometer.isSupported; +checksupport(); + +function checksupport():void { + if (isSupported) { + myTextField.text = "Accelerometer feature supported"; + acc1.addEventListener(AccelerometerEvent.UPDATE, updateHandler); + } else { + myTextField.text = "Accelerometer feature not supported"; + } +} + +function updateHandler(evt:AccelerometerEvent):void { + myTextField.text = String("at: " + evt.timestamp + "\n" + "acceleration X: " + evt.accelerationX + "\n" + "acceleration Y: " + evt.accelerationY + "\n" + "acceleration Z: " + evt.accelerationZ); + +} +muted + Specifies whether the user has denied access to the accelerometer (true) + or allowed access (false).Boolean + Specifies whether the user has denied access to the accelerometer (true) + or allowed access (false). When this value changes, + a status event is dispatched. + + status
Geolocation + The Geolocation class dispatches events in response to the device's location sensor.flash.events:EventDispatcher + The Geolocation class dispatches events in response to the device's location sensor. + +

If a device supports geolocation, you can use this class to obtain the current geographical + location of the device. The geographical location is displayed on the device in the form of latitudinal + and longitudinal coordinates (in WGS-84 standard format). When the location of the device changes, + you can receive updates about the changes. If the device supports this feature, you will be able to obtain + information about the altitude, accuracy, heading, speed, and timestamp of the latest change in the location.

+ +

AIR profile support: This feature is supported + only on mobile devices. It is not supported on desktop or AIR for TV devices. You can test + for support at run time using the Geolocation.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles. +

+ +
In the following example, the application displays the latitude, + longitude, and horizontal accuracy of geolocation update events + as they are received. + +package +{ + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.GeolocationEvent; + import flash.sensors.Geolocation; + import flash.text.TextField; + import flash.text.TextFormat; + + public class GeolocationTest extends Sprite + { + private var geo:Geolocation; + private var log:TextField; + + public function GeolocationTest() + { + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + setUpTextField(); + + if (Geolocation.isSupported) + { + geo = new Geolocation(); + geo.setRequestedUpdateInterval(100); + geo.addEventListener(GeolocationEvent.UPDATE, geolocationUpdateHandler); + } + else + { + log.text = "No geolocation support."; + } + } + + private function geolocationUpdateHandler(event:GeolocationEvent):void + { + log.text = "latitude:" + event.latitude.toString() + "°\n"; + log.appendText("longitude:" + event.longitude.toString() + "°\n"); + log.appendText("horizontal accuracy:" + event.horizontalAccuracy.toString() + " m"); + } + private function setUpTextField():void + { + log = new TextField(); + var format:TextFormat = new TextFormat("_sans", 24); + log.defaultTextFormat = format; + log.border = true; + log.wordWrap = true; + log.multiline = true; + log.x = 10; + log.y = 10; + log.height = stage.stageHeight - 20; + log.width = stage.stageWidth - 20; + addChild(log); + } + } +} +
Cristophe Coenraets: Mulit-user Google Maps Collaborationstatus + The Geolocation object dispatches status events when the user changes access + to the location sensor.flash.events.StatusEvent.STATUSflash.events.StatusEvent + The Geolocation object dispatches status events when the user changes access + to the location sensor. For example, if, in response to a device prompt, the user prevents the + application from accessing location data, the Geolcation object dispatches a status + event. When the status changes to a state where the location sensor is not available, the + muted property of the Geolocation instance is true. + + mutedupdate + The update event is dispatched in response to updates from the location sensor.flash.events.GeolocationEvent.UPDATEflash.events.GeolocationEvent + The update event is dispatched in response to updates from the location sensor. The event + is dispatched under the following circumstances: + +

  • When a new listener function is attached through addEventListener(), this event is + delivered once to all the registered listeners to provide the current value of the location.
  • Whenever location updates are obtained from the platform at device determined intervals.
  • Whenever the application misses a change in the location (for example, the application is waking up + after being asleep).

+ +

Note: First-generation iPhones, which do not include a GPS unit, dispatch + update events only occasionally. On these devices, a Geolocation object initially + dispatches one or two update events. It then dispatches update events + when information changes noticeably.

+ +
Geolocation + Creates a new Geolocation instance. + Creates a new Geolocation instance. + + setRequestedUpdateInterval + Used to set the time interval for updates, in milliseconds.The specified interval is less than zero. + + ArgumentErrorArgumentErrorintervalNumberrequested update interval. If interval <= 0, then any call to this method + has no effect. + + + Used to set the time interval for updates, in milliseconds. The update interval is only used as a + hint to conserve the battery power. The actual time between location updates may be greater or + lesser than this value.Any change in the update interval using this method + affects all registered update event listeners. The Geolocation class + can be used without calling the setRequestedUpdateInterval method. + In this case, the platform will return updates based on its default interval. + +

Note: First-generation iPhones, which do not include a GPS unit, dispatch + update events only occasionally. On these devices, a Geolocation object initially + dispatches one or two update events. It then dispatches update events + when information changes noticeably.

+ +
isSupported + Whether a location sensor is available on the device (true); otherwise false.Boolean + Whether a location sensor is available on the device (true); otherwise false. + + muted + Specifies whether the user has denied access to the geolocation (true) + or allowed access (false).Boolean + Specifies whether the user has denied access to the geolocation (true) + or allowed access (false). When this value changes, + a status event is dispatched. + + status
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.system.xml b/language-server/playerglobal_docs/flash.system.xml new file mode 100644 index 0000000..a03903a --- /dev/null +++ b/language-server/playerglobal_docs/flash.system.xml @@ -0,0 +1,2804 @@ +flash.systemImageDecodingPolicy + + The ImageDecodingPolicy class defines values for the imageDecodingPolicy property + of the LoaderContext class.The ImageDecodingPolicy class defines values for the imageDecodingPolicy property + of the LoaderContext class. + + Object + The ImageDecodingPolicy class defines values for the imageDecodingPolicy property + of the LoaderContext class. + + LoaderContext.imageDecodingPolicyON_DEMAND + Specifies that the image being loaded will not be decoded until needed.onDemandString + Specifies that the image being loaded will not be decoded until needed. + + ON_LOAD + Specifies that the image will be decoded when it is loaded, before the + complete event is sent.onLoadString + Specifies that the image will be decoded when it is loaded, before the + complete event is sent. + + SystemUpdaterType + The SystemUpdaterType class provides constants for a system update.Object + The SystemUpdaterType class provides constants for a system update. These constants + are used in the SystemUpdater.update() function. + +

Note: The SystemUpdater API is supported on desktop platforms.

+
DRM + Updates the DRM module.drmString + Updates the DRM module. + SYSTEM + Updates the player runtime itself.systemString + Updates the player runtime itself. +
IMEConversionMode + This class contains constants for use with the IME.conversionMode + property.Object + This class contains constants for use with the IME.conversionMode + property. Setting conversionMode to either + ALPHANUMERIC_FULL or JAPANESE_KATAKANA_FULL causes the + player to use a full width font, whereas using ALPHANUMERIC_HALF or + JAPANESE_KATAKANA_HALF uses a half width font. + flash.system.IME.conversionModeALPHANUMERIC_FULL + The string "ALPHANUMERIC_FULL", for use with the + IME.conversionMode property.ALPHANUMERIC_FULLString + The string "ALPHANUMERIC_FULL", for use with the + IME.conversionMode property. + This constant is used with all IMEs. + Use the syntax IMEConversionMode.ALPHANUMERIC_FULL. + + flash.system.IME.conversionModeALPHANUMERIC_HALF + The string "ALPHANUMERIC_HALF", for use with the + IME.conversionMode property.ALPHANUMERIC_HALFString + The string "ALPHANUMERIC_HALF", for use with the + IME.conversionMode property. + This constant is used with all IMEs. + Use the syntax IMEConversionMode.ALPHANUMERIC_HALF. + + flash.system.IME.conversionModeCHINESE + The string "CHINESE", for use with the + IME.conversionMode property.CHINESEString + The string "CHINESE", for use with the + IME.conversionMode property. + This constant is used with simplified and traditional Chinese IMEs. + Use the syntax IMEConversionMode.CHINESE. + + flash.system.IME.conversionModeJAPANESE_HIRAGANA + The string "JAPANESE_HIRAGANA", for use with the + IME.conversionMode property.JAPANESE_HIRAGANAString + The string "JAPANESE_HIRAGANA", for use with the + IME.conversionMode property. + This constant is used with Japanese IMEs. + Use the syntax IMEConversionMode.JAPANESE_HIRAGANA. + + flash.system.IME.conversionModeJAPANESE_KATAKANA_FULL + The string "JAPANESE_KATAKANA_FULL", for use with the + IME.conversionMode property.JAPANESE_KATAKANA_FULLString + The string "JAPANESE_KATAKANA_FULL", for use with the + IME.conversionMode property. + This constant is used with Japanese IMEs. + Use the syntax IMEConversionMode.JAPANESE_KATAKANA_FULL. + + flash.system.IME.conversionModeJAPANESE_KATAKANA_HALF + The string "JAPANESE_KATAKANA_HALF", for use with the + IME.conversionMode property.JAPANESE_KATAKANA_HALFString + The string "JAPANESE_KATAKANA_HALF", for use with the + IME.conversionMode property. + This constant is used with Japanese IMEs. + Use the syntax IMEConversionMode.JAPANESE_KATAKANA_HALF. + + flash.system.IME.conversionModeKOREAN + The string "KOREAN", for use with the + IME.conversionMode property.KOREANString + The string "KOREAN", for use with the + IME.conversionMode property. + This constant is used with Korean IMEs. + Use the syntax IMEConversionMode.KOREAN. + + flash.system.IME.conversionModeUNKNOWN + The string "UNKNOWN", which can be returned by a call to + the IME.conversionMode property.UNKNOWNString + The string "UNKNOWN", which can be returned by a call to + the IME.conversionMode property. This value cannot be set, + and is returned only if the player is unable to identify the currently + active IME. + Use the syntax IMEConversionMode.UNKNOWN. + + flash.system.IME.conversionModeSecurityPanel + The SecurityPanel class provides values for specifying + which Security Settings panel you want to display.Object + The SecurityPanel class provides values for specifying + which Security Settings panel you want to display. + +

This class contains static constants that are used with the + Security.showSettings() method. You cannot create new instances + of the SecurityPanel class.

+ +
The following example shows how a click event on a Sprite object can be + used to show the Local Storage Settings panel of the Flash Player Settings. An orange box is added to the + stage using draw(). In draw(), a click event listener is + added named clickHandler(), which responds to click events by directing + Flash Player to open its Local Storage Settings panel. + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.*; + import flash.system.Security; + import flash.system.SecurityPanel; + + public class SecurityExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 100; + + public function SecurityExample() { + draw(); + } + + private function draw():void { + var child:Sprite = new Sprite(); + child.graphics.beginFill(bgColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + child.buttonMode = true; + + var label:TextField = new TextField(); + label.text = "settings"; + label.selectable = false; + label.mouseEnabled = false; + child.addChild(label); + + child.addEventListener(MouseEvent.CLICK, clickHandler); + addChild(child); + } + + private function clickHandler(event:MouseEvent):void { + Security.showSettings(SecurityPanel.LOCAL_STORAGE); + } + } +} +
CAMERA + When passed to Security.showSettings(), displays the + Camera panel in Flash Player Settings.cameraString + When passed to Security.showSettings(), displays the + Camera panel in Flash Player Settings. + + Security.showSettings()DEFAULT + When passed to Security.showSettings(), displays the panel + that was open the last time the user closed the Flash Player Settings.defaultString + When passed to Security.showSettings(), displays the panel + that was open the last time the user closed the Flash Player Settings. + + Security.showSettings()DISPLAY + When passed to Security.showSettings(), displays the + Display panel in Flash Player Settings.displayString + When passed to Security.showSettings(), displays the + Display panel in Flash Player Settings. + + Security.showSettings()LOCAL_STORAGE + When passed to Security.showSettings(), displays the + Local Storage Settings panel in Flash Player Settings.localStorageString + When passed to Security.showSettings(), displays the + Local Storage Settings panel in Flash Player Settings. + + Security.showSettings()MICROPHONE + When passed to Security.showSettings(), displays the + Microphone panel in Flash Player Settings.microphoneString + When passed to Security.showSettings(), displays the + Microphone panel in Flash Player Settings. + + Security.showSettings()PRIVACY + When passed to Security.showSettings(), displays the + Privacy Settings panel in Flash Player Settings.privacyString + When passed to Security.showSettings(), displays the + Privacy Settings panel in Flash Player Settings. + + Security.showSettings()SETTINGS_MANAGER + When passed to Security.showSettings(), displays the + Settings Manager (in a separate browser window).settingsManagerString + When passed to Security.showSettings(), displays the + Settings Manager (in a separate browser window). + + Security.showSettings()
TouchscreenType + The TouchscreenType class is an enumeration class that provides values for the different types of touch screens.Object + The TouchscreenType class is an enumeration class that provides values for the different types of touch screens. + +

Use the values defined by the TouchscreenType class with the Capabilities.touchscreenType + property.

+ +
The following example is a simple test that indicates the current state of the "Num Lock" and "Caps Lock" keys + as well as the type of keybaord and touch screen type in the running environment. When testing this example, click the + text field to see the property values: + +import flash.events.~~; +import flash.display.~~; +import flash.ui.Keyboard; +import flash.system.Capabilities; +import flash.text.TextField; + + +var keyboardInfoTxt:TextField = new TextField(); +keyboardInfoTxt.x = 30; +keyboardInfoTxt.y = 50; +keyboardInfoTxt.width = 300; +keyboardInfoTxt.height = 100; +keyboardInfoTxt.border = true; + +addChild(keyboardInfoTxt); + +addEventListener (MouseEvent.CLICK, getScreenKeyboardType); + +function getScreenKeyboardType(e:MouseEvent):void{ + keyboardInfoTxt.text= "Caps Lock is : " + String(flash.ui.Keyboard.capsLock)+ "\n" + + "Num Lock is : " + String(flash.ui.Keyboard.numLock) +"\n" + + "Has Virtual Keyboard : " + String(flash.ui.Keyboard.hasVirtualKeyboard) + "\n" + + "Physical Keyboard Type : " + flash.ui.Keyboard.physicalKeyboardType + "\n" + + "flash.system.Capabilities.touchscreenType is : " + flash.system.Capabilities.touchscreenType; +} +
Capabilities.touchscreenTypeflash.ui.Mouse.supportsCursorFINGER + A touchscreen designed to respond to finger touches.fingerString + A touchscreen designed to respond to finger touches. + + NONE + The computer or device does not have a supported touchscreen.noneString + The computer or device does not have a supported touchscreen. + + STYLUS + A touchscreen designed for use with a stylus.stylusString + A touchscreen designed for use with a stylus. + +
ApplicationDomain + The ApplicationDomain class is a container for discrete groups of class definitions.Object + The ApplicationDomain class is a container for discrete groups of class definitions. + Application domains are used to partition classes that are in the same security domain. + They allow multiple definitions of the same class to exist and allow children to reuse parent + definitions. + +

Application domains are used when an external SWF file is loaded through the Loader class. + All ActionScript 3.0 definitions in the loaded SWF file are stored in the application + domain, which is specified by the applicationDomain property of the LoaderContext + object that you pass as a context parameter of the Loader object's load() or + loadBytes() method. The LoaderInfo object also contains an + applicationDomain property, which is read-only.

+ +

All code in a SWF file is defined to exist in an application domain. The current application + domain is where your main application runs. The system domain contains all application domains, + including the current domain, which means that it contains all Flash Player classes.

+ +

Every application domain, except the system domain, has an associated parent domain. + The parent domain of your main application's application domain is the system domain. + Loaded classes are defined only when their parent doesn't already define them. + You cannot override a loaded class definition with a newer definition.

+ +

For usage examples of application domains, see the ActionScript 3.0 Developer's Guide.

+ +

The ApplicationDomain() constructor function allows you to create an ApplicationDomain object.

+ +
The following example demonstrates runtime class loading as well as how to call public methods of a class that reside in another SWF. +

Notes:

+
  • Since the ClassLoader class loads a SWF file, local security needs to be at the file system level.
  • To run this example, you must have a swf file called RuntimeClasses.swf existing in the same folder + as the ApplicationDomainExample.swf file.
+ +

Begin by creating the RuntimeClasses.swf file from the following code:

+ + package { + import flash.display.Sprite; + public class RuntimeClasses extends Sprite + { + public function RuntimeClasses() + {} + + public function greet():String { + return("Hello World"); + } + } + } + + +

Then implement the following code:

+ + +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.errors.IllegalOperationError; + import flash.events.Event; + import flash.text.TextField; + + public class ApplicationDomainExample extends Sprite { + private var loader:ClassLoader; + private var tf:TextField = new TextField(); + + public function ApplicationDomainExample() { + addChild(tf); + + loader = new ClassLoader(); + loader.addEventListener(ClassLoader.LOAD_ERROR,loadErrorHandler); + loader.addEventListener(ClassLoader.CLASS_LOADED,classLoadedHandler); + loader.load("RuntimeClasses.swf"); + } + + private function loadErrorHandler(e:Event):void { + tf.text = "Load failed"; + throw new IllegalOperationError("Cannot load the specified file."); + } + + private function classLoadedHandler(e:Event):void { + var runtimeClassRef:Class = loader.getClass("RuntimeClasses"); + var greeter:Object = new runtimeClassRef(); + + tf.text = greeter.greet(); + } + } +} + +import flash.display.Loader; +import flash.errors.IllegalOperationError; +import flash.events.Event; +import flash.events.EventDispatcher; +import flash.events.IOErrorEvent; +import flash.events.SecurityErrorEvent; +import flash.net.URLRequest; +import flash.system.ApplicationDomain; +import flash.system.LoaderContext; + +class ClassLoader extends EventDispatcher { + public static var CLASS_LOADED:String = "classLoaded"; + public static var LOAD_ERROR:String = "loadError"; + private var loader:Loader; + private var swfLib:String; + private var request:URLRequest; + private var loadedClass:Class; + + public function ClassLoader() { + + loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); + loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler); + } + + public function load(lib:String):void { + swfLib = lib; + request = new URLRequest(swfLib); + var context:LoaderContext = new LoaderContext(); + context.applicationDomain=ApplicationDomain.currentDomain; + loader.load(request,context); + } + + public function getClass(className:String):Class { + try { + return loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class; + } catch (e:Error) { + throw new IllegalOperationError(className + " definition not found in " + swfLib); + } + return null; + } + + private function completeHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.CLASS_LOADED)); + } + + private function ioErrorHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.LOAD_ERROR)); + } + + private function securityErrorHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.LOAD_ERROR)); + } +} +
If multiple SWF files contain compiled classes with the same name but provide different implementation, you can partition the classes of externally loaded SWF files separate from the classes of each other following this example. + Previously, the child SWF was instructed to use ApplicationDomain.currentDomain. In this case, a new ApplicationDomain is created, + so that then the properties and methods of the Greeter class of whichever SWF loads second will not replace the properties and methods of the first Greeter class. + You can test this by modifying the context.applicationDomain property in the load method of ClassLoader. +

Notes:

+
  • Since the ClassLoader class loads a SWF file, local security needs to be at the file system level.
  • To run this example, you must have two SWF files called Greeter.swf existing in an "en" and "es" folder respectively.
+ +

Create a Greeter.as file in the "en" directory with the following code:

+ + package { + import flash.display.Sprite; + public class Greeter extends Sprite + { + public function Greeter() + { + } + + public function greet():String { + return("Good Morning"); + } + } + } + +

Then create a very similar Greeter.as file in the "es" directory:

+ + + package { + import flash.display.Sprite; + public class Greeter extends Sprite + { + public function Greeter() + { + } + + public function greet():String { + return("Buenos Dias"); + } + } +} + + +

Compile SWF files for both and then implement the following code:

+ +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.errors.IllegalOperationError; + import flash.events.Event; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class ApplicationDomainExample2 extends Sprite { + private var spanishGreeterLoader:ClassLoader; + private var englishGreeterLoader:ClassLoader; + private var tf:TextField = new TextField(); + private var greetersLoaded:uint = 0; + + public function ApplicationDomainExample2() { + tf.autoSize = TextFieldAutoSize.LEFT; + addChild(tf); + + spanishGreeterLoader = new ClassLoader(); + spanishGreeterLoader.addEventListener(ClassLoader.LOAD_ERROR,loadErrorHandler); + spanishGreeterLoader.addEventListener(ClassLoader.CLASS_LOADED,classLoadedHandler); + spanishGreeterLoader.load("es/Greeter.swf"); + + englishGreeterLoader = new ClassLoader(); + englishGreeterLoader.addEventListener(ClassLoader.LOAD_ERROR,loadErrorHandler); + englishGreeterLoader.addEventListener(ClassLoader.CLASS_LOADED,classLoadedHandler); + englishGreeterLoader.load("en/Greeter.swf"); + } + + private function loadErrorHandler(e:Event):void { + tf.text = "Load failed"; + throw new IllegalOperationError("Cannot load the specified file."); + } + + private function classLoadedHandler(e:Event):void { + greetersLoaded++; + if(greetersLoaded == 2) { + greet(); + } + } + + private function greet():void { + var spanishGreeter:Class = spanishGreeterLoader.getClass("Greeter"); + var englishGreeter:Class = englishGreeterLoader.getClass("Greeter"); + var greeter1 = new spanishGreeter(); + var greeter2 = new englishGreeter(); + + tf.text = greeter1.greet() + "\n" + greeter2.greet(); + } + } +} + +import flash.display.Loader; +import flash.errors.IllegalOperationError; +import flash.events.Event; +import flash.events.EventDispatcher; +import flash.events.IOErrorEvent; +import flash.events.SecurityErrorEvent; +import flash.net.URLRequest; +import flash.system.ApplicationDomain; +import flash.system.LoaderContext; + +class ClassLoader extends EventDispatcher { + public static var CLASS_LOADED:String = "classLoaded"; + public static var LOAD_ERROR:String = "loadError"; + private var loader:Loader; + private var swfLib:String; + private var request:URLRequest; + private var loadedClass:Class; + + public function ClassLoader() { + + loader = new Loader(); + loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler); + loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); + loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler); + } + + public function load(lib:String):void { + swfLib = lib; + request = new URLRequest(swfLib); + var context:LoaderContext = new LoaderContext(); +// context.applicationDomain = ApplicationDomain.currentDomain; + context.applicationDomain = new ApplicationDomain(); + loader.load(request,context); + } + + public function getClass(className:String):Class { + try { + return loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class; + } catch (e:Error) { + throw new IllegalOperationError(className + " definition not found in " + swfLib); + } + return null; + } + + private function completeHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.CLASS_LOADED)); + } + + private function ioErrorHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.LOAD_ERROR)); + } + + private function securityErrorHandler(e:Event):void { + dispatchEvent(new Event(ClassLoader.LOAD_ERROR)); + } +} +
flash.display.Loader.load()flash.display.Loader.loadBytes()flash.display.LoaderInfoflash.net.URLRequestflash.system.LoaderContextApplicationDomain + Creates a new application domain.parentDomainflash.system:ApplicationDomainnullIf no parent domain is passed in, this application domain takes the system domain as its parent. + + + + Creates a new application domain. + + getDefinition + Gets a public definition from the specified application domain.No public definition exists with the + specified name. + + ReferenceErrorReferenceErrorThe object associated with the definition. + + ObjectnameStringThe name of the definition. + + + Gets a public definition from the specified application domain. + The definition can be that of a class, a namespace, or a function. + + hasDefinition + Checks to see if a public definition exists within the specified application domain.A value of true if the specified definition exists; otherwise, false. + + BooleannameStringThe name of the definition. + + + Checks to see if a public definition exists within the specified application domain. + The definition can be that of a class, a namespace, or a function. + + MIN_DOMAIN_MEMORY_LENGTH + Gets the minimum memory object length required to be used as + ApplicationDomain.domainMemory.uint + + Gets the minimum memory object length required to be used as + ApplicationDomain.domainMemory. + + currentDomain + Gets the current application domain in which your code is executing.flash.system:ApplicationDomain + + Gets the current application domain in which your code is executing. + domainMemory + Gets and sets the object on which domain-global memory operations + will operate within this ApplicationDomain.flash.utils:ByteArray + + Gets and sets the object on which domain-global memory operations + will operate within this ApplicationDomain. + + parentDomain + Gets the parent domain of this application domain.flash.system:ApplicationDomain + + Gets the parent domain of this application domain. + +
Security + The Security class lets you specify how content in different domains can communicate with + each other.Object + The Security class lets you specify how content in different domains can communicate with + each other. + + The following example shows how a click event on a Sprite object can be + used to show the Local Storage Settings panel of the Flash Player Settings. An orange box is added to the + stage using draw(). In draw(), a click event listener is + added named clickHandler(), which responds to click events by directing + Flash Player to open its Local Storage Settings panel. + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.*; + import flash.system.Security; + import flash.system.SecurityPanel; + + public class SecurityExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 100; + + public function SecurityExample() { + draw(); + } + + private function draw():void { + var child:Sprite = new Sprite(); + child.graphics.beginFill(bgColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + child.buttonMode = true; + + var label:TextField = new TextField(); + label.text = "settings"; + label.selectable = false; + label.mouseEnabled = false; + child.addChild(label); + + child.addEventListener(MouseEvent.CLICK, clickHandler); + addChild(child); + } + + private function clickHandler(event:MouseEvent):void { + Security.showSettings(SecurityPanel.LOCAL_STORAGE); + } + } +} +allowDomain + Lets SWF files in the identified domains access objects and variables + in the SWF file that contains the allowDomain() call.Calling this method from code in the AIR application security sandbox + throws a SecurityError exception. Content outside of the application security sandbox cannot cross-script + content in the application security sandbox. + + SecurityErrorSecurityErrordomainsOne or more strings or URLRequest objects that name the domains from which + you want to allow access. You can specify the special domain "~~" to + allow access from all domains. + +

In Flash Professional, specifying "~~" is the only + way to allow access to nonlocal SWF files from local SWF files that have been + published using Access Network Only for the Local Playback + Security option in the Flash authoring tool.

+

Note: + The wildcard value does not work for subdomains. For example, you cannot use ~~.foo.com for + the domains parameter. While you can specify a subdomain with a wild card value for a cross domain policy file + (as in ~~.foo.com), you can't use a wildcard value that way for the allowDomain() method.

+ +
Lets SWF files and HTML files access objects and variables in the calling SWF file. + +
+ Lets SWF files in the identified domains access objects and variables + in the SWF file that contains the allowDomain() call. + + + +

Note: Calling this method from code in the AIR application sandbox + throws a SecurityError exception. Content outside of the application security domain cannot directly + cross-script content in the application sandbox. However, content outside of the application sandbox can + communicate with content in the application security sandbox using a sandbox bridge.

+ +

If two SWF files are served from the same domain — for example, http://mysite.com/swfA.swf and + http://mysite.com/swfB.swf — then swfA.swf can examine and modify variables, objects, properties, + methods, and so on in swfB.swf, and swfB.swf can do the same for swfA.swf. This is called cross-movie + scripting or cross-scripting.

+ +

If two SWF files are served from different domains — for example, http://siteA.com/swfA.swf and + http://siteB.com/siteB.swf — then, by default, Flash Player does not allow swfA.swf to script + swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains + by calling Security.allowDomain(). This is + called cross-domain scripting. By calling Security.allowDomain("siteA.com"), siteB.swf + gives siteA.swf permission to script it.

+ +

In any cross-domain situation, it is important to be clear about the two parties involved. + For the purposes of this discussion, the side performing the cross-scripting + is called the accessing party (usually the accessing SWF), and the other side is called the party being accessed + (usually the SWF file being accessed). When siteA.swf scripts siteB.swf, + siteA.swf is the accessing party, and siteB.swf is the party being accessed.

+ +

+ +

Cross-domain permissions that are established with allowDomain() are asymmetrical. + In the previous example, siteA.swf can script siteB.swf, but siteB.swf cannot script siteA.swf, + because siteA.swf has not called allowDomain() to give SWF files at siteB.com permission + to script it. You can set up symmetrical permissions by having both SWF files call + allowDomain().

+ +

In addition to protecting SWF files from cross-domain scripting originated by other SWF files, Flash Player + protects SWF files from cross-domain scripting originated by HTML files. HTML-to-SWF scripting can + occur with older browser functions such as SetVariable or callbacks + established through ExternalInterface.addCallback(). When HTML-to-SWF scripting crosses + domains, the SWF file being accessed must call allowDomain(), + just as when the accessing party is a SWF file, or the operation will fail.

+ +

Specifying an IP address as a parameter to allowDomain() + does not permit access by all parties that originate at the specified IP address. + Instead, it permits access only by a party that contains the specified IP address it its URL, + rather than a domain name that maps to that IP address.

+ +

Version-specific differences

+

Flash Player's cross-domain security rules have evolved from version to version. + The following table summarizes the differences.

+ + Latest SWF version involved in cross-scriptingallowDomain() needed?allowInsecureDomain() needed?Which SWF file must call allowDomain() or allowInsecureDomain()?What can be specified in allowDomain() or allowInsecureDomain()?5 or earlierNoNoN/AN/A6Yes, if superdomains don't matchNoThe SWF file being accessed, or any SWF file with the same superdomain as the SWF file being accessed
  • Text-based domain (mysite.com)
  • IP address (192.168.1.1)
7Yes, if domains don't match exactlyYes, if performing HTTP-to-HTTPS access (even if domains match exactly)The SWF file being accessed, or any SWF file with exactly the same domain as the SWF file being accessed
  • Text-based domain (mysite.com)
  • IP address (192.168.1.1)
8 or laterYes, if domains don't match exactlyYes, if performing HTTP-to-HTTPS access (even if domains match exactly)SWF file being accessed
  • Text-based domain (mysite.com)
  • IP address (192.168.1.1)
  • Wildcard (~~)
+ +

The versions that control the behavior of Flash Player are SWF versions + (the published version of a SWF file), not the version of Flash Player itself. + For example, when Flash Player 8 is playing a SWF file published for version 7, it + applies behavior that is consistent with version 7. This practice ensures that player upgrades do not + change the behavior of Security.allowDomain() in deployed SWF files.

+ +

The version column in the previous table shows the latest SWF version involved in a cross-scripting + operation. Flash Player determines its behavior according to either the accessing SWF file's + version or the version of the SWF file that is being accessed, whichever is later.

+ +

The following paragraphs provide more detail about Flash Player security changes involving + Security.allowDomain().

+ +

Version 5. There are no cross-domain scripting restrictions.

+ +

Version 6. Cross-domain scripting security is introduced. By default, Flash Player forbids + cross-domain scripting; Security.allowDomain() can permit it. To determine whether two files are + in the same domain, Flash Player uses each file's superdomain, which is the exact host name from the + file's URL, minus the first segment, down to a minimum of two segments. For example, the superdomain of + www.mysite.com is mysite.com. SWF files from www.mysite.com and + store.mysite.com to script each other without a call to Security.allowDomain().

+ +

Version 7. Superdomain matching is changed to exact domain matching. Two files are + permitted to script each other only if the host names in their URLs are identical; otherwise, a call to + Security.allowDomain() is required. By default, files loaded from non-HTTPS URLs are no longer + permitted to script files loaded from HTTPS URLs, even if the files are loaded from exactly the same + domain. This restriction helps protect HTTPS files, because a non-HTTPS file is vulnerable to + modification during download, and a maliciously modified non-HTTPS file could corrupt an HTTPS file, + which is otherwise immune to such tampering. Security.allowInsecureDomain() is introduced to + allow HTTPS SWF files that are being accessed to voluntarily disable this restriction, but the use of + Security.allowInsecureDomain() is discouraged.

+ +

Version 8. There are two major areas of change:

+ +
  • Calling Security.allowDomain() now permits cross-scripting operations + only if the SWF file being accessed is the SWF file that called Security.allowDomain(). + In other words, a SWF file that calls Security.allowDomain() now permits access only to itself. + In previous versions, calling Security.allowDomain() permitted cross-scripting operations + where the SWF file being accessed could be any SWF file in the same domain as the SWF file that called + Security.allowDomain(). Calling Security.allowDomain() previously opened up + the entire domain of the calling SWF file.
  • Support has been added for wildcard values with Security.allowDomain("~~") and + Security.allowInsecureDomain("~~"). + The wildcard (~~) value permits cross-scripting operations where the accessing file is any file at all, + loaded from anywhere. Think of the wildcard as a global permission. Wildcard permissions + are required to enable certain kinds of operations + under the local file security rules. Specifically, + for a local SWF file with network-access permissions to script a SWF file on the + Internet, the Internet SWF file being accessed must call Security.allowDomain("~~"), + reflecting that the origin of a local SWF file is unknown. (If the Internet SWF file is loaded from an + HTTPS URL, the Internet SWF file must instead call Security.allowInsecureDomain("~~").)
+ +

Occasionally, you may encounter the following situation: You load a child SWF file + from a different domain and want to allow the child SWF file to script the parent SWF file, + but you don't know the final domain of the child SWF file. This can happen, for + example, when you use load-balancing redirects or third-party servers.

+ +

In this situation, you can use the url property of the URLRequest object + that you pass to Loader.load(). For example, if you load a child SWF file + into a parent SWF, you can access the contentLoaderInfo property of the Loader + object for the parent SWF:

+ Security.allowDomain(loader.contentLoaderInfo.url) + +

Make sure that you wait until the child SWF file begins loading to get the correct + value of the url property. To determine when the child SWF has begun loading, + use the progress event.

+ +

The opposite situation can also occur; that is, you might create a child SWF file + that wants to allow its parent to script it, but doesn't know what the domain of its parent + will be. In this situation, you can access the loaderInfo property + of the display object that is the SWF's root object. In the child SWF, call + Security.allowDomain( this.root.loaderInfo.loaderURL). + You don't have to wait for the parent SWF file to load; the parent will already be + loaded by the time the child loads.

+ +

If you are publishing for Flash Player 8 or later, you can also handle these situations by calling + Security.allowDomain("~~"). However, this can sometimes be a dangerous shortcut, + because it allows the calling SWF file to be accessed by any other SWF file from any domain. + It is usually safer to use the _url property.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
ExternalInterface.addCallback()flash.events.Event.COMPLETEflash.display.DisplayObject.parentflash.net.URLRequest.urlallowInsecureDomain()
allowInsecureDomain + Lets SWF files and HTML files in the identified domains access objects + and variables in the calling SWF file, which is hosted by means of the HTTPS protocol.Calling this method from code in the AIR application security sandbox causes a + SecurityError exception to be thrown. Content outside of the application security sandbox cannot cross-script + content in the application security sandbox. + + SecurityErrorSecurityErrordomainsOne or more strings or URLRequest objects that name the domains from which + you want to allow access. You can specify the special domain "~~" to + allow access from all domains. + +

Specifying "~~" is the only + way to allow access to nonlocal SWF files from local SWF files that have been + published using the Access Network Only option for the Local Playback + Security setting (File > Publish Settings > Flash tab) in the Flash authoring tool.

+ +

Note: + The wildcard value does not work for subdomains. For example, you cannot use ~~.foo.com for + the domains parameter. While you can specify a subdomain with a wild card value for a cross domain policy file + (as in ~~.foo.com), you can't use a wildcard value that way for the allowInsecureDomain() method.

+
Lets SWF and HTML files hosted using the HTTPS protocol, access objects and variables in + the calling SWF file. + +
+ Lets SWF files and HTML files in the identified domains access objects + and variables in the calling SWF file, which is hosted by means of the HTTPS protocol. + + + + +

Flash Player provides allowInsecureDomain() to maximize flexibility, + but calling this method is not recommended. Serving a file over HTTPS provides several protections + for you and your users, and calling allowInsecureDomain weakens one of those + protections.

+ +

Note: Calling this method from code in the AIR application sandbox + throws a SecurityError exception. Content outside of the application security domain cannot directly + cross-script content in the application sandbox. However, content outside of the application sandbox can + communicate with content in the application security sandbox using a sandbox bridge.

+ +

This method works in the same way as Security.allowDomain(), but it also + permits operations in which the accessing party is loaded with a non-HTTPS protocol, and the + party being accessed is loaded with HTTPS. In Flash Player 7 and later, + non-HTTPS files are not allowed to script HTTPS files. The allowInsecureDomain() method lifts this + restriction when the HTTPS SWF file being accessed uses it.

+ +

Use allowInsecureDomain() only to enable scripting from non-HTTPS files + to HTTPS files. Use it to enable scripting when the accessing non-HTTPS file and + the HTTPS file being accessed are served from the same domain, for example, if a SWF file at + http://mysite.com wants to script a SWF file at https://mysite.com. Do not use this method to enable + scripting between non-HTTPS files, between HTTPS files, or from HTTPS files to non-HTTPS + files. For those situations, use allowDomain() instead.

+ + The following scenario illustrates how allowInsecureDomain() can compromise security, if it is not used + with careful consideration. + +

Note that the following information is only one possible scenario, designed to + help you understand allowInsecureDomain() through a real-world example + of cross-scripting. + It does not cover all issues with security architecture and should be used for background + information only. The Flash Player Developer Center contains extensive information on Flash Player + and security. For more information, see + the Flash Player Developer Center Topic Security.

+ +

Suppose you are building an e-commerce site that consists of two components: + a catalog, which does not need to be secure, because it contains only public information; + and a shopping cart/checkout component, which must be secure to protect users' financial and + personal information. Suppose you are considering serving the catalog from + http://mysite.com/catalog.swf and the cart from https://mysite.com/cart.swf. One + requirement for your site is that a third party should not be able to steal your + users' credit card numbers by taking advantage of a weakness in your security architecture.

+ +

Suppose that a middle-party attacker intervenes between your server and your users, attempting + to steal the credit card numbers that your users enter into your shopping cart application. + A middle party might, for example, be an unscrupulous ISP used by some of your users, or a + malicious administrator at a user's workplace — anyone who has the ability to view or alter + network packets transmitted over the public Internet between your users and your servers. + This situation is not uncommon.

+ +

If cart.swf uses HTTPS to transmit credit card information to your servers, then the + middle-party attacker can't directly steal this information from network packets, because the + HTTPS transmission is encrypted. However, the attacker can use a different technique: altering the + contents of one of your SWF files as it is delivered to the user, replacing your SWF file with an + altered version that transmits the user's information to a different server, owned by the attacker.

+ +

The HTTPS protocol, among other things, prevents this "modification" attack from working, + because, in addition to being encrypted, HTTPS transmissions are tamper-resistant. + If a middle-party attacker alters a packet, the receiving side detects the alteration + and discards the packet. So the attacker in this situation can't alter cart.swf, because it + is delivered over HTTPS.

+ +

However, suppose that you want to allow buttons in catalog.swf, served over HTTP, + to add items to the shopping cart in cart.swf, served over HTTPS. To accomplish this, + cart.swf calls allowInsecureDomain(), which allows catalog.swf to script cart.swf. + This action has an unintended consequence: Now the attacker can alter + catalog.swf as it is initially being downloaded by + the user, because catalog.swf is delivered with HTTP and is not tamper-resistant. + The attacker's altered catalog.swf can now script cart.swf, because cart.swf contains + a call to allowInsecureDomain(). The altered catalog.swf file can use ActionScript to access + the variables in cart.swf, thus reading the user's credit card information and other + sensitive data. The altered catalog.swf can then send this data to an attacker's server.

+ +

Obviously, this implementation is not desired, but you still want to allow + cross-scripting between the two SWF files on your site. Here are two possible ways to redesign + this hypothetical e-commerce site to avoid allowInsecureDomain():

+ +
  • Serve all SWF files in the application over HTTPS. This is by far the simplest and most + reliable solution. In the scenario described, you would serve both catalog.swf and cart.swf + over HTTPS. You might experience slightly higher bandwidth consumption and server CPU load + when switching a file such as catalog.swf from HTTP to HTTPS, and your users might experience + slightly longer application load times. You need to experiment with real servers to + determine the severity of these effects; usually they are no worse than 10-20% each, and + sometimes they are not present at all. You can usually improve results by using HTTPS-accelerating + hardware or software on your servers. A major benefit of serving all + cooperating SWF files over HTTPS is that you can use an HTTPS URL as the main URL + in the user's browser without generating any mixed-content warnings from the browser. + Also, the browser's padlock icon becomes visible, providing your users with + a common and trusted indicator of security.
  • Use HTTPS-to-HTTP scripting, rather than HTTP-to-HTTPS scripting. In the scenario described, you + could store the contents of the user's shopping cart in catalog.swf, and have cart.swf manage + only the checkout process. At checkout time, cart.swf could retrieve the cart contents from + ActionScript variables in catalog.swf. The restriction on HTTP-to-HTTPS scripting is asymmetrical; + although an HTTP-delivered catalog.swf file cannot safely be allowed to script an HTTPS-delivered cart.swf file, + an HTTPS cart.swf file can script the HTTP catalog.swf file. + This approach is more delicate than the all-HTTPS approach; you must be careful not to trust any + SWF file delivered over HTTP, because of its vulnerability to tampering. For example, when cart.swf + retrieves the ActionScript variable that describes the cart contents, the ActionScript code + in cart.swf cannot trust that the value of this variable is in the format that you expect. + You must verify that the cart contents do not contain invalid data that might + lead cart.swf to take an undesired action. You must also accept the risk that a middle party, + by altering catalog.swf, could supply valid but inaccurate data to cart.swf; for example, by placing + items in the user's cart. The usual checkout process mitigates + this risk somewhat by displaying the cart contents and total cost for final approval by the user, + but the risk remains present.
+ +

Web browsers have enforced separation between HTTPS and non-HTTPS files for years, + and the scenario described illustrates one good reason for this restriction. + Flash Player gives you the ability to work around this security restriction when you + absolutely must, but be sure to consider the consequences carefully before doing so.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
allowDomain()
loadPolicyFile + Looks for a policy file at the location specified by the url + parameter.urlStringThe URL location of the policy file to be loaded. + Looks for a policy file at the location specified by the url parameter. + + + Looks for a policy file at the location specified by the url + parameter. Adobe AIR and Flash Player use policy files to determine + whether to permit applications to load data from servers other than their own. + Note that even though the method name is loadPolicyFile(), + the file isn't actually loaded until a network request that requires a policy file is made. + +

With Security.loadPolicyFile(), Flash Player or AIR can + load policy files from arbitrary locations, as shown in the following example:

+ + + Security.loadPolicyFile("http://www.example.com/sub/dir/pf.xml"); + + + + +

This causes Flash Player or AIR to attempt to retrieve a policy file from the specified URL. Any permissions + granted by the policy file at that location will apply to all content at the same level or lower in + the virtual directory hierarchy of the server.

+ +

For example, following the previous code, these lines do not throw an exception:

+ + import flash.net.~~; + var request:URLRequest = new URLRequest("http://www.example.com/sub/dir/vars.txt"); + var loader:URLLoader = new URLLoader(); + loader.load(request); + + var loader2:URLLoader = new URLLoader(); + var request2:URLRequest = new URLRequest("http://www.example.com/sub/dir/deep/vars2.txt"); + loader2.load(request2); + + +

However, the following code does throw a security exception:

+ + import flash.net.~~; + var request3:URLRequest = new URLRequest("http://www.example.com/elsewhere/vars3.txt"); + var loader3:URLLoader = new URLLoader(); + loader3.load(request3); + + +

You can use loadPolicyFile() to load any number of policy files. When considering a + request that requires a policy file, Flash Player or AIR always waits for the completion of any policy + file downloads before denying a request. As a final fallback, if no policy file specified with + loadPolicyFile() authorizes a request, Flash Player or AIR consults the original default + locations.

+ +

When checking for a master policy file, Flash Player waits three seconds for a server response. + If a response isn't received, Flash Player assumes that no master policy file exists. + However, there is no default timeout value for calls to loadPolicyFile(); + Flash Player assumes that the file being called exists, and waits as long as necessary to load it. + Therefore, if you want to make sure that a master policy file is loaded, use loadPolicyFile() + to call it explicitly.

+ +

You cannot connect to commonly reserved ports. + For a complete list of blocked ports, see "Restricting Networking APIs" in the + ActionScript 3.0 Developer's Guide.

+ +

Using the xmlsocket protocol along with a specific port number lets you retrieve + policy files directly from an XMLSocket server, as shown in the following example. Socket + connections are not subject to the reserved port restriction described above.

+ + + Security.loadPolicyFile("xmlsocket://foo.com:414"); + + + + +

This causes Flash Player or AIR to attempt to retrieve a policy file from the specified host and port. + Upon establishing a connection with the + specified port, Flash Player or AIR transmits <policy-file-request />, terminated by a + null byte. The server must send a null byte to terminate a policy file, and may thereafter close the connection; + if the server does not close the connection, Flash Player or AIR does so upon receiving the terminating + null byte.

+ +

You can prevent a SWF file from using this method by setting the + allowNetworking parameter of the object and embed + tags in the HTML page that contains the SWF content.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
showSettings + Displays the Security Settings panel in Flash Player.panelStringdefaultA value from the SecurityPanel class that specifies which Security Settings + panel you want to display. If you omit this parameter, SecurityPanel.DEFAULT is used. + + + Displays the Security Settings panel in Flash Player. This method does not apply to content in + Adobe AIR; calling it in an AIR application has no effect. + + SecurityPanelAPPLICATION + The file is running in an AIR application, and it was installed with the package (the AIR file) for that + application.applicationString + The file is running in an AIR application, and it was installed with the package (the AIR file) for that + application. This content is included in the AIR application resource directory (where the application + content is installed). + + sandboxTypeREMOTELOCAL_WITH_FILELOCAL_WITH_NETWORKLOCAL_TRUSTEDLOCAL_TRUSTED + The file is a local file and has been trusted by the user, + using either the Flash Player Settings Manager or a FlashPlayerTrust configuration + file.localTrustedString + The file is a local file and has been trusted by the user, + using either the Flash Player Settings Manager or a FlashPlayerTrust configuration + file. The file can read from local data sources and communicate + with the Internet. + + sandboxTypeREMOTELOCAL_WITH_FILELOCAL_WITH_NETWORKAPPLICATIONLOCAL_WITH_FILE + The file is a local file, has not been trusted by the user, + and it is not a SWF file that was published with a networking designation.localWithFileString + The file is a local file, has not been trusted by the user, + and it is not a SWF file that was published with a networking designation. In Adobe AIR, + the local file is not in the application resource directory; such files are + put in the application security sandbox. The file may + read from local data sources but may not communicate with the Internet. + + sandboxTypeREMOTELOCAL_WITH_NETWORKLOCAL_TRUSTEDAPPLICATIONLOCAL_WITH_NETWORK + The file is a local file, has not been trusted by the user, and it is a SWF + file that was published with a networking designation.localWithNetworkString + The file is a local file, has not been trusted by the user, and it is a SWF + file that was published with a networking designation. The file can + communicate with the Internet but cannot read from local data sources. + + sandboxTypeREMOTELOCAL_WITH_FILELOCAL_TRUSTEDAPPLICATIONREMOTE + The file is from an Internet URL and operates under domain-based sandbox rules.remoteString + The file is from an Internet URL and operates under domain-based sandbox rules. + + sandboxTypeLOCAL_WITH_FILELOCAL_WITH_NETWORKLOCAL_TRUSTEDAPPLICATIONexactSettings + Determines how Flash Player or AIR chooses the domain to use for certain + content settings, including settings for camera and microphone + permissions, storage quotas, and storage of persistent shared objects.BooleanA Flash Player or AIR application already used the value of exactSettings + at least once in a decision about player settings. + + SecurityErrorSecurityError + Determines how Flash Player or AIR chooses the domain to use for certain + content settings, including settings for camera and microphone + permissions, storage quotas, and storage of persistent shared objects. + To have the SWF file use the same settings that were used in Flash Player 6, + set exactSettings to false. + + + +

In Flash Player 6, the domain used for these player settings was based on + the trailing portion of the domain of the SWF file. If the domain of a SWF file + includes more than two segments, such as www.example.com, the first segment + of the domain ("www") is removed, and the remaining portion of the domain is used: + example.com. So, in Flash Player 6, www.example.com and store.example.com both + use example.com as the domain for these settings. Similarly, www.example.co.uk and + store.example.co.uk both use example.co.uk as the domain for these settings. + In Flash Player 7 and later, player settings are chosen by default + according to a SWF file's exact domain; for example, a SWF file from www.example.com + would use the player settings for www.example.com, and a SWF file from + store.example.com would use the separate player settings for + store.example.com.

+ +

When Security.exactSettings is set to true, Flash Player + or AIR uses exact domains for player settings. The default value for exactSettings is true. + If you change exactSettings from its default value, do so before any events + occur that require Flash Player or AIR to choose player settings — for example, + using a camera or microphone, or retrieving a persistent shared object.

+ +

If you previously published a version 6 SWF file and + created persistent shared objects from it, and you now need to + retrieve those persistent shared objects from that SWF file + after porting it to version 7 or later, or from a different SWF file of + version 7 or later, set Security.exactSettings to false + before calling SharedObject.getLocal().

+ +
pageDomain + Get the page domain containing the swf.String + Get the page domain containing the swf. For security reasons, the method does not return the full URL, only the page + domain, such as http://www.example.com. + + sandboxType + Indicates the type of security sandbox in which the calling file is operating.String + Indicates the type of security sandbox in which the calling file is operating. + +

Security.sandboxType has one of the following values:

+ +
  • remote (Security.REMOTE)—This file is from an Internet URL and operates under domain-based sandbox + rules.
  • localWithFile (Security.LOCAL_WITH_FILE)—This file is a local file, has not been trusted by the user, and + it is not a SWF file that was published with a networking designation. The file may read from local data sources but may + not communicate with the Internet.
  • localWithNetwork (Security.LOCAL_WITH_NETWORK)—This SWF file is a local file, has not been trusted by the user, and + was published with a networking designation. The SWF file can communicate with the Internet but cannot + read from local data sources.
  • localTrusted (Security.LOCAL_TRUSTED)—This file is a local file and has been trusted by + the user, using either the Flash Player Settings Manager or a FlashPlayerTrust configuration file. The file can read from local data + sources and communicate with the Internet.
  • application (Security.APPLICATION)—This file is + running in an AIR application, and it was installed with the package (AIR file) for that + application. By default, files in the AIR application sandbox can cross-script any file from any domain + (although files outside the AIR application sandbox may not be permitted to cross-script the AIR file). + By default, files in the AIR application sandbox can load content and data from any domain.
+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +
REMOTELOCAL_WITH_FILELOCAL_WITH_NETWORKLOCAL_TRUSTEDAPPLICATION
LoaderContext + The LoaderContext class provides options for loading SWF files and other media by using the Loader class.Object + The LoaderContext class provides options for loading SWF files and other media by using the Loader class. + The LoaderContext class is used as the context parameter in the load() and + loadBytes() methods of the Loader class. + +

When loading SWF files with the Loader.load() method, you have two decisions to make: + into which security domain the loaded SWF file should be placed, and into which application domain + within that security domain? For more details on these choices, see the + applicationDomain and securityDomain properties.

+ +

When loading a SWF file with the Loader.loadBytes() method, you have the same + application domain choice to make as for Loader.load(), but it's not + necessary to specify a security domain, because Loader.loadBytes() always + places its loaded SWF file into the security domain of the loading SWF file.

+ +

When loading images (JPEG, GIF, or PNG) instead of SWF files, there is no need to + specify a SecurityDomain or an application domain, because those concepts are + meaningful only for SWF files. Instead, you have only one decision to make: do you need + programmatic access to the pixels of the loaded image? If so, see the + checkPolicyFile property. If you want to apply deblocking when loading + an image, use the JPEGLoaderContext class instead of the LoaderContext class.

+ +
flash.display.Loader.load()flash.display.Loader.loadBytes()flash.system.ApplicationDomainflash.system.JPEGLoaderContextflash.system.LoaderContext.applicationDomainflash.system.LoaderContext.checkPolicyFileflash.system.LoaderContext.securityDomainflash.system.SecurityDomainflash.system.ImageDecodingPolicyLoaderContext + Creates a new LoaderContext object, with the specified settings.checkPolicyFileBooleanfalseSpecifies whether a check should be made for the existence + of a URL policy file before loading the object. + + applicationDomainflash.system:ApplicationDomainnullSpecifies the ApplicationDomain object to use for a Loader object. + + securityDomainflash.system:SecurityDomainnullSpecifies the SecurityDomain object to use for a Loader object. + +

Note: Content in the air application security sandbox cannot load content from + other sandboxes into its SecurityDomain.

+ +
+ Creates a new LoaderContext object, with the specified settings. For complete + details on these settings, see the descriptions of the properties of this class. + +
flash.display.Loader.load()flash.display.Loader.loadBytes()flash.system.ApplicationDomainflash.system.SecurityDomain
allowCodeImport + Specifies whether you can use a Loader object to import content with executable code, + such as a SWF file, into the caller's security sandbox.Boolean + Specifies whether you can use a Loader object to import content with executable code, + such as a SWF file, into the caller's security sandbox. There are two affected importing operations: + the Loader.loadBytes() method, and the Loader.load() method with + LoaderContext.securityDomain = SecurityDomain.currentDomain. (The latter operation is not + supported in the AIR application sandbox.) With the allowCodeImport property set to + false, these importing operations are restricted to safe operations, such as loading + images. Normal, non-importing SWF file loading with the Loader.load() method is not + affected by the value of this property. + +

This property is useful when you want to import image content into your sandbox - for example, when you + want to replicate or process an image from a different domain - but you don't want to take the security risk + of receiving a SWF file when you expected only an image file. Since SWF files may contain ActionScript code, + importing a SWF file is a much riskier operation than importing an image file.

+ +

In AIR content in the application sandbox, the default value is false. In non-application + content (which includes all content in Flash Player), the default value is true.

+ +

The allowCodeImport property was added in Flash Player 10.1 and AIR 2.0. + However, this property is made available to SWF files and AIR applications of all versions when the + Flash Runtime supports it.

+ +
flash.display.Loader.loadBytes()flash.display.Loader.load()securityDomain
applicationDomain + Specifies the application domain to use for the Loader.load() or + Loader.loadBytes() method.nullflash.system:ApplicationDomain + Specifies the application domain to use for the Loader.load() or + Loader.loadBytes() method. Use this property only when loading a SWF file + written in ActionScript 3.0 (not an image or a SWF file written in ActionScript 1.0 or ActionScript 2.0). + +

Every security domain is divided into one or more application domains, represented + by ApplicationDomain objects. Application domains are not for security + purposes; they are for managing cooperating units of ActionScript code. If you are + loading a SWF file from another domain, and allowing it to be placed in a separate + security domain, then you cannot control the choice of application domain into which the + loaded SWF file is placed; and if you have specified a choice of application domain, it + will be ignored. However, if you are loading a SWF file into your own security domain — + either because the SWF file comes from your own domain, or because you are importing it into + your security domain — then you can control the choice of application domain for the + loaded SWF file.

+ +

You can pass an application domain only from your own security domain in + LoaderContext.applicationDomain. Attempting to pass an application domain + from any other security domain results in a SecurityError exception.

+ +

You have four choices for what kind of ApplicationDomain property to use:

+ +
  • Child of loader's ApplicationDomain. The default. You can + explicitly represent this choice with the syntax + new ApplicationDomain(ApplicationDomain.currentDomain). This allows the + loaded SWF file to use the parent's classes directly, for example by writing + new MyClassDefinedInParent(). The parent, however, cannot use this syntax; + if the parent wishes to use the child's classes, it must call + ApplicationDomain.getDefinition() to retrieve them. The advantage of + this choice is that, if the child defines a class with the same name as a class already + defined by the parent, no error results; the child simply inherits the parent's + definition of that class, and the child's conflicting definition goes unused unless + either child or parent calls the ApplicationDomain.getDefinition() method to retrieve + it.
  • Loader's own ApplicationDomain. You use this application domain when using + ApplicationDomain.currentDomain. When the load is complete, parent and + child can use each other's classes directly. If the child attempts to define a class with the same name + as a class already defined by the parent, the parent class is used and the child class is ignored.
  • Child of the system ApplicationDomain. You use this application domain when using + new ApplicationDomain(null). This separates loader and loadee entirely, + allowing them to define separate versions of classes with the same name without conflict + or overshadowing. The only way either side sees the other's classes is by calling the + ApplicationDomain.getDefinition() method.
  • Child of some other ApplicationDomain. Occasionally you may have + a more complex ApplicationDomain hierarchy. You can load a SWF file into any + ApplicationDomain from your own SecurityDomain. For example, + new ApplicationDomain(ApplicationDomain.currentDomain.parentDomain.parentDomain) + loads a SWF file into a new child of the current domain's parent's parent.
+ +

When a load is complete, either side (loading or loaded) may need to find its own + ApplicationDomain, or the other side's ApplicationDomain, for the purpose of calling + ApplicationDomain.getDefinition(). Either side can retrieve a reference to + its own application domain by using ApplicationDomain.currentDomain. The loading + SWF file can retrieve a reference to the loaded SWF file's ApplicationDomain via + Loader.contentLoaderInfo.applicationDomain. If the loaded SWF file knows how it + was loaded, it can find its way to the loading SWF file's ApplicationDomain object. For example, if + the child was loaded in the default way, it can find the loading SWF file's application domain + by using ApplicationDomain.currentDomain.parentDomain.

+ +

For more information, see the "ApplicationDomain class" section of the "Client System + Environment" chapter of the ActionScript 3.0 Developer's Guide.

+ +
flash.display.Loader.load()flash.display.Loader.loadBytes()flash.system.ApplicationDomain
checkPolicyFile + Specifies whether the application should attempt to download a URL policy file from the + loaded object's server before beginning to load the object itself.falseBoolean + Specifies whether the application should attempt to download a URL policy file from the + loaded object's server before beginning to load the object itself. This flag is applicable to + the Loader.load() method, but not to the Loader.loadBytes() method. + +

Set this flag to true when you are loading an image (JPEG, GIF, or PNG) from outside the calling + SWF file's own domain, and you expect to need access to the content of that image from ActionScript. + Examples of accessing image content include referencing the Loader.content property + to obtain a Bitmap object, and calling the BitmapData.draw() method to obtain a + copy of the loaded image's pixels. If you attempt one of these operations without having + specified checkPolicyFile at loading time, you may get a SecurityError + exception because the needed policy file has not been downloaded yet.

+ +

When you call the Loader.load() method with LoaderContext.checkPolicyFile set to + true, the application does not begin downloading the specified object in URLRequest.url + until it has either successfully downloaded a relevant URL policy file or discovered + that no such policy file exists. Flash Player or AIR first considers policy files that have already + been downloaded, then attempts to download any pending policy files specified in calls to + the Security.loadPolicyFile() method, then attempts to download a policy file from the default + location that corresponds to URLRequest.url, which is /crossdomain.xml + on the same server as URLRequest.url. In all cases, the given policy file is required to exist + at URLRequest.url by virtue of the policy file's location, and the file must permit access + by virtue of one or more <allow-access-from> + tags.

+ +

If you set checkPolicyFile to true, the main download that specified in the + Loader.load() method does not load until the policy file has been completely processed. + Therefore, as long as the + policy file that you need exists, as soon as you have received any ProgressEvent.PROGRESS or + Event.COMPLETE events from the contentLoaderInfo property of your Loader object, + the policy file download is complete, and you can safely begin performing operations that require + the policy file.

+ +

If you set checkPolicyFile to true, and no relevant policy file is found, + you will not receive any error indication until you attempt an operation that throws a + SecurityError exception. However, once the LoaderInfo object dispatches a + ProgressEvent.PROGRESS or Event.COMPLETE event, you can test whether a relevant + policy file was found by checking the value of the LoaderInfo.childAllowsParent property.

+ +

If you will not need pixel-level access to the image that you are loading, you should not set the + checkPolicyFile property to true. Checking for a policy file in this case is + wasteful, because it may delay the start of your download, and it may consume network bandwidth unnecessarily.

+ +

Also try to avoid setting checkPolicyFile to true if you are using the + Loader.load() method to download a SWF file. This is because SWF-to-SWF permissions are not + controlled by policy files, but rather by the Security.allowDomain() method, and thus + checkPolicyFile has no effect when you load a SWF file. Checking for a policy file in + this case is wasteful, because it may delay the download of the SWF file, and it may consume + network bandwidth unnecessarily. (Flash Player or AIR cannot tell whether your main download will be a + SWF file or an image, because the policy file download occurs before the main download.)

+ +

Be careful with checkPolicyFile if you are downloading an object from a URL that + may use server-side HTTP redirects. Policy files are always retrieved from the corresponding initial + URL that you specify in URLRequest.url. If the final + object comes from a different URL because of HTTP redirects, then the initially downloaded policy + files might not be applicable to the object's final URL, which is the URL that matters in + security decisions. If you find yourself in this situation, you can examine the value of + LoaderInfo.url after you have received a ProgressEvent.PROGRESS + or Event.COMPLETE event, which tells you the object's final URL. Then call the + Security.loadPolicyFile() method with a policy file URL based on the object's final + URL. Then poll the value of LoaderInfo.childAllowsParent until it becomes true.

+ +

You do not need to set this property for AIR content running in the application sandbox. Content + in the AIR application sandbox can call the BitmapData.draw() method using any loaded image + content as the source.

+ +
flash.display.BitmapData.draw()flash.display.Loader.contentflash.display.Loader.load()flash.display.LoaderInfo.childAllowsParentflash.display.LoaderInfo.urlflash.system.Security.allowDomain()flash.system.Security.loadPolicyFile()
imageDecodingPolicy + Specifies whether to decode image data when it is used or when it is loaded.String + Specifies whether to decode image data when it is used or when it is loaded. + +

Under the default policy, ImageDecodingPolicy.ON_DEMAND, the runtime decodes the image data + when the data is needed for display or other purpose. This policy maintains the decoding behavior used + by previous versions of the runtime.

+ +

Under the ImageDecodingPolicy.ON_LOAD policy, the runtime decodes the image immediately after + it is loaded and before dispatching the complete event. Decoding images on load rather than on demand can + improve animation and UI performance when several loaded images are displayed in quick succession, such as in a + scrolling list or a cover flow control. On the other hand, using the onLoad policy indiscriminately can increase + the peak memory usage of your application since more decoded image data might be in memory at one time than would + be the case under the onDemand policy.

+ +

Under both policies, the runtime uses the same cache and flush behavior after the image is decoded. + The runtime can flush the decoded data at any time and re-decode the image the next time + it is required.

+
flash.system.ImageDecodingPolicy
parameters + An Object containing the parameters to pass to the LoaderInfo object of the content.Object + An Object containing the parameters to pass to the LoaderInfo object of the content. + +

Normally, the value of the contentLoaderInfo.parameters property is obtained by parsing the requesting URL. + If the parameters var is set, the contentLoaderInfo.parameters gets its value from the LoaderContext object, instead of from + the requesting URL. The parameters var accepts only objects containing name-value string pairs, similar to URL parameters. If the object does + not contain name-value string pairs, an IllegalOperationError is thrown.

+

The intent of this API is to enable the loading SWF file to forward its parameters to a loaded SWF file. + This functionality is especially helpful when you use the loadBytes() method, since LoadBytes does not provide a + means of passing parameters through the URL. Parameters can be forwarded successfully only to another AS3 SWF file; an AS1 or AS2 SWF file cannot receive the parameters in an + accessible form, although the AVM1Movie's AS3 loaderInfo.parameters object will be the forwarded object.

+ + +

For example, consider the following URL:

+

http://yourdomain/users/jdoe/test01/child.swf?foo=bar;

+

The following code uses the LoaderContext.parameters property to replicate a parameter passed to this URL:

+ +
+      import flash.system.LoaderContext; 
+      import flash.display.Loader; 
+      var l:Loader = new Loader(); 
+      var lc:LoaderContext = new LoaderContext; 
+      lc.parameters = { "foo": "bar" }; 
+      l.load(new URLRequest("child.swf"), lc);
+     
+ +

To verify that the parameter passed properly, use the following trace statement after you run this code:

+

trace(loaderInfo.parameters.foo);

+

If the content loaded successfully, this trace prints "bar".

+
requestedContentParent + The parent to which the Loader will attempt to add the loaded content.flash.display:DisplayObjectContainer + The parent to which the Loader will attempt to add the loaded content. + +

When content is completely loaded, the Loader object normally becomes the parent of the content. + If requestedContentParent is set, the object that it specifies becomes the parent, unless a runtime error prevents the assignment. + This reparenting can also be done after the complete event without use of this property. However, specifying the + parent with LoaderContext.requestedContentParent eliminates extra events.

+

LoaderContext.requestedContentParent sets the desired parent before frame one scripts in + the loaded content execute, but after the constructor has run. If requestedContentParent is null (the default), + the Loader object becomes the content's parent.

+

If the loaded content is an AVM1Movie object, or if an + error is thrown when addChild() is called on the requestedContentParent object, then the following actions occur: +

  • The Loader object becomes the parent of the loaded content.
  • The runtime dispatches an AsyncErrorEvent.

+

If the requested parent and the loaded content are in different security sandboxes, and if the requested parent does not have access + to the loaded content, then the following actions occur: +

  • The Loader becomes the parent of the loaded content.
  • The runtime dispatches a SecurityErrorEvent.

+ +

The following code uses requestedContentParent to place the loaded content into a Sprite object:

+
+      import flash.system.LoaderContext; 
+      import flash.display.Loader; 
+      import flash.display.Sprite; 
+     
+      var lc:LoaderContext = new LoaderContext(); 
+      var l:Loader = new Loader(); 
+      var s:Sprite = new Sprite(); 
+      lc.requestedContentParent = s; 
+      addChild(s); 
+      l.load(new URLRequest("child.swf"), lc);
+     
+ +

When this code runs, the child SWF file appears on stage. This fact confirms that the Sprite object you added to the stage is the + parent of the loaded child.swf file.

+
securityDomain + Specifies the security domain to use for a Loader.load() operation.nullflash.system:SecurityDomain + Specifies the security domain to use for a Loader.load() operation. Use this property + only when loading a SWF file (not an image). + +

The choice of security domain is meaningful only if you are loading a SWF file that might + come from a different domain (a different server) than the loading SWF file. When you load a + SWF file from your own domain, it is always placed into your security domain. But when you + load a SWF file from a different domain, you have two options. You can allow the loaded SWF file to + be placed in its "natural" security domain, which is different from that of the + loading SWF file; this is the default. The other option is to specify that you want to place the + loaded SWF file placed into the same security domain as the loading SWF file, by setting + myLoaderContext.securityDomain to be equal to SecurityDomain.currentDomain. This is + called import loading, and it is equivalent, for security purposes, to copying the + loaded SWF file to your own server and loading it from there. In order for import loading to + succeed, the loaded SWF file's server must have a policy file trusting the domain of the + loading SWF file.

+ +

You can pass your own security domain only in LoaderContext.securityDomain. + Attempting to pass any other security domain results in a SecurityError exception.

+ +

Content in the AIR application security sandbox cannot load content from + other sandboxes into its SecurityDomain.

+ +

For more information, see the "Security" chapter in the ActionScript 3.0 Developer's Guide.

+ +
flash.display.Loader.load()flash.system.SecurityDomain
allowLoadBytesCodeExecution + Legacy property, replaced by allowCodeImport, but still supported for compatibility.Boolean + Legacy property, replaced by allowCodeImport, but still supported for compatibility. + Previously, the only operation affected by allowLoadBytesCodeExecution was the + Loader.loadBytes() method, but as of Flash Player 10.1 and AIR 2.0, the import-loading + operation of Loader.load() with LoaderContext.securityDomain = SecurityDomain.currentDomain + is affected as well. (The latter operation is not supported in the AIR application sandbox.) + This dual effect made the property name allowLoadBytesCodeExecution overly specific, + so now allowCodeImport is the preferred property name. Setting either of + allowCodeImport or allowLoadBytesCodeExecution will affect the value of both. + +

Specifies whether you can use a Loader object to import content with executable code, + such as a SWF file, into the caller's security sandbox. With this property set to false, + these importing operations are restricted to safe operations, such as loading images.

+ +

In AIR content in the application sandbox, the default value is false. In non-application content, the + default value is true.

+ +
flash.display.Loader.loadBytes()
JPEGLoaderContext + The JPEGLoaderContext class includes a property for enabling a deblocking filter when loading a JPEG image.flash.system:LoaderContext + The JPEGLoaderContext class includes a property for enabling a deblocking filter when loading a JPEG image. + The deblocking filter improves an image's quality at higher compression settings by smoothing neighboring pixels. + To apply deblocking when loading a JPEG image, create a JPEGLoaderContext object, and set its + deblockingFilter property. Then use the JPEGLoaderContext object name as the value of the + context parameter of the load() method of the Loader object used to load the image. + +

The JPEGLoaderContext class extends the LoaderContext class. Set the checkPolicyFile + property to true if you need programmatic access to the pixels of the loaded image + (for example, if you're using the BitmapData.draw() method). Setting the checkPolicyFile + property is not necessary for AIR content running in the application sandbox.

+ +
flash.display.Loader.load()flash.display.BitmapData.draw()JPEGLoaderContext + Creates a new JPEGLoaderContext object with the specified settings.deblockingFilterNumber0.0Specifies the strength of the deblocking filter. A value of 1.0 + applies a full strength deblocking filter, a value of 0.0 disables the deblocking filter. + + checkPolicyFileBooleanfalseSpecifies whether Flash Player should check for the existence + of a URL policy file before loading the object. Does not apply for AIR content running in the application sandbox. + + applicationDomainflash.system:ApplicationDomainnullSpecifies the ApplicationDomain object to use for a Loader object. + + securityDomainflash.system:SecurityDomainnullSpecifies the SecurityDomain object to use for a Loader object. + + + Creates a new JPEGLoaderContext object with the specified settings. + + flash.system.LoaderContextflash.display.Loader.load()flash.display.Loader.loadBytes()flash.system.ApplicationDomainflash.system.SecurityDomaindeblockingFilter + Specifies the strength of the deblocking filter.0.0Number + Specifies the strength of the deblocking filter. A value of 1.0 + applies a full strength deblocking filter, a value of 0.0 disables the deblocking filter. + +
Capabilities + The Capabilities class provides properties that + describe the system and runtime that are hosting the application.Object + The Capabilities class provides properties that + describe the system and runtime that are hosting the application. + For example, a mobile phone's screen might be 100 square + pixels, black and white, whereas a PC screen might be 1000 square pixels, color. + By using the Capabilities class to determine what capabilities the client has, + you can provide appropriate content to as many users as possible. When you know + the device's capabilities, you can tell the server to send the appropriate SWF + files or tell the SWF file to alter its presentation. + + + +

However, some capabilities of Adobe AIR are not listed as properties in the + Capabilities class. They are properties of other classes:

+ + PropertyDescriptionNativeApplication.supportsDockIconWhether the operating system supports application doc icons.NativeApplication.supportsMenuWhether the operating system supports a global application menu bar.NativeApplication.supportsSystemTrayIconWhether the operating system supports system tray icons.NativeWindow.supportsMenuWhether the operating system supports window menus.NativeWindow.supportsTransparencyWhether the operating system supports transparent windows. + +

Do not use Capabilities.os or Capabilities.manufacturer to + determine a capability based on the operating system. Basing a capability on the operating system + is a bad idea, since it can lead to problems if an application does not consider all potential + target operating systems. Instead, use the property corresponding to the capability for which you + are testing.

+ +

You can send capabilities information, which is stored in the + Capabilities.serverString property as a URL-encoded string, using the + GET or POST HTTP method. The following example shows a server + string for a computer that has MP3 support and 1600 x 1200 pixel resolution and that is + running Windows XP with an input method editor (IME) installed:

+ +
A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&
+     SB=f&DEB=t&V=WIN%209%2C0%2C0%2C0&M=Adobe%20Windows&
+     R=1600x1200&DP=72&COL=color&AR=1.0&OS=Windows%20XP&
+     L=en&PT=External&AVD=f&LFD=f&WD=f&IME=t
+ +

The following table lists the properties of the Capabilities class and corresponding server strings: + Capabilities class propertyServer stringavHardwareDisableAVDhasAccessibilityACChasAudioAhasAudioEncoderAEhasEmbeddedVideoEVhasIMEIMEhasMP3MP3hasPrintingPRhasScreenBroadcastSBhasScreenPlaybackSPhasStreamingAudioSAhasStreamingVideoSVhasTLSTLShasVideoEncoderVEisDebuggerDEBlanguageLlocalFileReadDisableLFDmanufacturerMmaxLevelIDCMLosOSpixelAspectRatioARplayerTypePTscreenColorCOLscreenDPIDPscreenResolutionXRscreenResolutionYRversionV +

+ +

There is also a WD server string that specifies whether windowless mode is disabled. Windowless mode + can be disabled in Flash Player due to incompatibility with the web browser or to a user setting in the mms.cfg file. + There is no corresponding Capabilities property.

+ +

All properties of the Capabilities class are read-only.

+ +
The following example outputs the values found in the + flash.system.Capabilities object. First, it outputs the values into a text field. + Then, it outputs the values using several calls to trace(). + + +package { + import flash.display.Sprite; + import flash.system.Capabilities; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class CapabilitiesExample extends Sprite { + + public function CapabilitiesExample() { + showCapabilities(); + } + + private function showCapabilities():void { + var tf:TextField = new TextField(); + tf.height = 600; + tf.width = 400; + tf.autoSize = TextFieldAutoSize.LEFT; + tf.wordWrap = true; + + tf.text = "avHardwareDisable: " + Capabilities.avHardwareDisable + + + "\nhasAccessibility: " + Capabilities.hasAccessibility + + "\nhasAudio: " + Capabilities.hasAudio + + "\nhasAudioEncoder: " + Capabilities.hasAudioEncoder + + "\nhasEmbeddedVideo: " + Capabilities.hasEmbeddedVideo + + "\nhasIME: " + Capabilities.hasIME + + "\nhasMP3: " + Capabilities.hasMP3 + + "\nhasPrinting: " + Capabilities.hasPrinting + + "\nhasScreenBroadcast: " + Capabilities.hasScreenBroadcast + + "\nhasScreenPlayback: " + Capabilities.hasScreenPlayback + + "\nhasStreamingAudio: " + Capabilities.hasStreamingAudio + + "\nhasStreamingVideo: " + Capabilities.hasStreamingVideo + + "\nhasTLS: " + Capabilities.hasTLS + + "\nhasVideoEncoder: " + Capabilities.hasVideoEncoder + + "\nisDebugger: " + Capabilities.isDebugger + + "\nisEmbeddedInAcrobat: " + Capabilities.isEmbeddedInAcrobat + + "\nlanguage: " + Capabilities.language + + "\nlocalFileReadDisable: " + Capabilities.localFileReadDisable + + "\nmanufacturer: " + Capabilities.manufacturer + + "\nmaxLevelIDC: " + Capabilities.maxLevelIDC + + "\nos: " + Capabilities.os + + "\npixelAspectRatio: " + Capabilities.pixelAspectRatio + + "\nplayerType: " + Capabilities.playerType + + "\nscreenColor: " + Capabilities.screenColor + + "\nscreenDPI: " + Capabilities.screenDPI + + "\nscreenResolutionX: " + Capabilities.screenResolutionX + + "\nscreenResolutionY: " + Capabilities.screenResolutionY + + "\nserverString: " + Capabilities.serverString + + "\ntouchscreenType: " + Capabilities.touchscreenType + + + // The following capabilities are supported only when publishing for AIR. + // If you are publishing for AIR, uncomment the following lines. + //"\nlanguages: " + Capabilities.languages + + //"\ncpuArchitecture: " + Capabilities.cpuArchitecture + + //"\nsupports32BitProcesses: " + Capabilities.supports32BitProcesses + + //"\nsupports64BitProcesses: " + Capabilities.supports64BitProcesses + + + "\nversion: " + Capabilities.version; + + addChild(tf); + + trace("avHardwareDisable: " + Capabilities.avHardwareDisable); + trace("hasAccessibility: " + Capabilities.hasAccessibility); + trace("hasAudio: " + Capabilities.hasAudio); + trace("hasAudioEncoder: " + Capabilities.hasAudioEncoder); + trace("hasEmbeddedVideo: " + Capabilities.hasEmbeddedVideo); + trace("hasIME: " + Capabilities.hasIME); + trace("hasMP3: " + Capabilities.hasMP3); + trace("hasPrinting: " + Capabilities.hasPrinting); + trace("hasScreenBroadcast: " + Capabilities.hasScreenBroadcast); + trace("hasScreenPlayback: " + Capabilities.hasScreenPlayback); + trace("hasStreamingAudio: " + Capabilities.hasStreamingAudio); + trace("hasStreamingVideo: " + Capabilities.hasStreamingVideo); + trace("hasTLS: " + Capabilities.hasTLS); + trace("hasVideoEncoder: " + Capabilities.hasVideoEncoder); + trace("isDebugger: " + Capabilities.isDebugger); + trace("isEmbeddedInAcrobat: " + Capabilities.isEmbeddedInAcrobat); + trace("language: " + Capabilities.language); + trace("localFileReadDisable: " + Capabilities.localFileReadDisable); + trace("manufacturer: " + Capabilities.manufacturer); + trace("maxLevelIDC: " + Capabilities.maxLevelIDC); + trace("os: " + Capabilities.os); + trace("pixelAspectRatio: " + Capabilities.pixelAspectRatio); + trace("playerType: " + Capabilities.playerType); + trace("screenColor: " + Capabilities.screenColor); + trace("screenDPI: " + Capabilities.screenDPI); + trace("screenResolutionX: " + Capabilities.screenResolutionX); + trace("screenResolutionY: " + Capabilities.screenResolutionY); + trace("serverString: " + Capabilities.serverString); + trace("touchscreenType: " + Capabilities.touchscreenType); + + // The following capabilities are supported only when publishing for AIR. + // If you are publishing for AIR, uncomment the following lines. + //trace("cpuArchitecture: " + Capabilities.cpuArchitecture); + //trace("languages: " + Capabilities.languages); + //trace("supports32BitProcesses: " + Capabilities.supports32BitProcesses); + //trace("supports64BitProcesses: " + Capabilities.supports64BitProcesses); + + trace("version: " + Capabilities.version); + + } + } +} + +
avHardwareDisable + Specifies whether access to the user's camera and microphone has + been administratively prohibited (true) or allowed (false).Boolean + Specifies whether access to the user's camera and microphone has + been administratively prohibited (true) or allowed (false). + The server string is AVD. + +

For content in Adobe AIR™, this property applies only to content in security + sandboxes other than the application security sandbox. Content in the application + security sandbox can always access the user's camera and microphone.

+ +
flash.media.Camera.getCamera()flash.media.Microphone.getMicrophone()Security.showSettings()
cpuArchitecture + Specifies the current CPU architecture.String + Specifies the current CPU architecture. The cpuArchitecture property + can return the following strings: "PowerPC", "x86", + "SPARC", and "ARM". + The server string is ARCH. + + hasAccessibility + Specifies whether the system supports + (true) or does not support (false) communication + with accessibility aids.Boolean + Specifies whether the system supports + (true) or does not support (false) communication + with accessibility aids. + The server string is ACC. + + flash.accessibility.Accessibility.activeflash.accessibility.Accessibility.updateProperties()hasAudioEncoder + Specifies whether the system can (true) or cannot (false) + encode an audio stream, such as that coming from a microphone.Boolean + Specifies whether the system can (true) or cannot (false) + encode an audio stream, such as that coming from a microphone. + The server string is AE. + + hasAudio + Specifies whether the system has audio + capabilities.Boolean + Specifies whether the system has audio + capabilities. This property is always true. The server + string is A. + + hasEmbeddedVideo + Specifies whether the system supports + (true) or does not support (false) + embedded video.Boolean + Specifies whether the system supports + (true) or does not support (false) + embedded video. The server string is EV. + + hasIME + Specifies whether the system does (true) + or does not (false) have an input method editor (IME) installed.Boolean + Specifies whether the system does (true) + or does not (false) have an input method editor (IME) installed. + The server string is IME. + + flash.system.IMEflash.system.System.imehasMP3 + Specifies whether the system does (true) + or does not (false) have an MP3 decoder.Boolean + Specifies whether the system does (true) + or does not (false) have an MP3 decoder. + The server string is MP3. + + hasPrinting + Specifies whether the system does (true) + or does not (false) support printing.Boolean + Specifies whether the system does (true) + or does not (false) support printing. + The server string is PR. + + hasScreenBroadcast + Specifies whether the system does (true) or does not (false) + support the development of screen broadcast applications to be run through Flash Media + Server.Boolean + Specifies whether the system does (true) or does not (false) + support the development of screen broadcast applications to be run through Flash Media + Server. + The server string is SB. + + hasScreenPlayback + Specifies whether the system does (true) or does not + (false) support the playback of screen broadcast applications + that are being run through Flash Media Server.Boolean + Specifies whether the system does (true) or does not + (false) support the playback of screen broadcast applications + that are being run through Flash Media Server. + The server string is SP. + + hasStreamingAudio + Specifies whether the system can (true) or cannot (false) + play streaming audio.Boolean + Specifies whether the system can (true) or cannot (false) + play streaming audio. + The server string is SA. + + hasStreamingVideo + Specifies whether the system can (true) or cannot + (false) play streaming video.Boolean + Specifies whether the system can (true) or cannot + (false) play streaming video. + The server string is SV. + + hasTLS + Specifies whether the system supports native SSL sockets through NetConnection + (true) or does not (false).Boolean + Specifies whether the system supports native SSL sockets through NetConnection + (true) or does not (false). + The server string is TLS. + + flash.net.NetConnection.connectedProxyTypeflash.net.NetConnection.proxyTypeflash.net.NetConnection.usingTLShasVideoEncoder + Specifies whether the system can (true) or cannot + (false) encode a video stream, such as that coming + from a web camera.Boolean + Specifies whether the system can (true) or cannot + (false) encode a video stream, such as that coming + from a web camera. + The server string is VE. + + isDebugger + Specifies whether the system is a special debugging version + (true) or an officially released version (false).Boolean + Specifies whether the system is a special debugging version + (true) or an officially released version (false). + The server string is DEB. This property is set to true + when running in the debug version of Flash Player or + the AIR Debug Launcher (ADL). + + isEmbeddedInAcrobat + Specifies whether the Flash runtime is embedded in a PDF file that is open in Acrobat 9.0 or higher + (true) or not (false).Boolean + Specifies whether the Flash runtime is embedded in a PDF file that is open in Acrobat 9.0 or higher + (true) or not (false). + + languages + An array of strings that contain information about the user's preferred user interface languages, as set + through the operating system.Array + An array of strings that contain information about the user's preferred user interface languages, as set + through the operating system. The strings will contain language tags (and script and region information, + where applicable) defined by RFC4646 + (http://www.ietf.org/rfc/rfc4646.txt) + and will use dashes as a delimiter (for example, "en-US" or "ja-JP"). + Languages are listed in the array in the order of preference, as determined by the operating system + settings. + +

Operating systems differ in region information returned in locale strings. One operating system + may return "en-us", whereas another may return "en".

+ +

The first entry in the returned array generally has the same primary language ID + as the Capabilities.language property. For example, if Capabilities.languages[0] + is set to "en-US", then the language property is set to "en". + However, if the Capabilities.language property is set to "xu" (specifying + an unknown language), the first element in this array will be different. For this reason, + Capabilities.languages[0] can be more accurate than Capabilities.language.

+ +

The server string is LS.

+ +
language + Specifies the language code of the system on which the content is running.String + Specifies the language code of the system on which the content is running. The language is + specified as a lowercase two-letter language code from ISO 639-1. For Chinese, an additional + uppercase two-letter country code from ISO 3166 distinguishes between Simplified and + Traditional Chinese. The languages codes are based on the English names of the language: for example, + hu specifies Hungarian. + +

On English systems, this property returns only the language code (en), not + the country code. On Microsoft Windows systems, this property returns the user interface (UI) + language, which refers to the language used for all menus, dialog boxes, error messages, and help + files. The following table lists the possible values: + + LanguageValueCzechcsDanishdaDutchnlEnglishenFinnishfiFrenchfrGermandeHungarianhuItalianitJapanesejaKoreankoNorwegiannoOther/unknownxuPolishplPortugueseptRussianruSimplified Chinesezh-CNSpanishesSwedishsvTraditional Chinesezh-TWTurkishtr +

+ +

Note: The value of Capabilities.language property is limited + to the possible values on this list. Because of this limitation, Adobe AIR applications + should use the first element in the Capabilities.languages + array to determine the primary user interface language for the system.

+ +

The server string is L.

+ +
In the following example, the content that is displayed depends on the language of the user's operating + system. + +

The Capabilities.language property returns the ISO 639-1 language code + (for example, "en" for English). The switch statement checks for the language code and sets + the content of the myTextField text field to a greeting specific to the + language. If the language code is not supported by the example, the default error string + is returned.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.system.Capabilities; + + public class Capabilities_languageExample extends Sprite { + + public function Capabilities_languageExample() { + var myTextField:TextField = new TextField(); + myTextField.x = 10; + myTextField.y = 10; + myTextField.background = true; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + var greetingEnglish:String = "Hello World"; + var greetingGerman:String = "Hallo Welt"; + var greetingFrench:String = "Bonjour Monde"; + var greetingSpanish:String = "Hola Mundo"; + + var lang:String = Capabilities.language; + + switch (lang) { + case "en": + myTextField.text = greetingEnglish; + break; + case "de": + myTextField.text = greetingGerman; + break; + case "fr": + myTextField.text = greetingFrench; + break; + case "es": + myTextField.text = greetingSpanish; + break; + default: + myTextField.text = "Sorry your system's language is not supported at this time."; + } + + this.addChild(myTextField); + } + } +} +
languages
localFileReadDisable + Specifies whether read access to the user's hard disk has been + administratively prohibited (true) or allowed + (false).Boolean + Specifies whether read access to the user's hard disk has been + administratively prohibited (true) or allowed + (false). For content in Adobe AIR, this property + applies only to content in security sandboxes other + than the application security sandbox. (Content in the application + security sandbox can always read from the file system.) + If this property is true, + Flash Player cannot read files (including the first file that + Flash Player launches with) from the user's hard disk. + If this property is true, AIR content outside of the + application security sandbox cannot read files from the user's + hard disk. For example, attempts to read a file on the user's + hard disk using load methods will fail if this property + is set to true. + +

Reading runtime shared libraries is also blocked + if this property is set to true, but reading local shared objects + is allowed without regard to the value of this property.

+ +

The server string is LFD.

+ + +
flash.display.Loader
manufacturer + Specifies the manufacturer of the running version of + Flash Player or the AIR runtime, in the format "Adobe + OSName".String + Specifies the manufacturer of the running version of + Flash Player or the AIR runtime, in the format "Adobe + OSName". The value for OSName + could be "Windows", "Macintosh", + "Linux", or another operating system name. The server string is M. + +

Do not use Capabilities.manufacturer to determine a capability based on + the operating system if a more specific capability property exists. Basing a capability on the operating + system is a bad idea, since it can lead to problems if an application does not consider all potential + target operating systems. Instead, use the property corresponding to the capability for which you + are testing. For more information, see the Capabilities class description.

+ +
maxLevelIDC + Retrieves the highest H.264 Level IDC that the client hardware supports.String + Retrieves the highest H.264 Level IDC that the client hardware supports. + Media run at this level are guaranteed to run; however, media run at + the highest level might not run with the highest quality. + This property is useful for servers trying to target a client's capabilities. + Using this property, a server can determine the level of video to send to the client. + +

The server string is ML.

+ +
os + Specifies the current operating system.String + Specifies the current operating system. The os property + can return the following strings: + + Operating systemValueWindows 7"Windows 7"Windows Vista"Windows Vista"Windows Server 2008 R2"Windows Server 2008 R2"Windows Server 2008"Windows Server 2008"Windows Home Server"Windows Home Server"Windows Server 2003 R2"Windows Server 2003 R2"Windows Server 2003"Windows Server 2003"Windows XP 64"Windows Server XP 64"Windows XP"Windows XP"Windows 98"Windows 98"Windows 95"Windows 95"Windows NT"Windows NT"Windows 2000"Windows 2000"Windows ME"Windows ME"Windows CE"Windows CE"Windows SmartPhone"Windows SmartPhone"Windows PocketPC"Windows PocketPC"Windows CEPC"Windows CEPC"Windows Mobile"Windows Mobile"Mac OS"Mac OS X.Y.Z" (where X.Y.Z is the version number, for example: + "Mac OS 10.5.2")Linux"Linux" (Flash Player attaches the Linux version, such as "Linux 2.6.15-1.2054_FC5smp"iPhone OS 4.1"iPhone3,1" + +

The server string is OS.

+ +

Do not use Capabilities.os to determine a capability based on + the operating system if a more specific capability property exists. Basing a capability on the operating + system is a bad idea, since it can lead to problems if an application does not consider all potential + target operating systems. Instead, use the property corresponding to the capability for which you + are testing. For more information, see the Capabilities class description.

+ +
pixelAspectRatio + Specifies the pixel aspect ratio of the screen.Number + Specifies the pixel aspect ratio of the screen. The server string + is AR. + + playerType + Specifies the type of runtime environment.String + Specifies the type of runtime environment. This property can have one of the following + values: + +
  • "ActiveX" for the Flash Player ActiveX control used by Microsoft Internet Explorer
  • "Desktop" for the Adobe AIR runtime (except for SWF content loaded by an HTML page, which + has Capabilities.playerType set to "PlugIn")
  • "External" for the external Flash Player or in test mode
  • "PlugIn" for the Flash Player browser plug-in (and for SWF content loaded by + an HTML page in an AIR application)
  • "StandAlone" for the stand-alone Flash Player
+

The server string is PT.

+ +
screenColor + Specifies the screen color.String + Specifies the screen color. This property can have the value + "color", "gray" (for grayscale), or + "bw" (for black and white). + The server string is COL. + + screenDPI + Specifies the dots-per-inch (dpi) resolution of the screen, in pixels.Number + Specifies the dots-per-inch (dpi) resolution of the screen, in pixels. + The server string is DP. + + screenResolutionX + Specifies the maximum horizontal resolution of the screen.Number + Specifies the maximum horizontal resolution of the screen. + The server string is R (which returns both the width and height of the screen). + This property does not update with a user's screen resolution and instead only indicates the resolution + at the time Flash Player or an Adobe AIR application started. + Also, the value only specifies the primary screen. + + screenResolutionY + Specifies the maximum vertical resolution of the screen.Number + Specifies the maximum vertical resolution of the screen. + The server string is R (which returns both the width and height of the screen). + This property does not update with a user's screen resolution and instead only indicates the resolution + at the time Flash Player or an Adobe AIR application started. + Also, the value only specifies the primary screen. + + The following example is a simple test that indicates the current screen resolution and operating system version. + When testing this example, click the text field to see the property values: + +import flash.events.~; +import flash.display.~; +import flash.system.Capabilities; +import flash.text.TextField; + +var screenInfoTxt:TextField = new TextField(); +var screenInfoTxt.x = 30; +var screenInfoTxt.y = 50; +var screenInfoTxt.width = 300; +var screenInfoTxt.height = 100; +var screenInfoTxt.border = true; + +addChild(screenInfoTxt); + +addEventListener(MouseEvent.CLICK, getScreenNVersion); + +function getScreenNVersion(e:MouseEvent):void{ + screenInfoTxt.text= "flash.system.Capabilities.screenResolutionX is : " + String(flash.system.Capabilities.screenResolutionX) + "\n" + + "flash.system.Capabilities.screenResolutionY is : " + String(flash.system.Capabilities.screenResolutionY) + "\n" + + "flash.system.Capabilities.version is : " + flash.system.Capabilities.version; +} +serverString + A URL-encoded string that specifies values for each Capabilities + property.String + A URL-encoded string that specifies values for each Capabilities + property. + +

The following example shows a URL-encoded string: +

A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&
+	 SB=f&DEB=t&V=WIN%208%2C5%2C0%2C208&M=Adobe%20Windows&
+	 R=1600x1200&DP=72&COL=color&AR=1.0&OS=Windows%20XP&
+	 L=en&PT=External&AVD=f&LFD=f&WD=f

+ +
supports32BitProcesses + Specifies whether the system supports running 32-bit processes.Boolean + Specifies whether the system supports running 32-bit processes. + The server string is PR32. + + supports64BitProcesses + Specifies whether the system supports running 64-bit processes.Boolean + Specifies whether the system supports running 64-bit processes. + The server string is PR64. + + touchscreenType + Specifies the type of touchscreen supported, if any.String + Specifies the type of touchscreen supported, if any. Values are defined in the flash.system.TouchscreenType class. + + The following example is a simple test that indicates the current type of touch screen. + When testing this example, click a text field to see the property values: + +import flash.events.~~; +import flash.display.~~; +import flash.system.Capabilities; +import flash.text.TextField; + +var capabilitiesTouchScreenTypeTxt:TextField = new TextField(); +capabilitiesTouchScreenTypeTxt.width = 300; +capabilitiesTouchScreenTypeTxt.border = true; + +addChild(capabilitiesTouchScreenTypeTxt); + +addEventListener(MouseEvent.CLICK, getScreenKeyboardType); + +function getScreenKeyboardType(e:MouseEvent):void{ + capabilitiesTouchScreenTypeTxt.text= "flash.system.Capabilities.touchscreenType is : " + flash.system.Capabilities.touchscreenType; +} +TouchscreenType classflash.ui.Mouse.supportsCursorversion + Specifies the Flash Player or Adobe&#xAE; AIR&#xAE; + platform and version information.String + Specifies the Flash Player or Adobe® AIR® + platform and version information. The format of the version number is: + platform majorVersion,minorVersion,buildNumber,internalBuildNumber. + Possible values for platform are "WIN", ` + "MAC", "LNX", and "AND". Here are some + examples of version information: + +
+	 WIN 9,0,0,0  // Flash Player 9 for Windows
+	 MAC 7,0,25,0   // Flash Player 7 for Macintosh
+	 LNX 9,0,115,0  // Flash Player 9 for Linux
+	 AND 10,2,150,0 // Flash Player 10 for Android
+	 
+ +

Do not use Capabilities.version to determine a capability based on + the operating system if a more specific capability property exists. Basing a capability on the operating + system is a bad idea, since it can lead to problems if an application does not consider all potential + target operating systems. Instead, use the property corresponding to the capability for which you + are testing. For more information, see the Capabilities class description.

+ +

The server string is V.

+ +
The following example is a simple test that indicates the current screen resolution and operating system version. + When testing this example, click the text field to see the property values: + +import flash.events.~; +import flash.display.~; +import flash.system.Capabilities; +import flash.text.TextField; + +var screenInfoTxt:TextField = new TextField(); +var screenInfoTxt.x = 30; +var screenInfoTxt.y = 50; +var screenInfoTxt.width = 300; +var screenInfoTxt.height = 100; +var screenInfoTxt.border = true; + +addChild(screenInfoTxt); + +addEventListener(MouseEvent.CLICK, getScreenNVersion); + +function getScreenNVersion(e:MouseEvent):void{ + screenInfoTxt.text= "flash.system.Capabilities.screenResolutionX is : " + String(flash.system.Capabilities.screenResolutionX) + "\n" + + "flash.system.Capabilities.screenResolutionY is : " + String(flash.system.Capabilities.screenResolutionY) + "\n" + + "flash.system.Capabilities.version is : " + flash.system.Capabilities.version; +} +
fscommand + Lets the SWF file communicate with either Flash Player or the program hosting Flash Player, + such as a web browser.If the function is not called in response to a user action, such as a mouse + event or keypress event. + + ErrorErrorcommandStringA string passed to the host application for any use, or a command passed to Flash Player. + + argsStringA string passed to the host application for any use, or a value passed to Flash Player. + + + Lets the SWF file communicate with either Flash Player or the program hosting Flash Player, + such as a web browser. You can also use the fscommand() function to pass messages to + Director or to Visual Basic, Visual C++, and other programs that can host ActiveX controls. + + +

The fscommand() function lets a SWF file communicate with a script in a web page. + However, script access is controlled by the web page's allowScriptAccess setting. + (You set this attribute in the HTML code that embeds the SWF file—for + example, in the PARAM tag for Internet Explorer or the EMBED tag for Netscape.)

+
  • When allowScriptAccess is set to "sameDomain" (the default), + scripting is allowed only from SWF files that are in the same domain as the web page.
  • When allowScriptAccess is set to "always", + the SWF file can communicate with the HTML page in which it is embedded + even when the SWF file is from a different domain than the HTML page.
  • When allowScriptAccess is set to "never", + the SWF file cannot communicate with any HTML page. Note that using this value is deprecated and not recommended, + and shouldn't be necessary if you don't serve untrusted SWF files from your own domain. + If you do need to serve untrusted SWF files, Adobe recommends that you create a distinct subdomain + and place all untrusted content there.
+ +

You can prevent a SWF file from using this method by setting the + allowNetworking parameter of the the object and embed + tags in the HTML page that contains the SWF content.

+ +

The fscommand() function is not allowed if the calling SWF file is in + the local-with-file-system or local-with-network sandbox and the containing HTML page is in + an untrusted sandbox.

+ +

For more information related to security, see the Flash Player Developer Center Topic: + Security.

+ +

Usage 1: To use fscommand() to send a message to Flash Player, you must use predefined commands and parameters. The + following table shows the values that you can specify for the fscommand() function's command and + args parameters. These values control SWF files that are playing in Flash Player, including projectors. (A + projector is a SWF file saved in a format that can run as a stand-alone application—that is, without Flash Player.)

+ + CommandParameter (args)PurposequitNoneCloses the projector.fullscreentrue or falseSpecifying true sets Flash Player to full-screen mode. Specifying + false returns the player to normal menu view.allowscaletrue or falseSpecifying false sets the player so that the SWF file is always drawn + at its original size and never scaled. Specifying true forces the SWF file to scale to 100% of the + player.showmenutrue or falseSpecifying true enables the full set of context menu items. Specifying + false hides all of the context menu items except About Flash Player and Settings.execPath to application Executes an application from within the projector.trapallkeystrue or falseSpecifying true sends all key events, including accelerator keys, to + the onClipEvent(keyDown/keyUp) handler in Flash Player. +

Not all of the commands listed in the table are available in all applications: +

  • None of the commands are available in web players.
  • All of the commands are available in stand-alone projector applications.
  • AIR applications should use the flash.desktop.NativeApplication class for similar functions, such as + NativeApplication.nativeApplication.exit() instead of fscommand("quit").
  • Only allowscale and exec are available in test-movie players.
+

+ +

The exec command can contain only the characters A-Z, a-z, 0-9, period (.), and underscore (_). The exec + command runs in the subdirectory fscommand only. In other words, if you use the exec command to call an application, the + application must reside in a subdirectory named fscommand. The exec command works only from within a Flash projector + file.

+ +

Usage 2: To use fscommand() to send a message to a scripting language such as JavaScript in a web browser, you can + pass any two parameters in the command and args parameters. These parameters can be strings or + expressions, and they are used in a JavaScript function that handles, or catches, the fscommand() function.

+ +

In a web browser, fscommand() calls the JavaScript function moviename_DoFScommand, which resides in the + web page that contains the SWF file. For moviename, supply the name of the Flash object that you used for the + NAME attribute of the EMBED tag or the ID property of the OBJECT tag. If you assign the SWF file + the name "myMovie", the JavaScript function myMovie_DoFScommand is called.

+ +

In the web page that contains the SWF file, set the allowScriptAccess attribute to allow or deny the SWF file's + ability to access the web page, as described above. (You set this attribute in the HTML code that embeds the SWF file—for example, in the + PARAM tag for Internet Explorer or the EMBED tag for Netscape.)

+ +

In Flash Player 10 and later running in a browser, using this method programmatically to + open a pop-up window may not be successful. Various browsers (and browser configurations) may block pop-up windows + at any time; it is not possible to guarantee any pop-up window will appear. + However, for the best chance of success, use this method to open a pop-up window only in code that executes + as a direct result of a user action (for example, in an event handler for a mouse click or key-press event.)

+ +

Usage 3: The fscommand() function can send messages to Director (Macromedia Director from Adobe). + These messages are interpreted by Lingo (the Director scripting language) as strings, events, or executable Lingo + code. If a message is a string or an event, you must write the Lingo code to receive the message from the + fscommand() function and carry out an action in Director. For more information, see the Director Support + Center at www.adobe.com/support/director/.

+ +

Usage 4: In VisualBasic, Visual C++, and other programs that can host ActiveX controls, fscommand() sends a VB event + with two strings that can be handled in the environment's programming language. For more information, use the keywords "Flash method" + to search the Flash Support Center at www.adobe.com/support/flash/.

+

Note: The ExternalInterface class provides better functionality + for communication between JavaScript and ActionScript (Usage 2) and between ActionScript and VisualBasic, Visual C++, or other + programs that can host ActiveX controls (Usage 4). You should continue to use fscommand() for sending messages to Flash + Player (Usage 1) and Director (Usage 3).

+ +
The following example shows how fscommand() can be used to direct + Flash Player to go into full screen mode and not allow scaling. An orange box is then + added to the stage using draw(). In draw(), a click + event listener is added named clickHandler(), which responds to click + events by directing Flash Player to exit using another call to fscommand(). + +

Note: this example should be executed in the standalone Flash Player and + not within a web browser.

+ +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.system.fscommand; + import flash.events.MouseEvent; + + public class FSCommandExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 100; + + public function FSCommandExample() { + fscommand("fullscreen", "true"); + fscommand("allowscale", "false"); + draw(); + } + + private function clickHandler(event:MouseEvent):void { + fscommand("quit"); + trace("clickHandler"); + } + + private function draw():void { + var child:Sprite = new Sprite(); + child.graphics.beginFill(bgColor); + child.graphics.drawRect(0, 0, size, size); + child.graphics.endFill(); + child.buttonMode = true; + addEventListener(MouseEvent.CLICK, clickHandler); + + var label:TextField = new TextField(); + label.text = "quit"; + label.selectable = false; + label.mouseEnabled = false; + child.addChild(label); + + addChild(child); + } + } +} +
flash.desktop.NativeApplication
IME + The IME class lets you directly manipulate the operating system's input method + editor (IME) in the Flash runtime application that is running on a client computer.Lets you directly manipulate the operating system's input method editor (IME). + + flash.events:EventDispatcher + The IME class lets you directly manipulate the operating system's input method + editor (IME) in the Flash runtime application that is running on a client computer. You can + determine whether an IME is installed, whether or not the IME is currently enabled, and which IME is + enabled. You can disable or enable the IME in the application, and you can perform other limited + functions, depending on the operating system. + + +

AIR profile support: This feature is supported + on desktop operating systems, but it is not supported on all mobile devices. It is also not supported on + AIR for TV devices. You can test for support at run time using the IME.isSupported property. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

IMEs let users type non-ASCII text characters in multibyte languages + such as Chinese, Japanese, and Korean. For more information on working with IMEs, see the + documentation for the operating system for which you are developing applications. + For additional resources, see the following websites: +

  • http://www.microsoft.com/globaldev/default.mspx
  • http://developer.apple.com/documentation/
  • http://java.sun.com
+

+ +

If an IME is not active on the user's computer, calls to IME methods or properties, + other than Capabilities.hasIME, will fail. Once you manually activate an IME, subsequent ActionScript + calls to IME methods and properties will work as expected. For example, if you are using a + Japanese IME, it must be activated before any IME method or property is called.

+ +

The following table shows the platform coverage of this class:

+ + + CapabilityWindowsMac OSXLinuxDetermine whether the IME is installed: Capabilities.hasIMEYesYesYesSet IME on or off: IME.enabledYesYesYesFind out whether IME is on or off: IME.enabledYesYesYesGet or set IME conversion mode: IME.conversionModeYesYes ~~~~NoSend IME the string to be converted: IME.setCompositionString()Yes ~~NoNoGet from IME the original string before conversion: System.ime.addEventListener()Yes ~~NoNoSend request to convert to IME: IME.doConversion()Yes ~~NoNo + +

~~ Not all Windows IMEs support all of these operations. The only IME + that supports them all is the Japanese IME.

+ +

~~~~ On the Macintosh, only the Japanese IME supports these methods, and third-party IMEs do not support them.

+

The ActionScript 3.0 version of this class does not support Macintosh Classic.

+ +
imeComposition + Dispatched when a user has completed an + input method editor (IME) composition + and the reading string is available.flash.events.IMEEvent.IME_COMPOSITIONflash.events.IMEEvent + Dispatched when a user has completed an + input method editor (IME) composition + and the reading string is available. + IMEs are generally used to enter text from languages that have ideographs instead + of letters, such as Japanese, Chinese and Korean. + compositionAbandoned + Causes the runtime to abandon any composition that is in progress. + Causes the runtime to abandon any composition that is in progress. Call this method when the user clicks + outside of the composition area or when the interactive object that has focus is being destroyed or reset. + The runtime confirms the composition by calling confirmComposition() in the client. The + runtime also resets the IME to inform the operating system that the composition has been abandoned. + + compositionSelectionChanged + Call this method when the selection within the composition has been updated, either interactively or + programmatically.startintSpecifies the offset in bytes of the start of the selection. + endintSpecifies the offset in bytes of the end of the selection. + + + Call this method when the selection within the composition has been updated, either interactively or + programmatically. + + doConversion + Instructs the IME to select the first candidate for the current composition string.The call was not successful. + ErrorError + Instructs the IME to select the first candidate for the current composition string. + setCompositionString + Sets the IME composition string.The call is not successful. + ErrorErrorcompositionStringThe string to send to the IME. + + Sets the IME composition string. When this string is set, the user + can select IME candidates before committing the result to the text + field that currently has focus. +

If no text field has focus, this method fails and throws an error.

+ +
conversionMode + The conversion mode of the current IME.StringA set attempt was not successful. + ErrorError + The conversion mode of the current IME. + Possible values are IME mode string constants that indicate the conversion mode: +
  • ALPHANUMERIC_FULL
  • ALPHANUMERIC_HALF
  • CHINESE
  • JAPANESE_HIRAGANA
  • JAPANESE_KATAKANA_FULL
  • JAPANESE_KATAKANA_HALF
  • KOREAN
  • UNKNOWN (read-only value; this value cannot be set)
+
flash.system.IMEConversionMode.ALPHANUMERIC_FULLflash.system.IMEConversionMode.ALPHANUMERIC_HALFflash.system.IMEConversionMode.CHINESEflash.system.IMEConversionMode.JAPANESE_HIRAGANAflash.system.IMEConversionMode.JAPANESE_KATAKANA_FULLflash.system.IMEConversionMode.JAPANESE_KATAKANA_HALFflash.system.IMEConversionMode.KOREANflash.system.IMEConversionMode.UNKNOWN
enabled + Indicates whether the system IME is enabled (true) or disabled (false).BooleanA set attempt was not successful. + ErrorError + Indicates whether the system IME is enabled (true) or disabled (false). + An enabled IME performs multibyte input; a disabled IME performs alphanumeric input. + isSupported + The isSupported property is set to true if the IME class is + available on the current platform, otherwise it is set to false.Boolean + The isSupported property is set to true if the IME class is + available on the current platform, otherwise it is set to false. + + +
System + The System class contains properties related to local settings and operations.Object + The System class contains properties related to local settings and operations. Among these are + settings for camers and microphones, operations with shared objects and the use of the Clipboard. + +

Additional properties and methods are in other classes within the flash.system package: + the Capabilities class, the IME class, and the + Security class.

+ +

This class contains only static methods and properties. You cannot + create new instances of the System class.

+ +
The following example shows how to copy information about your system's total memory to the + system Clipboard using a call to System.totalMemory within a call to the + System.setClipboard() method. + +package { + import flash.display.Sprite; + import flash.system.System; + + public class SystemExample extends Sprite { + public function SystemExample() { + System.setClipboard("System.totalMemory: " + System.totalMemory); + } + } +} +
flash.system.Securityflash.events.IMEEventdisposeXML + Makes the specified XML object immediately available for garbage collection.nodeXMLXML reference that should be made available for garbage collection. + + Makes the specified XML object immediately available for garbage collection. + This method will remove parent and child connections between all the nodes + for the specified XML node. + + exit + Closes Flash Player.codeuintA value to pass to the operating system. Typically, if + the process exits normally, the value is 0. + + + Closes Flash Player. + +

For the standalone Flash Player debugger version only.

+ +

AIR applications should call the NativeApplication.exit() method to exit the application.

+ +
flash.desktop.NativeApplication.exit()
gc + Forces the garbage collection process. + Forces the garbage collection process. + +

For the Flash Player debugger version and AIR applications only. + In an AIR application, the System.gc() method is only enabled in content running in the AIR Debug Launcher + (ADL) or, in an installed applcation, in content in the application security sandbox.

+ +
pause + Pauses Flash Player or the AIR Debug Launcher (ADL). + Pauses Flash Player or the AIR Debug Launcher (ADL). + After calling this method, nothing in the application continues except the delivery of Socket events. + +

For the Flash Player debugger version or the AIR Debug Launcher (ADL) only.

+ +
resume()
resume + Resumes the application after calling System.pause(). + Resumes the application after calling System.pause(). + +

For the Flash Player debugger version or the AIR Debug Launcher (ADL) only.

+ +
pause()
setClipboard + Replaces the contents of the Clipboard with a specified text string.stringStringA plain-text string of characters to put on the system Clipboard, replacing its current contents (if any). + + + Replaces the contents of the Clipboard with a specified text string. + + + Replaces the contents of the Clipboard with a specified text string. This method works from any security + context when called as a result of a user event (such as a keyboard or input device event handler). + +

This method is provided for SWF content running in Flash Player 9. It allows only adding + String content to the Clipboard.

+ +

Flash Player 10 content and content in the application security sandbox in an AIR application can call + the Clipboard.setData() method.

+ +
flash.desktop.Clipboard
freeMemory + The amount of memory (in bytes) that is allocated to + Adobe&#xAE; Flash&#xAE; Player or + Adobe&#xAE; AIR&#xAE; and that is not in use.Number + The amount of memory (in bytes) that is allocated to + Adobe® Flash® Player or + Adobe® AIR® and that is not in use. This unused portion of + allocated memory (System.totalMemory) fluctuates as garbage collection takes place. + Use this property to monitor garbage collection. + + privateMemorytotalMemorytotalMemoryNumberime + The currently installed system IME.flash.system:IME + The currently installed system IME. + To register for imeComposition events, call + addEventListener() on this instance. + IMEConversionModeprivateMemory + The entire amount of memory (in bytes) used by an application.Number + The entire amount of memory (in bytes) used by an application. This is the amount of resident private memory for the entire process. + +

AIR developers should use this property to determine the entire memory consumption of an application.

+ +

For Flash Player, this includes the memory used by the container application, + such as the web browser.

+ +
freeMemorytotalMemorytotalMemoryNumber
totalMemoryNumber + The amount of memory (in bytes) currently in use that has been directly allocated by + Flash Player or AIR.Number + The amount of memory (in bytes) currently in use that has been directly allocated by + Flash Player or AIR. + +

This property is expressed as a Number, which allows higher values than the + System.totalMemory property, which is of type int.

+ +

This property does not return all memory used by an Adobe AIR application or by + the application (such as a browser) containing Flash Player content. The browser or + operating system may consume other memory. The System.privateMemory property reflects all memory used by + an application.

+ +
freeMemoryprivateMemorytotalMemory
totalMemory + The amount of memory (in bytes) currently in use that has been directly allocated by + Flash Player or AIR.uint + The amount of memory (in bytes) currently in use that has been directly allocated by + Flash Player or AIR. + +

This property does not return all memory used by an Adobe AIR application or by + the application (such as a browser) containing Flash Player content. The browser or + operating system may consume other memory. The System.privateMemory property reflects all memory used by + an application.

+ +

If the amount of memory allocated is greater than the maximum value for a uint object (uint.MAX_VALUE, + or 4,294,967,295), then this property is set to 0. The System.totalMemoryNumber property allows + larger values.

+ +
freeMemoryprivateMemorytotalMemoryNumber
useCodePage + A Boolean value that determines which code page to use to interpret external text files.Boolean + A Boolean value that determines which code page to use to interpret external text files. + When the property is set to false, external text files are interpretted as Unicode. + (These files must be encoded as Unicode when you save them.) When the property is set to + true, external text files are interpretted using the traditional code page of the + operating system running the application. The default value of useCodePage is false. + +

Text that you load as an external file (using Loader.load(), the URLLoader class or + URLStream) must have been saved as Unicode in order for the application to recognize it + as Unicode. To encode external files as Unicode, save the files in an application that + supports Unicode, such as Notepad on Windows.

+ +

If you load external text files that are not Unicode-encoded, set useCodePage to true. + Add the following as the first line of code of the file that + is loading the data (for Flash Professional, add it to the first frame):

+ +
System.useCodePage = true;
+ +

When this code is present, the application interprets external text + using the traditional code page of the operating system. + For example, this is generally CP1252 for an English Windows operating + system and Shift-JIS for a Japanese operating system.

+ +

If you set useCodePage to true, + Flash Player 6 and later treat text as Flash Player 5 does. (Flash Player 5 + treated all text as if it were in the traditional code page of the operating + system running the player.)

+ +

If you set useCodePage to true, remember that the + traditional code page of the operating system running the application must include + the characters used in your external text file in order to display your text. + For example, if you load an external text file that contains Chinese characters, + those characters cannot display on a system that uses the CP1252 code page because + that code page does not include Chinese characters.

+ +

To ensure that users on all platforms can view external text files used in your + application, you should encode all external text files as Unicode and leave + useCodePage set to false. This way, the application + (Flash Player 6 and later, or AIR) interprets the text as Unicode.

+ +
flash.display.Loader.load()
SecurityDomain + The SecurityDomain class represents the current security "sandbox," also known as a security domain.Object + The SecurityDomain class represents the current security "sandbox," also known as a security domain. + By passing an instance of this class to Loader.load(), you can request that loaded media be placed in + a particular sandbox. + currentDomain + Gets the current security domain.flash.system:SecurityDomain + Gets the current security domain. + + flash.display.Loader.load()flash.display.Loader.loadBytes()flash.system.LoaderContextSystemUpdater + + The SystemUpdater class allows you to update modules of the Flash Player, + such as the DRM module for Flash Access, as well as the Flash Player itself.flash.events:EventDispatcher + + The SystemUpdater class allows you to update modules of the Flash Player, + such as the DRM module for Flash Access, as well as the Flash Player itself. + Available modules are listed in the SystemUpdaterType class. + +

Flash Player identifies the need for a Flash-Access-module update by dispatching a NetStatusEvent event. + The event has a code property with a value of "DRM.UpdateNeeded". For updates to the Flash Access + module, user consent is not required. Listen for the event and initiate the update by calling + update("DRM").

+ +

Flash Player identifies the need for a player update by dispatching a StatusEvent event, with several + possible code property values (see the status event). For updates to the player, + user consent is required. Listen for the event and present the user with the option to update. The user must agree to the actual + update and initiate the update by, for example, clicking a button in the user interface. You can then + initiate the player update directly in ActionScript by calling update("SYSTEM").

+ +

Note: The SystemUpdater API is supported on all desktop platforms.

+ +
flash.system.SystemUpdaterTypecancel + Dispatched when an update of the player itself is cancelled by the user.flash.events.Event.CANCELflash.events.Event + Dispatched when an update of the player itself is cancelled by the user. + This event is dispatched only when an update of type SystemUpdaterType.SYSTEM + is requested and the user cancels the update. + + complete + Dispatched when the update completes.flash.events.Event.COMPLETEflash.events.Event + Dispatched when the update completes. + + securityError + Dispatched upon encountering a security error.flash.events.SecurityErrorEvent.SECURITY_ERRORflash.events.SecurityErrorEvent + Dispatched upon encountering a security error. + For example, a security error that can cause this event is if the player + tries to perform an update when an update is not permitted by security policy. + + ioError + Dispatched when an I/O error occurs.flash.events.IOErrorEvent.IO_ERRORflash.events.IOErrorEvent + Dispatched when an I/O error occurs. + For example, one error that can cause this event is a loss of Internet connectivity. + + progress + Dispatched to indicate download progress.flash.events.ProgressEvent.PROGRESSflash.events.ProgressEvent + Dispatched to indicate download progress. This event is like the + progress event in the Loader and URLLoader classes. + + status + Dispatched when the update fails.flash.events.StatusEvent.STATUSflash.events.StatusEvent + Dispatched when the update fails. An update can fail for one of the following reasons: +

  • The caller is running on an unsupported platform or architecture. In this case, + the value of the code property is "DRM.UpdateFailedNotSupported" and the value of the + level property is "error".
  • The requested update package cannot be located on the server. In this case, + the value of the code property is "DRM.UpdateFailedNotCurrentlyAvailable" and the + value of the level property is "error".
  • The Flash Access module is not installed. This error is similar to the "DRM.UpdateNeeded" code, + which is dispatched by NetStatusEvent. + However, in this case, a more recent version of Flash Player must be downloaded first. In this case, + the value of the code property is "DRM.UpdateNeededButIncompatible" and the value of the + level property is "error". To perform an update + of Flash Player, call SystemUpdater.update(SystemUpdaterType.SYSTEM).
  • The new DRM module could not be downloaded. In this case, + the value of the code property is "DRM.UpdateFailed" and the value of the + level property is "error".

+ +
open + Dispatched when an update begins.flash.events.Event.OPENflash.events.Event + Dispatched when an update begins. The update is complete when a 'complete' event is sent, + or when an IOErrorEvent, SecurityErrorEvent, or StatusEvent is sent. + SystemUpdater + Constructor. + Constructor. + cancel + Cancels an active update. + Cancels an active update. + + update + Begins an update of a given type.typeString + Begins an update of a given type. Update types are one of the string constants defined + in the SystemUpdaterType class. + Only one update is allowed at a time across all browsers. +

After the update begins, listen for the events defined in this class. The following events + events indicate the end of an update and allow a new update or update attempt to proceed, + as does calling the update() function:

+

  • complete
  • cancel
  • securityError
  • ioError
  • status

+ +
flash.system.SystemUpdaterType
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.text.engine.xml b/language-server/playerglobal_docs/flash.text.engine.xml new file mode 100644 index 0000000..458d9bf --- /dev/null +++ b/language-server/playerglobal_docs/flash.text.engine.xml @@ -0,0 +1,3843 @@ +flash.text.engineTextLine + + The TextLine class is used to display text on the display list.flash.display:DisplayObjectContainer + The TextLine class is used to display text on the display list. + +

You cannot create a TextLine object directly from ActionScript code. + If you call new TextLine(), an exception is thrown. + To create a TextLine object, call the createTextLine() method of a TextBlock.

+ +

The TextLine encapsulates the minimum information necessary to render its contents + and to provide interactivity through some methods that describe the properties + of the atoms of the line. The term atom refers to both graphic elements and characters (including groups of combining characters), + the indivisible entities that make up a text line.

+ +

After normal event-dispatching for a text line finishes, if the line is valid, events are mirrored to the event dispatchers that are + specified in the eventMirror properties of the content element objects that contributed to the text line. These objects are recorded in the + TextLine.mirrorRegions property. The events are not mirrored if event propagation failed or was stopped, or if the text line is not valid.

+ +

Mirroring of mouse events is a special case. Because mirror regions aren't actually display objects, mouseOver and mouseOut + events are simulated for them. rollOver and rollOut events are not simulated. All naturally occurring + mouseOver, mouseOut, rollOver and rollOut events (whether targeted at the + text line or at children of the text line) are ignored - they are not mirrored.

+ +

The origin of a text line object is the beginning of the baseline. If you don't set the vertical position (y property) + of a line that contains Latin text on a Roman baseline, only the descenders of the text appear below the top of the Sprite to which + you add the text line. See the following diagram:

+ +

+ +

The TextLine class has several ancestor classes — DisplayObjectContainer, InteractiveObject, + DisplayObject, and EventDispatcher — from which it inherits properties and methods. + The following inherited properties are inapplicable to TextLine objects:

+ +
  • contextMenu
  • focusRect
  • tabChildren
  • tabEnabled
  • tabIndex
+ +

If you try to set these properties, the text engine throws the error: IllegalOperationError. You can read these properties, but they + always contain default values.

+ +
This example displays various text lines and steps through the atoms in a text + block, using getAtomBounds() to frame each one. +
  1. Add the NumericStepper component to the library.
  2. Save this code as TextLineExample.as in the same directory as your FLA.
  3. Set the Class in the Properties window of the FLA to TextLineExample.
+ +package { + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + import flash.text.engine.FontPosture; + import flash.text.engine.FontWeight; + import fl.controls.NumericStepper; + import flash.events.Event; + import flash.geom.Rectangle; + + public class TextLineExample extends Sprite { + + private var atomStepper:NumericStepper = new NumericStepper(); + private var atomDataContainer:Sprite; + private var fontDescriptionItalic:FontDescription = new FontDescription("Arial", FontWeight.NORMAL, FontPosture.ITALIC); + private var fontDescriptionNormal:FontDescription = new FontDescription("Arial", FontWeight.NORMAL , FontPosture.NORMAL); + private var textBlock:TextBlock = new TextBlock(); + private var textLine:TextLine; + + public function TextLineExample():void { + + var myText:String = "I am a TextElement, created from a String and assigned " + + "to the content property of a TextBlock. From the text block, " + + "the createTextLine() method created these lines, 300 pixels wide, " + + "for display." ; + + atomStepper.minimum = 0; + atomStepper.value = 0; + atomStepper.width = 50; + addChild(atomStepper); + atomStepper.x = 20; + atomStepper.y = 120; + atomStepper.addEventListener(Event.CHANGE, nsChange); + + var directions:String = "Click up / down arrows to frame atoms in text block above."; + + var formatItalic:ElementFormat = new ElementFormat(fontDescriptionItalic); + formatItalic.fontSize = 12; + var textElement1:TextElement = new TextElement(directions, formatItalic); + textBlock.content = textElement1; + createLines(textBlock, 15, 160, 400, this); + + var formatNormal:ElementFormat = new ElementFormat(fontDescriptionNormal); + formatNormal.fontSize = 16; + var textElement2:TextElement = new TextElement(myText, formatNormal); + textBlock.content = textElement2; + createLines(textBlock, 15.0, 20.0, 300, this); + textLine = textBlock.firstLine; + atomStepper.maximum = textLine.atomCount - 1; + showAtom(textLine, 0); + } + + private function nsChange(event:Event):void + { + removeAtom(textLine); + if (atomStepper.value == textLine.atomCount - 1) + { + if(textLine != textBlock.lastLine) + { + textLine = textLine.nextLine; + atomStepper.maximum = textLine.atomCount - 1; + atomStepper.value = 0; + } + } + showAtom(textLine, atomStepper.value); + } + + private function createLines(textBlock, startX, startY, width, container) + { + var textLine:TextLine = textBlock.createTextLine (null, width); + while (textLine) + { + textLine.x = startX; + textLine.y = startY; + startY += textLine.height + 2; + container.addChild(textLine); + textLine = textBlock.createTextLine (textLine, width); + } + } + + private function showAtom(textLine, i):void + { + var box:Sprite = new Sprite(); + var mcGraphics = box.graphics; + var bounds:Rectangle = textLine.getAtomBounds(i); + mcGraphics.lineStyle(1, 0xFF0000, 1.0); + mcGraphics.drawRect(bounds.left, bounds.top, bounds.width, bounds.height); + textLine.userData = textLine.addChild(box); + displayAtomData(textLine,i); + } + + private function displayAtomData(textLine, i) + { + if(atomDataContainer != null) + removeChild(atomDataContainer); + atomDataContainer=new Sprite(); + var format = new ElementFormat(fontDescriptionNormal); + format.color = 0x00000FF; + var n:int = 0; + var nxtY:Number = 0; + var atomInfo:String = "value of getAtomBidiLevel() is: " + textLine.getAtomBidiLevel(i)+"\n" + +"value of getAtomCenter() is: " + textLine.getAtomCenter(i)+"\n" + +"value of getAtomIndexAtCharIndex() is: " + textLine.getAtomIndexAtCharIndex(i)+"\n" + +"value of getAtomTextBlockBeginIndex() is: " + textLine.getAtomTextBlockBeginIndex(i)+"\n" + +"value of getAtomTextBlockEndIndex() is: " + textLine.getAtomTextBlockEndIndex(i)+"\n" + +"value of getAtomTextRotation() is: " + textLine.getAtomTextRotation(i)+"\n"; + var atomtextBlock:TextBlock = new TextBlock(); + var textElement3:TextElement = new TextElement(atomInfo, format); + atomtextBlock.content = textElement3; + createLines(atomtextBlock,20,200,500, atomDataContainer) + addChild(atomDataContainer); + } + + private function removeAtom(textLine):void + { + textLine.removeChild(textLine.userData); + } + } +} +
ContentElement.eventMirrorTextBlock.createTextLine()TextLineValiditydump + Dumps the underlying contents of the TextLine as an XML string.String + Dumps the underlying contents of the TextLine as an XML string. + This can be useful in automated testing, and includes text, formatting, and layout information. + +

The following describes the output:

+ +
+	 [LINE]
+	 <line ascent=[Number] descent=[Number] rotation=[int]>
+	 	<elements>
+	 		[0-N ELEMENT]
+	 	</elements>
+	 	<clusters>
+	 		[0-N CLUSTER]
+	 	</clusters>
+	 </line>
+	 
+	 [ELEMENT]
+	 <glyph isEmbedded=[Boolean] fontName=[String] isBold=[Boolean] isItalic=[Boolean] gid=[int] pointSize=[Number] x=[Number] y=[Number] rotation=[int]/>
+	 or
+	 <graphic child=[int] x=[Number] y=[Number] rotation=[int]/>
+	 or
+	 <embeddedRun x=[Number] y=[Number]>
+	 	[LINE]
+	 </embeddedRun>
+	 
+	 [CLUSTER]
+	 <cluster xLeft=[Number] xCenter=[Number] xRight=[Number] cursorOnLeft=[Boolean] cursorOnRight=[Boolean] wordBoundaryOnLeft=[Boolean] wordBoundaryOnRight=[Boolean]/>
+	 
+ +

Note: The content and format of the output from this method could change in the future. Adobe does not guarantee backward + compatibility for this method.

+ +
TextBlock.dump()
flushAtomData + This method is deprecated and has no effect.Now does nothing + This method is deprecated and has no effect. Atom data is compressed and is not a factor in managing memory efficiency. + + TextBlock.dump()getAtomBidiLevel + Gets the bidirectional level of the atom at the specified index.The specified atom index is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe bidirectional level of the atom at atomIndex. + + intatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the bidirectional level of the atom at the specified index. Determined by a combination of + TextBlock.bidiLevel and the Unicode bidirectional properties of the characters that + form the line. + +

For example, if you start a text block with some Hebrew text, you set TextBlock.bidiLevel to 1, establishing + a default of right to left. If within the text you have a quote in English (left to right), that text has an AtomBidiLevel of + 2. If within the English you have a bit of Arabic (right to left), AtomBidiLevel for that run goes to 3. If within the + Arabic a number (left to right) occurs, the AtomBidiLevel setting for the number is 4. It does not matter in which line the + atoms end up; the Hebrew atoms are AtomBidiLevel 1, the English atoms are AtomBidiLevel 2, Arabic atoms + are AtomBidiLevel 3, and the number atoms are AtomBidiLevel 4.

+ +
TextBlock.bidiLevel
getAtomBounds + Gets the bounds of the atom at the specified index relative to the text line.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe bounds of the atom at atomIndex. + + flash.geom:RectangleatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the bounds of the atom at the specified index relative to the text line. The bounds of the specified atom consist of + its horizontal position (x) in the line, its vertical position in the line (y), its width (w), + and its height (h). All values are in pixels. + + getAtomCenter + Gets the center of the atom as measured along the baseline at the specified index.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe center of the atom at atomIndex. + + NumberatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the center of the atom as measured along the baseline at the specified index. + + getAtomGraphic + Gets the graphic of the atom at the specified index, or null if the atom is a character.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe graphic of the atom at atomIndex. + + flash.display:DisplayObjectatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the graphic of the atom at the specified index, or null if the atom is a character. + + getAtomIndexAtCharIndex + Returns the index of the atom containing the character specified by the charIndex parameter, + or -1 if the character does not contribute to any atom in the line.The validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the atom containing the character at charIndex. + Returns -1 if the character does not contribute to any atom in the line. + + intcharIndexintThe zero-based index value of the character (for example, the first character is 0, + the second character is 1, and so on). + + + Returns the index of the atom containing the character specified by the charIndex parameter, + or -1 if the character does not contribute to any atom in the line. + The charIndex is relative to the entire contents of the text block containing the line. + + getAtomIndexAtPoint + Returns the index of the atom at the point specified by the x + and y parameters, or -1 if no atom exists at that point.The validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the atom under the point. Returns -1 if the point is not over any atom. + + intstageXNumberThe global x coordinate of the point to test. + stageYNumberThe global y coordinate of the point to test. + + Returns the index of the atom at the point specified by the x + and y parameters, or -1 if no atom exists at that point. + +

This method takes global coordinates so that you can easily use it with MouseEvent.stageX + and MouseEvent.stageY properties.

+ +
getAtomTextBlockBeginIndex + Gets the text block begin index of the atom at the specified index.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe text block begin index of the atom at atomIndex. + + intatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the text block begin index of the atom at the specified index. + + getAtomTextBlockEndIndex + Gets the text block end index of the atom at the specified index.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe text block end index of the atom at atomIndex. + + intatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the text block end index of the atom at the specified index. + + getAtomTextRotation + Gets the rotation of the atom at the specified index.The specified atom index is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe rotation of the atom at atomIndex. + + StringatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Gets the rotation of the atom at the specified index. TextRotation constants are used for this property. + The rotation of the atom is the cumulative rotations of the element and the line. Its primary use is for + setting the orientation of the caret (cursor) when interacting with a TextLine. + + ElementFormat.textRotationgetAtomWordBoundaryOnLeft + Indicates whether a word boundary occurs to the left of the atom at the specified index.The atom index specified is out of range. + RangeErrorRangeErrorThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationErrorA Boolean value that indicates whether a word boundary occurs to the left of the atom at atomIndex. + + BooleanatomIndexintThe zero-based index value of the atom (for example, the first atom is 0, + the second atom is 1, and so on). + + + Indicates whether a word boundary occurs to the left of the atom at the specified index. + Word boundaries are determined based on the Unicode properties of the characters which contributed to the line. + + getBaselinePosition + Gets the position of the specified baseline, relative to TextBlock.baselineZero.If the baseline specified is not a member of TextBaseline. + + ArgumentErrorArgumentErrorThe position of the specified baseline relative to TextBlock.baselineZero. + + NumberbaselineStringThe baseline for which to retrieve the position. Use TextBaseline values. + + + Gets the position of the specified baseline, relative to TextBlock.baselineZero. + + TextBlock.baselineZeroTextBaselinegetMirrorRegion + Returns the first TextLineMirrorRegion on the line whose mirror property matches + that specified by the mirror parameter, or null if no match exists.The first TextLineMirrorRegion on the line whose mirror property matches + the specified value, or null if no match exists. + + flash.text.engine:TextLineMirrorRegionmirrorflash.events:EventDispatcherThe EventDispatcher mirror object to search for. + + Returns the first TextLineMirrorRegion on the line whose mirror property matches + that specified by the mirror parameter, or null if no match exists. +

Even a single TextElement can produce multiple TextLineMirrorRegion + objects on one or more lines, depending on bidirectional level and line breaking. The nextRegion and + previousRegion properties link all the mirror regions generated from one text element.

+ +
TextLineMirrorRegionContentElement.eventMirror
MAX_LINE_WIDTH + The maximum requested width of a text line, in pixels.1000000int + The maximum requested width of a text line, in pixels. The TextBlock.createTextLine() method uses this constant + as the default value for the width parameter, if you do not specify a value. + + TextBlock.createTextLine()userData + Provides a way for the application to associate arbitrary data with the text line. + Provides a way for the application to associate arbitrary data with the text line. + + ascent + Specifies the number of pixels from the baseline to the top of the tallest characters in the line.Number + Specifies the number of pixels from the baseline to the top of the tallest characters in the line. For a TextLine that contains only a + graphic element, ascent is set to 0. + + atomCount + The number of atoms in the line, which is the number of indivisible elements, including spaces and graphic + elements.intThe validity of the line is TextLineValidity.STATIC. + + IllegalOperationErrorflash.errors:IllegalOperationError + The number of atoms in the line, which is the number of indivisible elements, including spaces and graphic + elements. + + descent + Specifies the number of pixels from the baseline to the bottom of the lowest-descending characters in the line.Number + Specifies the number of pixels from the baseline to the bottom of the lowest-descending characters in the line. For a TextLine that + contains only a graphic element, descent is set to 0. + + hasGraphicElement + Indicates whether the text line contains any graphic elements.Boolean + Indicates whether the text line contains any graphic elements. + + GraphicElementhasTabs + Indicates whether the text line contains any tabs.Boolean + Indicates whether the text line contains any tabs. + + mirrorRegions + A Vector containing the TextLineMirrorRegion objects associated with the line, or null if none exist. + A Vector containing the TextLineMirrorRegion objects associated with the line, or null if none exist. + + ContentElement.eventMirrorTextLineMirrorRegionnextLine + The next TextLine in the TextBlock, or null if the current line is the last line in the block + or the validity of the line is TextLineValidity.STATIC.flash.text.engine:TextLine + The next TextLine in the TextBlock, or null if the current line is the last line in the block + or the validity of the line is TextLineValidity.STATIC. + + previousLinepreviousLine + The previous TextLine in the TextBlock, or null if the line is the first line in the block + or the validity of the line is TextLineValidity.STATIC.flash.text.engine:TextLine + The previous TextLine in the TextBlock, or null if the line is the first line in the block + or the validity of the line is TextLineValidity.STATIC. + + nextLinerawTextLength + The length of the raw text in the text block that became the line, + including the U+FDEF characters representing graphic elements + and any trailing spaces, which are part of the line but not are displayed.int + The length of the raw text in the text block that became the line, + including the U+FDEF characters representing graphic elements + and any trailing spaces, which are part of the line but not are displayed. + + TextBlockContentElement.rawTextspecifiedWidth + The width that was specified to the TextBlock.createTextLine() method when it created the line.Number + The width that was specified to the TextBlock.createTextLine() method when it created the line. + This value is useful when deciding if a change requires rebreaking the line. + + TextBlock.createTextLine()textWidthunjustifiedTextWidthtextBlockBeginIndex + The index of the first character of the line in the raw text of the text block.int + The index of the first character of the line in the raw text of the text block. + + TextBlocktextBlock + The TextBlock containing this text line, or null if the validity of the line is TextLineValidity.STATIC, + meaning that the connection between the line and the TextBlock has been severed.flash.text.engine:TextBlock + The TextBlock containing this text line, or null if the validity of the line is TextLineValidity.STATIC, + meaning that the connection between the line and the TextBlock has been severed. + + TextBlockTextLineValiditytextHeight + The logical height of the text line, which is equal to ascent + descent.Number + The logical height of the text line, which is equal to ascent + descent. + To get the inked height, access the inherited height property. + +

The value is calculated based on the difference between the baselines that bound the line, + either ideo top/bottom or ascent/descent depending on whether TextBlock.baselineZero is ideo or not. + Graphic elements are not considered when computing these baselines.

+ +
DisplayObject.height
textWidth + The logical width of the text line, which is the width that the text engine uses to lay out the line.Number + The logical width of the text line, which is the width that the text engine uses to lay out the line. Access the inherited + width property to get the actual width of the bounding box of all the drawn pixels. + + This example displays a line once in normal posture and once in + italic, and traces the values of the specifiedWidth, textWidth + and width properties in each case. + The trace output is: +
  • specifiedWidth is: 500
  • textWidth is: 268.9921875
  • width is: 269
  • specifiedWidth is: 500
  • textWidth is: 267.52734375
  • width is: 267.55
+ + +package { +import flash.display.Sprite; +import flash.text.engine.TextBlock; +import flash.text.engine.TextElement; +import flash.text.engine.TextLine; +import flash.text.engine.FontDescription; +import flash.text.engine.ElementFormat; +import flash.text.engine.FontPosture; + + public class TextLine_textWidthExample extends Sprite { + + public function TextLine_textWidthExample() { + + var str:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, "; + var yPos:Number = 20; + var fontDescription:FontDescription = new FontDescription(); + var textBlock:TextBlock = new TextBlock(); + fontDescription.fontPosture = FontPosture.NORMAL; + var format:ElementFormat = new ElementFormat(fontDescription, 12); + var textElement:TextElement = new TextElement(str, format); + textBlock.content = textElement; + createLine(textBlock, yPos); + var fontDescriptionItalic = fontDescription.clone(); + fontDescriptionItalic.fontPosture = FontPosture.ITALIC; + var formatItalic = new ElementFormat(fontDescriptionItalic, 12); + textElement = new TextElement(str, formatItalic); + textBlock.content = textElement; + createLine(textBlock, yPos + 20); + } + + private function createLine(textBlock:TextBlock, yPos:Number):void { + var textLine:TextLine = textBlock.createTextLine (null, 500); + trace("specifiedWidth is: " + textLine.specifiedWidth); + trace("textWidth is: " + textLine.textWidth); + trace("width is: " + textLine.width); + addChild(textLine); + textLine.x = 15; + textLine.y = yPos; + } + } +} + +
specifiedWidthDisplayObject.width
totalAscent + Specifies the number of pixels from the baseline to the top of the tallest character or graphic in the line.Number + Specifies the number of pixels from the baseline to the top of the tallest character or graphic in the line. + + totalDescent + Specifies the number of pixels from the baseline to the bottom of the lowest-descending character or graphic in the line.Number + Specifies the number of pixels from the baseline to the bottom of the lowest-descending character or graphic in the line. + + totalHeight + The total logical height of the text line, which is equal to totalAscent + totalDescent.Number + The total logical height of the text line, which is equal to totalAscent + totalDescent. + + unjustifiedTextWidth + The width of the line if it was not justified.Number + The width of the line if it was not justified. For unjustified text, this value is the same as textWidth. For + justified text, this value is what the length would have been without justification, and textWidth represents + the actual line width. For example, when the following String is justified and submitted to TextBlock.createTextLine() + with a width of 500, it has an actual width of 500 but an unjustified width of 268.9921875. + + When the String in the following example is justified and submitted to TextBlock.createTextLine() with a width of 500, + it gets an actual width of 500 but has an unjustified width of 268.9921875. + + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.FontDescription; + import flash.text.engine.ElementFormat; + import flash.text.engine.SpaceJustifier; + import flash.text.engine.LineJustification; + + var str:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, "; + var fontDescription:FontDescription = new FontDescription(); + var textBlock:TextBlock = new TextBlock(); + var format:ElementFormat = new ElementFormat(fontDescription, 12); + var textElement:TextElement = new TextElement(str, format); + textBlock.content = textElement; + var spaceJustifier:SpaceJustifier = new SpaceJustifier("en", LineJustification.ALL_INCLUDING_LAST); + textBlock.textJustifier = spaceJustifier; + var textLine:TextLine = textBlock.createTextLine(null, 500); + textLine.y = 20; + + addChild(textLine); + trace("textWidth value is: " + textLine.textWidth); // 500.00244140625 + trace("unjustifiedTextWidth is: " + textLine.unjustifiedTextWidth); // 268.9921875 + + + EastAsianJustifierLineJustificationSpaceJustifierspecifiedWidthtextWidthvalidity + Specifies the current validity of the text line.StringIf current value is TextLineValidity.STATIC. + ArgumentErrorArgumentErrorIf current value is TextLineValidity.INVALID and new value is anything other than + TextValidity.STATIC. + ArgumentErrorArgumentErrorIf current value is TextLineValidity.POSSIBLY_INVALID and new value is + TextLineValidity.VALID. + ArgumentErrorArgumentErrorIf new value is TextLineValidity.POSSIBLY_INVALID. + + ArgumentErrorArgumentError + Specifies the current validity of the text line. + Values for this property are found in the members of the + TextLineValidity class. + The rules for setting this property are as follows: + +

A line is considered USER_INVALID if validity is set to any string which is not a member of TextLineValidity. + USER_INVALID is an abstraction used here to represent any such value.

+ +

When the contents of the TextBlock are modified, the Flash runtime marks affected text lines, the previous line, and all following lines as INVALID. + The previous line must be marked invalid when a change allows the previous line to absorb part of the content that was + originally on the first affected line.

+ +

Newly broken lines are always VALID. The Flash runtime may change lines that follow from VALID to POSSIBLY_INVALID or INVALID. + It may change POSSIBLY_INVALID lines to VALID if the line breaks match up, or to INVALID if they don't.

+ +

Application code can mark VALID lines as INVALID or USER_INVALID, and can mark USER_INVALID lines as VALID. Application code cannot mark lines POSSIBLY_INVALID.

+ +

Application code can mark any line STATIC. Doing so causes the block member to become null. + Any graphic elements in a STATIC text line are removed and reparented if they are part of a new text line broken + from the text block from which the STATIC text line originally derived.

+ +
TextBlock.firstInvalidLineTextLineValidity
TabStop + The TabStop class represents the properties of a tab stop in a text block.Object + The TabStop class represents the properties of a tab stop in a text block. You assign tab stops as a Vector of TabStop objects + to the TextBlock.tabStops property. + +

Setting the properties of a TabStop object after you apply it to a TextBlock does not invalidate the TextBlock.

+ +
This example illustrates the effects of the four tab stop alignment settings - START, + CENTER, DECIMAL, and END. + +package { + + import flash.text.engine.*; + import flash.display.Sprite; + + public class TabStopExample extends Sprite { + + public function TabStopExample():void { + var container:Sprite = new Sprite(); + + var english:ElementFormat = new ElementFormat(); + english.fontDescription = new FontDescription("Arial"); + english.fontSize = 16; + english.locale = "en"; + + var tabStops:Vector.<TabStop> = new Vector.<TabStop>(); + tabStops.push( + new TabStop(TabAlignment.START, 20), + new TabStop(TabAlignment.CENTER, 120), + new TabStop(TabAlignment.DECIMAL, 220, "."), + new TabStop(TabAlignment.END, 320) + ); + + var textBlock:TextBlock = new TextBlock(); + textBlock.content = new TextElement( + "\tstart\tcenter\tdeci.mal\tend\n" + + "\tl\tl\t3.4\tl\n" + + "\tlm\tlm\t234.56\tlm\n" + + "\tlmn\tlmn\t12345678.34567\tlmn\n" + , english); + textBlock.tabStops = tabStops; + var y:Number = 60; + var previousTextLine:TextLine = null; + var textLine:TextLine; + var i:int; + var tabOrigin:Number = 100; + for (i = 0; i < 4; i++) { + textLine = textBlock.createTextLine(previousTextLine, 1000, 0); + textLine.x = 20; + textLine.y = y; + + container.addChild(textLine); + + y += 25; + previousTextLine = textLine; + } + addChild(container); + } + } +} + +
TextBlock.tabStopsTabAlignmentTabStop + Creates a new TabStop.The alignment specified is not a member of TabAlignment. + + ArgumentErrorArgumentErroralignmentStringstartThe tab alignment type of this tab stop. + Valid values for this property are found in the members of the TabAlignment class. + The default value is TabAlignment.START. + positionNumber0.0The position of the tab stop, in pixels. + The default value is 0.0. + decimalAlignmentTokenStringThe alignment token to be used if the alignment is TabAlignment.DECIMAL, + The default value is "". + + Creates a new TabStop. + TabAlignmentalignment + Specifies the tab alignment for this tab stop.StringIf set to any value that is not a member of TabAlignment. + + ArgumentErrorArgumentError + Specifies the tab alignment for this tab stop. Use the constants in the TabAlignment class to + set this property. + +

The default value is TabAlignment.START.

+ +

Use the lineOffset argument to TextBlock.createTextLine() + to adjust the tabs if the origin of the line does not align with other lines that + share the same tab stops.

+ +

Use the following constants from the TabAlignment class to set the value for this property:

+ + String valueDescriptionTabAlignment.STARTThe position property specifies the number of pixels that the start of the tabbed text is from the start of the text line.TabAlignment.CENTERThe position property specifies the number of pixels that the center of the tabbed text is from the start of the text line.TabAlignment.ENDThe position property specifies the number of pixels that the end of the tabbed text is from the start of the text line.TabAlignment.DECIMALThe position property specifies the number of pixels that the alignment token is from the start of the text line. + +
TabAlignmentTextBlock.createTextLine()
decimalAlignmentToken + Specifies the alignment token to use when you set the alignment property to TabAlignment.DECIMAL.String + Specifies the alignment token to use when you set the alignment property to TabAlignment.DECIMAL. The value + is a String that occurs in the text line. + +

The default value is "".

+ +
TabAlignment.DECIMAL
position + The position of the tab stop, in pixels, relative to the start of the text line.NumberIf set to a value less than 0.0. + + ArgumentErrorArgumentError + The position of the tab stop, in pixels, relative to the start of the text line. + +

The default value is 0.0.

+ +
FontLookup +The FontLookup class is an enumeration of constant values used with FontDescription.fontLookup.Object +The FontLookup class is an enumeration of constant values used with FontDescription.fontLookup. + +FontDescription.fontLookupDEVICE + Used to indicate device font lookup.deviceString + Used to indicate device font lookup. + The Flash runtime uses the fonts installed on the system that is running application. + +

Using device fonts results in a smaller movie size, because font data + is not included in the file.

+ +

Text rendered with device fonts is not always displayed the same across different + systems and platforms, because the Flash runtime uses the fonts that are installed on the system.

+ +
EMBEDDED_CFF + Used to indicate embedded CFF (Compact Font Format) font lookup.embeddedCFFString + Used to indicate embedded CFF (Compact Font Format) font lookup. + The Flash runtime uses font outlines embedded in the published application. + +

Text rendered with embedded fonts is always displayed + in the chosen font, whether that font is installed + on the playback system or not.

+ +

One drawback to embedded fonts is that they increase the size of the application.

+ +
DigitCase +The DigitCase class is an enumeration of constant values used in setting the digitCase property +of the ElementFormat class.Object +The DigitCase class is an enumeration of constant values used in setting the digitCase property +of the ElementFormat class. + + +flash.text.engine.ElementFormat.digitCaseDEFAULT + Used to specify default digit case.defaultString + Used to specify default digit case. The results are font-dependent; characters use the settings specified by the font designer + without any features applied. + + LINING + Used to specify lining digit case.liningString + Used to specify lining digit case. + + OLD_STYLE + Used to specify old style digit case.oldStyleString + Used to specify old style digit case. + + TypographicCase +The TypographicCase class is an enumeration of constant values for setting the typographicCase property +of the ElementFormat class.Object +The TypographicCase class is an enumeration of constant values for setting the typographicCase property +of the ElementFormat class. + + +ElementFormat.typographicCaseCAPS_AND_SMALL_CAPS + Specifies that all lowercase characters use small-caps glyphs on output.capsAndSmallCapsString + Specifies that all lowercase characters use small-caps glyphs on output. + + CAPS + Specifies that spacing is adjusted for uppercase characters on output.capsString + Specifies that spacing is adjusted for uppercase characters on output. + + DEFAULT + Specifies default typographic case.defaultString + Specifies default typographic case. The results are font-dependent; characters use the settings specified by the font designer + without any features applied. + + LOWERCASE + Specifies that all characters use lowercase glyphs on output.lowercaseString + Specifies that all characters use lowercase glyphs on output. + + SMALL_CAPS + Specifies that uppercase characters use small-caps glyphs on output.smallCapsString + Specifies that uppercase characters use small-caps glyphs on output. + + TITLE + Specifies that uppercase characters use title glyphs on output.titleString + Specifies that uppercase characters use title glyphs on output. + + UPPERCASE + Specifies that all characters use uppercase glyphs on output.uppercaseString + Specifies that all characters use uppercase glyphs on output. + + TextElement + The TextElement class represents a string of formatted text.flash.text.engine:ContentElement + The TextElement class represents a string of formatted text. Assign a TextElement object to the content + property of a TextBlock object to create a block of text. Assign it to a GroupElement object to combine it with other text + and graphic elements as a unit. Use the ElementFormat class to format the text. + + ContentElementElementFormatTextBlockTextElement + Creates a new TextElement instance.textStringnullThe text for the element. The default value is null. + elementFormatflash.text.engine:ElementFormatnullThe element format for the text in the element. The default value is null. + eventMirrorflash.events:EventDispatchernullThe EventDispatcher object that receives copies of every + event dispatched to text lines based on this content element. The default value is null. + textRotationStringrotate0The rotation applied the element as a unit. Use TextRotation + constants for this property. The default value is TextRotation.ROTATE_0. + + Creates a new TextElement instance. + + The following example creates a TextElement object from a string of text, formats + it using a font size of 12 and the color red (0xCC0000), and assigns it to the + content property of a TextBlock. It calls the createLines() function to break the + block of text into lines of 150 pixels each. + + +package { + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + + public class TextElementExample extends Sprite { + + public function TextElementExample():void { + + var str:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " + + "enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " + + "aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur " + + "sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt " + + "mollit anim id est laborum."; + + var format:ElementFormat = new ElementFormat(null, 12, 0xCC0000); + var textElement:TextElement = new TextElement(str, format); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = textElement; + createLines(textBlock); + } + + private function createLines(textBlock:TextBlock):void { + + var yPos = 20; + var textLine:TextLine = textBlock.createTextLine (null, 150); + + while (textLine) + { + addChild(textLine); + textLine.x = 15; + yPos += textLine.textHeight+2; + textLine.y = yPos; + textLine = textBlock.createTextLine(textLine, 150); + } + } + } +} +replaceText + Replaces the range of characters that the beginIndex and + endIndex parameters specify with the contents + of the newText parameter.The beginIndex or endIndex specified is out of range. + + + RangeErrorRangeErrorbeginIndexintThe zero-based index value for the start position of the replacement range. + endIndexintThe zero-based index value following the end position of the replacement range. + newTextStringThe text to use to replace the specified range of characters. + + + Replaces the range of characters that the beginIndex and + endIndex parameters specify with the contents + of the newText parameter. The beginIndex and + endIndex values refer to the current contents of text. +

To delete text, pass null for newText.

+

To insert text, pass the same value for beginIndex and endIndex. + The new text is inserted before the specified index.

+

To append text, pass text.length for beginIndex and endIndex.

+

To set all the text, pass 0 for beginIndex and text.length for endIndex.

+ +
This example calls replaceText() several times to do the following: +
  • insert a string at the beginning of text
  • append a string to the end of text
  • insert a string in the middle of text
  • replace text entirely with new text
+ + +package { + import flash.display.Sprite; + import flash.text.engine.FontDescription; + import flash.text.engine.ElementFormat; + import flash.text.engine.TextElement; + import flash.text.engine.TextBlock; + import flash.text.engine.TextLine; + + + public class TextElement_replaceTextExample extends Sprite { + public function TextElement_replaceTextExample():void { + + var str:String = "0123456"; + var fontDescription:FontDescription = new FontDescription("Arial"); + var format:ElementFormat = new ElementFormat(fontDescription); + format.fontSize = 14; + var textElement:TextElement = new TextElement(str, format); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = textElement; + textElement.replaceText(0, 0, "abc"); + createLine(textBlock, 20); //"abc0123456" + textElement.replaceText(10, 10, "abc"); + createLine(textBlock, 40); // "abc0123456abc" + textElement.replaceText(5, 8, "abc"); + createLine(textBlock, 60); // "abc01abc56abc" + textElement.replaceText(0, 13, "abc"); + createLine(textBlock, 80); // "abc" + textElement.replaceText(0, 3, "That's all she wrote!"); + createLine(textBlock, 100); // "That's all she wrote" */ + } + + private function createLine(textBlock:TextBlock, y:Number):void { + var textLine:TextLine = textBlock.createTextLine(null, 150); + textLine.x = 10; + textLine.y = y; + addChild(textLine); + } + } +} +
text + Receives the text that is the content of the element.String + Receives the text that is the content of the element. + +

The default value is null.

+ +
TextLineValidity +The TextLineValidity class is an enumeration of constant values for setting the validity property +of the TextLine class.Object +The TextLineValidity class is an enumeration of constant values for setting the validity property +of the TextLine class. + +TextBlock.firstInvalidLineTextLine.validityINVALID + Specifies that the line is invalid.invalidString + Specifies that the line is invalid. + + POSSIBLY_INVALID + Specifies that the text line is possibly invalid.possiblyInvalidString + Specifies that the text line is possibly invalid. The Flash runtime uses this validity during rebreaking of a previously broken text + block whose content has not changed. You cannot set this value. + + STATIC + Specifies that the line is static, and that the connection between the line and the text block has been severed.staticString + Specifies that the line is static, and that the connection between the line and the text block has been severed. + + VALID + Specifies that the text line is valid.validString + Specifies that the text line is valid. + + FontPosture +The FontPosture class is an enumeration of constant values used with FontDescription.fontPosture to +set text to italic or normal.Object +The FontPosture class is an enumeration of constant values used with FontDescription.fontPosture to +set text to italic or normal. + +FontDescription.fontPostureITALIC + Used to indicate italic font posture.italicString + Used to indicate italic font posture. + + NORMAL + Used to indicate normal font posture.normalString + Used to indicate normal font posture. + + JustificationStyle +The JustificationStyle class is an enumeration of constant values for setting the justificationStyle property +of the EastAsianJustifier class.Object +The JustificationStyle class is an enumeration of constant values for setting the justificationStyle property +of the EastAsianJustifier class. These constants specify options for handling kinsoku characters, which are Japanese characters that cannot +appear at either the beginning or end of a line. + +EastAsianJustifier.justificationStylePRIORITIZE_LEAST_ADJUSTMENT + Bases justification on either expanding or compressing + the line, whichever gives a result closest to the desired width.prioritizeLeastAdjustmentString + Bases justification on either expanding or compressing + the line, whichever gives a result closest to the desired width. + + PUSH_IN_KINSOKU + Bases justification on compressing kinsoku at the end of the line, + or expanding it if no kinsoku occurs or if that space is insufficient.pushInKinsokuString + Bases justification on compressing kinsoku at the end of the line, + or expanding it if no kinsoku occurs or if that space is insufficient. + + PUSH_OUT_ONLY + Bases justification on expanding the line.pushOutOnlyString + Bases justification on expanding the line. + + EastAsianJustifier + The EastAsianJustifier class has properties to control the justification options for text lines whose + content is primarily East Asian text.flash.text.engine:TextJustifier + The EastAsianJustifier class has properties to control the justification options for text lines whose + content is primarily East Asian text. + +

Use the constructor new EastAsianJustifier() to create an EastAsianJustifier object + before setting its properties. Setting the properties of an EastAsianJustifier object after it has been applied to a TextBlock does + not invalidate the TextBlock.

+ +
This example displays a block of Japanese text vertically, + using EastAsianJustifier properties to justify the text. + + +package { + import flash.text.engine.TextBlock; + import flash.text.engine.TextLine; + import flash.text.engine.TextElement; + import flash.text.engine.TextBaseline; + import flash.text.engine.EastAsianJustifier; + import flash.text.engine.LineJustification; + import flash.text.engine.TextRotation; + import flash.text.engine.FontDescription; + import flash.text.engine.ElementFormat; + import flash.display.Stage; + import flash.display.Sprite; + import flash.system.Capabilities; + + public class EastAsianJustifierExample extends Sprite { + + public function EastAsianJustifierExample():void { + + var Japanese_txt:String = String.fromCharCode( + 0x5185, 0x95A3, 0x5E9C, 0x304C, 0x300C, 0x653F, 0x5E9C, 0x30A4, + 0x30F3, 0x30BF, 0x30FC, 0x30CD, 0x30C3, 0x30C8, 0x30C6, 0x30EC, + 0x30D3, 0x300D, 0x306E, 0x52D5, 0x753B, 0x914D, 0x4FE1, 0x5411, + 0x3051, 0x306B, 0x30A2, 0x30C9, 0x30D3, 0x30B7, 0x30B9, 0x30C6, + 0x30E0, 0x30BA, 0x793E, 0x306E + ) + + "FMS 2" + + String.fromCharCode(0x3092, 0x63A1, 0x7528, 0x3059, 0x308B, 0x3068, + 0x767a, 0x8868, 0x3057, 0x307e, 0x3057, 0x305F, 0x3002); + + var textBlock:TextBlock = new TextBlock(); + var font:FontDescription = new FontDescription(); + var format:ElementFormat = new ElementFormat(); + format.fontSize = 12; + format.locale = "ja"; + format.color = 0xCC0000; + textBlock.baselineZero = TextBaseline.IDEOGRAPHIC_CENTER; + textBlock.textJustifier = new EastAsianJustifier("ja", LineJustification.ALL_INCLUDING_LAST); + textBlock.lineRotation = TextRotation.ROTATE_90; + var linePosition:Number = this.stage.stageWidth - 75; + if (Capabilities.os.search("Mac OS") > -1) + // set fontName: Kozuka Mincho Pro R + font.fontName = String.fromCharCode(0x5C0F, 0x585A, 0x660E, 0x671D) + " Pro R"; + else + font.fontName = "Kozuka Mincho Pro R"; + textBlock.content = new TextElement(Japanese_txt, format); + var previousLine:TextLine = null; + + while (true) + { + var textLine:TextLine = textBlock.createTextLine(previousLine, 320); + if (textLine == null) + break; + textLine.y = 20; + textLine.x = linePosition; + linePosition -= 25; + addChild(textLine); + previousLine = textLine; + } + } + } +} + + +
JustificationStyleLineJustificationTextBlock.textJustifierEastAsianJustifier + Creates an EastAsianJustifier object.The locale specified is null or too short to represent a valid locale. + ArgumentErrorArgumentErrorThe lineJustification specified is not a member of LineJustification. + ArgumentErrorArgumentErrorThe justificationStyle specified is not a member of JustificationStyle. + + ArgumentErrorArgumentErrorlocaleStringjaThe locale to determine the justification rules. + The default value is "ja". + lineJustificationStringallButLastThe type of line justification for the paragraph. + Use LineJustification constants for this property. + The default value is LineJustification.ALL_BUT_LAST. + justificationStyleStringpushInKinsokuThe justification style for the text in a text block using an East Asian justifier. + Use JustificationStyle constants for this property. + The default value is JustificationStyle.PUSH_IN_KINSOKU. + + Creates an EastAsianJustifier object. + + JustificationStyleLineJustificationclone + Constructs a cloned copy of the EastAsianJustifier.A copy of the EastAsianJustifier object. + + flash.text.engine:TextJustifier + Constructs a cloned copy of the EastAsianJustifier. + + justificationStyle + Specifies the justification style for the text in a text block.String + Specifies the justification style for the text in a text block. + +

The default value is JustificationStyle.PUSH_IN_KINSOKU.

+ +

Use one of the constants in the JustificationStyle class to set the value for this + property. The following table lists the possible values:

+ + String valueDescriptionJustificationStyle.PUSH_IN_KINSOKUSpecifies push in justification.JustificationStyle.PUSH_OUT_ONLYSpecifies push out justification.JustificationStyle.PRIORITIZE_LEAST_ADJUSTMENTSpecifies justification wherein the least adjustment is prioritized. + +
JustificationStyle
RenderingMode +The RenderingMode class provides values for rendering mode in the FontDescription class.Object +The RenderingMode class provides values for rendering mode in the FontDescription class. +FontDescriptionCFF + Sets rendering mode to CFF (Compact Font Format).cffString + Sets rendering mode to CFF (Compact Font Format). CFF rendering improves readability of text on a display. + This setting is recommended for applications that have a lot of small text. + This constant is used for the renderingMode property in the FontDescription + class. + Use the syntax RenderingMode.CFF. + + flash.text.engine.FontDescription.renderingModeNORMAL + Sets rendering mode to the rendering mode that is used in Flash Player 7 and earlier.normalString + Sets rendering mode to the rendering mode that is used in Flash Player 7 and earlier. + This setting is recommended for animated text. + This constant is used for the renderingMode property in the FontDescription + class. + Use the syntax RenderingMode.NORMAL. + flash.text.engine.FontDescription.renderingModeFontMetrics + The FontMetrics class contains measurement and offset information about a font.Object + The FontMetrics class contains measurement and offset information about a font. + The ElementFormat.getFontMetrics() method returns objects of this class. + + ElementFormat.getFontMetrics()FontMetrics + Creates a FontMetrics object.emBoxflash.geom:RectangleThe emBox of the font in pixels. + strikethroughOffsetNumberThe offset for a strikethrough in pixels. + strikethroughThicknessNumberThe thickness for a strikethrough in pixels. + underlineOffsetNumberThe offset for an underline in pixels. + underlineThicknessNumberThe thickness for an underline in pixels. + subscriptOffsetNumberThe offset for a subscript in pixels. + subscriptScaleNumberThe scale to apply to the point size of a subscript. + superscriptOffsetNumberThe offset for a superscript in pixels. + superscriptScaleNumberThe scale to apply to the point size of a superscript. + + + Creates a FontMetrics object. The FontMetrics object contains information about + the metrics of a font in an element format. + The flash.text.engine.ElementFormat.getFontMetrics() method returns objects of this class. + + ElementFormat.getFontMetrics()emBox + The emBox value represents the design space of the font and is used to place Chinese, + Korean, or Japanese glyphs relative to the Roman baseline.flash.geom:Rectangle + The emBox value represents the design space of the font and is used to place Chinese, + Korean, or Japanese glyphs relative to the Roman baseline. + Typically a square, sized to the point size of the font. The origin (coordinate 0,0) + of the emBox is set to the left edge and Roman baseline of the rect. + For example, for a 10-point font, the emBox can be a rect [L,T,R,B] of [0, -8.8, 10, 1.2]. + + strikethroughOffset + The strikethroughOffset value is the suggested vertical offset from the Roman baseline for a strikethrough.Number + The strikethroughOffset value is the suggested vertical offset from the Roman baseline for a strikethrough. + +

Note that depending on the rotation of the line, this value is either added or subtracted from the + position of the line to find the position for the strikethrough. In a line with TextRotation.ROTATE_0, + strikethrough.y = line.y + strikethroughOffset. In a line + with TextRotation.ROTATE_90, strikethrough.x = line.x - strikethroughOffset.

+ +

When applying decorations such as strikethroughs to a TextLine, the recommended procedure is to specify + an eventMirror on the ContentElement which is to receive the decoration. + In response to the Event.ADDED event, the bounds of the + TextLineMirrorRegion can be used in conjunction + with the strikethroughOffset to place the strikethrough.

+ +
ContentElement.eventMirrorTextLineMirrorRegion
strikethroughThickness + The strikethroughThickness value is the suggested thickness for a strikethrough.Number + The strikethroughThickness value is the suggested thickness for a strikethrough. + + subscriptOffset + The subscriptOffset value is the suggested vertical offset from the Roman baseline for a subscript.Number + The subscriptOffset value is the suggested vertical offset from the Roman baseline for a subscript. + +

The subscriptOffset value is used with ElementFormat.baselineShift to position the subscript.

+ +
ElementFormat.baselineShift
subscriptScale + The subscriptScale value is the suggested scale factor to apply to the point size for a subscript.Number + The subscriptScale value is the suggested scale factor to apply to the point size for a subscript. + A scale factor of 1.0 means no scaling. + + superscriptOffset + The superscriptOffset value is the suggested vertical offset from the Roman baseline for a superscript.Number + The superscriptOffset value is the suggested vertical offset from the Roman baseline for a superscript. + +

The superscriptOffset value is used with ElementFormat.baselineShift to position the superscript.

+ +
ElementFormat.baselineShift
superscriptScale + The superscriptScale value is the suggested scale factor to apply to the point size for a superscript.Number + The superscriptScale value is the suggested scale factor to apply to the point size for a superscript. + A scale factor of 1.0 means no scaling. + + underlineOffset + The underlineOffset value is the suggested vertical offset from the Roman baseline for an underline.Number + The underlineOffset value is the suggested vertical offset from the Roman baseline for an underline. + +

Note that depending on the rotation of the line, this value is either added or subtracted from the + position of the line to find the position for the underline. In a line with TextRotation.ROTATE_0, + underline.y = line.y + underlineOffset. In a line + with TextRotation.ROTATE_90, underline.x = line.x - underlineOffset.

+ +

When applying decorations such as underlines to a TextLine, the recommended procedure is to specify + an eventMirror on the ContentElement which is to receive the decoration. + In response to the Event.ADDED event, the bounds of the + TextLineMirrorRegion can be used in conjunction + with the underlineOffset to place the underline.

+ +
ContentElement.eventMirrorEventTextLineMirrorRegionTextRotation
underlineThickness + The underlineThickness value is the suggested thickness for an underline.Number + The underlineThickness value is the suggested thickness for an underline. + +
ElementFormat + The ElementFormat class represents formatting information which can be applied to a ContentElement.Object + The ElementFormat class represents formatting information which can be applied to a ContentElement. Use the ElementFormat class + to create specific text formatting for the various subclasses of ContentElement. The properties of the ElementFormat class apply to device and + embedded fonts. + +

An ElementFormat object that is applied to a ContentElement in a TextBlock does not invalidate the TextBlock. + Once an ElementFormat has been + applied to a ContentElement, its locked property is set to true. + The properties of a locked ElementFormat object cannot be changed. Instead, use the clone() + method to create an unlocked copy of the object, which can be modified and assigned to the ContentElement.

+ +

This example creates two ElementFormat objects and sets several of + their properties. It then assigns the new ElementFormats to a TextElement object, + which has been assigned as the content of a TextBlock. Note that changing the + ElementFormat of a TextElement does not affect TextLines that + have been previously created by the parent TextBlock.

+ + +package { + + import flash.display.Sprite; + import flash.text.engine.*; + + + public class ElementFormatExample extends Sprite { + + public function ElementFormatExample():void { + var fd:FontDescription = new FontDescription(); + fd.fontName = "Garamond"; + fd.fontWeight = flash.text.engine.FontWeight.BOLD; + + var ef1:ElementFormat = new ElementFormat(fd); + ef1.fontSize = 30; + ef1.color = 0xFF0000; + ef1.alpha = 100; + ef1.kerning = flash.text.engine.Kerning.ON; + ef1.trackingRight = 2; + ef1.typographicCase = flash.text.engine.TypographicCase.UPPERCASE; + ef1.alignmentBaseline = flash.text.engine.TextBaseline.DESCENT; + ef1.ligatureLevel = flash.text.engine.LigatureLevel.EXOTIC; + + var ef2:ElementFormat = new ElementFormat(fd); + ef2.fontSize = 30; + ef2.color = 0xFF0000; + ef2.alpha = 0.3; + ef2.kerning = flash.text.engine.Kerning.OFF; + ef2.typographicCase = flash.text.engine.TypographicCase.LOWERCASE; + ef2.digitCase = flash.text.engine.DigitCase.OLD_STYLE; + ef2.textRotation = flash.text.engine.TextRotation.ROTATE_180; + + var str:String = "This is flash text 0123456789"; + var tb:TextBlock = new TextBlock(); + var te1:TextElement = new TextElement(str, ef1); + tb.content = te1; + var line1:TextLine = tb.createTextLine(null, 600); + addChild(line1); + line1.x = 15; + line1.y = 30; + + tb.content.elementFormat = ef2; + var line2:TextLine = tb.createTextLine(null, 600); + addChild(line2); + line2.x = 15; + line2.y = 60; + + } + } +} +
ContentElement.elementFormatElementFormat + Creates an ElementFormat object.The fontSize specified is less than 0. + ArgumentErrorArgumentErrorThe textRotation specified is not a member of TextRotation. + ArgumentErrorArgumentErrorThe dominantBaseline specified is not a member of TextBaseline. + ArgumentErrorArgumentErrorThe alignmentBaseline specified is not a member of TextBaseline. + ArgumentErrorArgumentErrorThe kerning specified is not a member of Kerning. + ArgumentErrorArgumentErrorThe breakOpportunity specified is not a member of BreakOpportunity. + ArgumentErrorArgumentErrorThe digitCase specified is not a member of DigitCase. + ArgumentErrorArgumentErrorThe digitWidth specified is not a member of DigitWidth. + ArgumentErrorArgumentErrorThe ligatureLevel specified is not a member of LigatureLevel. + ArgumentErrorArgumentErrorThe typographicCase specified is not a member of TypographicCase. + + ArgumentErrorArgumentErrorfontDescriptionflash.text.engine:FontDescriptionnullThe FontDescription object which identifies the font used with this element format. + The default value is null. If no font description is provided, a default font description is constructed. + fontSizeNumber12.0The size of text in pixels. + coloruint0x000000The color of text. A hexadecimal number containing three 8-bit RGB + components; for example, 0xFF0000 is red and 0x00FF00 is green. + alphaNumber1.0The alpha property applied to all line atoms based on the element format. + textRotationStringautothe rotation applied to individual glyphs. Use TextRotation + constants for this property. + dominantBaselineStringromanThe baseline to which the glyphs in the text snap. + Use TextBaseline constants for this property. + alignmentBaselineStringuseDominantBaselineThe baseline on the containing line to which the dominant baseline snaps. + Use TextBaseline constants for this property. + baselineShiftNumber0.0The baseline shift for the text in pixels em. + kerningStringonThe kerning used for this text. Use constants defined in the Kerning class. + trackingRightNumber0.0The tracking or manual kerning applied to the right of each glyph in pixels. + trackingLeftNumber0.0The tracking or manual kerning applied to the left of each glyph in pixels. + localeStringenThe locale of the text. + breakOpportunityStringautoThe line break opportunity applied to this text. Use BreakOpportunity + constants for this property. + digitCaseStringdefaultThe digit case used for this text. Use DigitCase + constants for this property. + digitWidthStringdefaultThe digit width used for this text. Use DigitWidth + constants for this property. + ligatureLevelStringcommonThe ligature level used for this text. Use LigatureLevel + constants for this property. + typographicCaseStringdefaultThe typographic case used for this text. Use TypographicCase + constants for this property. + + + Creates an ElementFormat object. + + clone + Constructs an unlocked, cloned copy of the ElementFormat.An unlocked copy of the ElementFormat object. + + flash.text.engine:ElementFormat + Constructs an unlocked, cloned copy of the ElementFormat. + +

This example creates an ElementFormat object and sets a FontSize. + A new TextElement is created, using the ElementFormat (and therefore locking it), and + the TextElement is used as content for a TextBlock. A + line of text is created from the TextBlock.

+

To modify the ElementFormat object, first check its + locked property. If true, use the clone() method to + create an unlocked copy of the ElementFormat, change its properties, + then re-link the new ElementFormat to the TextBlock. + When the lines are re-broken, the new lines will have the new font settings.

+ + +package { + + import flash.display.Sprite; + import flash.text.engine.*; + + + public class ElementFormat_cloneExample extends Sprite { + private var ef1:ElementFormat; + private var ef2:ElementFormat; + + public function ElementFormat_cloneExample():void { + var fd:FontDescription = new FontDescription(); + fd.fontLookup = flash.text.engine.FontLookup.DEVICE; + fd.fontName = "Palatino"; + + var ef1:ElementFormat = new ElementFormat(fd); + ef1.fontSize=20; + + var str:String = "This is flash text 0123456789"; + var tb:TextBlock = new TextBlock(); + var te1:TextElement = new TextElement(str, ef1); + tb.content = te1; + var line1:TextLine = tb.createTextLine(null, 600); + addChild(line1); + + ef2 = (ef1.locked) ? ef1.clone() : ef1; + ef2.fontSize = 32; + + tb.content.elementFormat=ef2; + var line2:TextLine = tb.createTextLine(null, 600); + addChild(line2); + + } + } +} +
getFontMetrics + Returns a FontMetrics object with properties which describe the emBox, strikethrough position, + strikethrough thickness, underline position, and underline thickness for the font specified by + fontDescription and fontSize. + + A FontMetrics object describing properties of the font specified by fontDescription. + + flash.text.engine:FontMetrics +

Returns a FontMetrics object with properties which describe the emBox, strikethrough position, + strikethrough thickness, underline position, and underline thickness for the font specified by + fontDescription and fontSize.

+ +
This example creates an ElementFormat object with an assigned + FontDescription and uses the getFontMetrics method to + display metrics for the chosen font at 24 points. + + +package { + + import flash.display.Sprite; + import flash.text.engine.*; + + + public class FontMetricsExample extends Sprite { + + public function FontMetricsExample():void { + var fd:FontDescription = new FontDescription(); + fd.fontName = "Garamond"; + fd.fontWeight = flash.text.engine.FontWeight.BOLD; + + var ef1:ElementFormat = new ElementFormat(fd); + ef1.fontSize = 24; + var fm1:FontMetrics = ef1.getFontMetrics(); + + trace(fm1.emBox); + trace(fm1.strikethroughOffset); + trace(fm1.strikethroughThickness); + trace(fm1.subscriptScale); + trace(fm1.subscriptOffset); + trace(fm1.superscriptScale); + trace(fm1.superscriptOffset); + trace(fm1.underlineOffset); + trace(fm1.underlineThickness); + + + } + } +} +
FontDescriptionFontMetrics
alignmentBaseline + Specifies the type of baseline in the containing element to which to align the dominant baselines of elements having + this format.StringIf set to any value which is not a member of TextBaseline. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies the type of baseline in the containing element to which to align the dominant baselines of elements having + this format. Use TextBaseline constants for this property. + +

The largest vertical element in the line determines the alignment of baselines unless + TextBlock.baselineFontDescription and TextBlock.baselineFontSize are set to override that logic.

+ +

The default value is TextBaseline.USE_DOMINANT_BASELINE.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTextBaseline.ROMANThe dominantBaseline aligns with the roman baseline of the line.TextBaseline.ASCENTThe dominantBaseline aligns with the ascent baseline of the line.TextBaseline.DESCENTThe dominantBaseline aligns with the descent baseline of the line.TextBaseline.IDEOGRAPHIC_TOPThe dominantBaseline aligns with the ideographic top baseline of the line.TextBaseline.IDEOGRAPHIC_CENTERThe dominantBaseline aligns with the ideographic center baseline of the line.TextBaseline.IDEOGRAPHIC_BOTTOMThe dominantBaseline aligns with the ideographic bottom baseline of the line.TextBaseline.USE_DOMINANT_BASELINEThe dominantBaseline aligns with the same baseline of the line. +

+ SubclassEffect of setting propertyGraphicElementSets the alignment baseline of the line to which the dominantBaseline of the graphic element aligns.GroupElementHas no effect.TextElementSets the alignment baseline of the line to which the dominantBaseline of the text element aligns. + + TextBaselineElementFormat.dominantBaselinealpha + Specifies the transparency of the line elements affected by this obect.NumberIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies the transparency of the line elements affected by this obect. Valid values range from 0 (fully transparent) + to 1 (fully opaque). Display objects with alpha set to 0 are active, even though they are invisible. + +

The default value is 1.

+ + SubclassEffect of setting propertyGraphicElementApplies the specified alpha to the graphic element. Combines + multiplicatively with any alpha set on the graphic DisplayObject + itself or on the TextLine.GroupElementHas no effect.TextElementApplies the specified alpha to the text element. Combines + multiplicatively with any alpha set on the TextLine. + +
DisplayObject.alpha
baselineShift + Indicates the baseline shift for the element in pixels.NumberIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Indicates the baseline shift for the element in pixels. +

The element is shifted away from the dominantBaseline by this amount. + The offset is added to the y position of the members of the element, so in non-rotated + text, a positive baseline shift moves the element down and a negative baseline shift + moves the element up.

+ +

The default value is 0.0, indicating no shift.

+ + SubclassEffect of setting propertyGraphicElementShifts the graphic away from the baseline.GroupElementHas no effect.TextElementShifts the text away from the baseline. + +
breakOpportunity + The line break opportunity applied to this text.StringIf set to a value not a member of BreakOpportunity. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The line break opportunity applied to this text. + This property determines which characters can be used for breaking when wrapping text is broken into multiple lines. + Use BreakOpportunity + constants for this property. + +

The default value is BreakOpportunity.AUTO.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionBreakOpportunity.AUTOLine breaking opportunities are based on standard Unicode character properties, such as breaking between words and on hyphens.BreakOpportunity.ANYAny character in the ContentElement object is treated as a line break opportunity. This value is typically used when Roman text is embedded in Asian text and it is desirable for breaks to happen in the middle of words.BreakOpportunity.NONENo characters in the range are treated as line break opportunities.BreakOpportunity.ALLAll characters in the range are treated as line break opportunities, meaning that a line break will occur + after each character. Useful for creating effects like text on a path. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementDetermines the break opportunity between adjacent text elements in the group. + If the elementFormat of the group is null, the format of the first + of the adjacent elements is used.TextElementDetermines the break opportunity between the characters in the text element. + + BreakOpportunitycolor + Indicates the color of the text.uintIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Indicates the color of the text. An integer containing three 8-bit RGB components; for example, + 0xFF0000 is red and 0x00FF00 is green. + +

The default value is 0x000000, which is black.

+ + SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementSets the color of the text. + +
digitCase + The digit case used for this text.StringIf set to any value which is not a member of DigitCase. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The digit case used for this text. + Digit case affects the style and positioning of groups of numeric characters. + Use DigitCase + constants for this property. + +

The default value is DigitCase.DEFAULT.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionDigitCase.DEFAULTApplies default digit case to the text.DigitCase.LININGApplies lining digit case to the text.DigitCase.OLD_STYLEApplies old style digit case to the text. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the digit case used for the text in the element. + + DigitCasedigitWidth + The digit width used for this text.StringIf set to any value which is not a member of DigitWidth. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The digit width used for this text. Use DigitWidth + constants for this property. + +

The default value is DigitWidth.DEFAULT.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionDigitWidth.DEFAULTApplies default digit width to the text.DigitWidth.PROPORTIONALApplies proportional digit width to the text.DigitWidth.TABULARApplies tabular digit width to the text. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the digit width used for the text in the element. + + DigitWidthdominantBaseline + Specifies the type of baseline to use as the dominant baseline.StringIf set to any value which is not a member of TextBaseline. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies the type of baseline to use as the dominant baseline. The dominant baseline is aligned + with the alignment baseline to determine the vertical position of the element on the line. + Use TextBaseline constants for this property. + +

The content of the element determines the baselines. + In the case of a TextElement, the font and the point size determine the baselines. + In the case of a GraphicElement, the height of the element determines the baselines.

+ +

The default value is TextBaseline.ROMAN.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTextBaseline.ROMANThe roman baseline of the element aligns with the alignmentBaseline.TextBaseline.ASCENTThe ascent baseline of the element aligns with the alignmentBaseline.TextBaseline.DESCENTThe descent baseline of the element aligns with the alignmentBaseline.TextBaseline.IDEOGRAPHIC_TOPThe ideographic top baseline of the element aligns with the alignmentBaseline.TextBaseline.IDEOGRAPHIC_CENTERThe ideographic center baseline of the element aligns with the alignmentBaseline.TextBaseline.IDEOGRAPHIC_BOTTOMThe ideographic bottom baseline of the element aligns with the alignmentBaseline. +

+ SubclassEffect of setting propertyGraphicElementDetermines which of the baselines of the graphic element aligns with the alignmentBaseline.GroupElementHas no effect.TextElementDetermines which of the baselines of the text element aligns with the alignmentBaseline. + + TextBaselineElementFormat.alignmentBaselinefontDescription + An object whose properties describe a font.flash.text.engine:FontDescriptionIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + An object whose properties describe a font. + +

The default value is a default-constructed FontDescription object.

+ +

When the fontDescription property is set, the FontDescription object provided is locked: its locked + property is set to true. A locked FontDescription cannot be modified.

+ + SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the font used for the text in the element. + +
FontDescription
fontSize + The size of text in pixels.NumberIf set to a value less than zero. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The size of text in pixels. + +

The default value is 12.0.

+ + SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the size in pixels for the text in the element. + +
kerning + Kerning adjusts the pixels between certain character pairs to improve readability.StringIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Kerning adjusts the pixels between certain character pairs to improve readability. + Kerning is supported for all fonts which have kerning tables. + +

The default value is Kerning.ON.

+ +

To set values for this property, use the following constants in the Kerning class:

+ + String valueDescriptionKerning.ONKerning is enabled.Kerning.OFFKerning is disabled.Kerning.AUTOKerning is enabled except where inappropriate in Asian typography. Kerning is applied between two + characters if neither is Kanji, Hiragana, or Katakana. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementDetermines whether kerning is applied between adjacent text elements in the group. + If the elementFormat of the group is null, the format of the first + of the adjacent elements is used.TextElementDetermines whether kerning is applied between the characters in the text element. + + KerningligatureLevel + The ligature level used for this text.StringIf set to any value which is not a member of LigatureLevel. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The ligature level used for this text. + A ligature occurs where two or more letter-forms are joined as a single glyph. Ligatures + usually replace consecutive characters sharing common components, such as the letter pairs 'fi', 'fl', or 'ae'. + They are used with both Latin and non-Latin character sets. Use LigatureLevel + constants for this property. + +

The default value is LigatureLevel.COMMON.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionLigatureLevel.NONENo ligatures are created.LigatureLevel.MINIMUMMinimal ligatures are created.LigatureLevel.COMMONCommon ligatures are created.LigatureLevel.UNCOMMONUncommon ligatures are created.LigatureLevel.EXOTICExotic ligatures are created. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementDetermines the ligature level between adjacent text elements in the group. + If the elementFormat of the group is null, the format of the first + of the adjacent elements is used.TextElementDetermines the ligature level between the characters in the text element. + + LigatureLevellocale + The locale of the text.StringIf set after the ElementFormat object is locked (locked is true). + + + IllegalOperationErrorflash.errors:IllegalOperationError + The locale of the text. Controls case transformations and shaping. + Standard locale identifiers are used. For example "en", "en_US" and "en-US" are all + English, "ja" is Japanese. See iso639-2 code list + for a list of locale codes. + +

The default value is "en".

+ + SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines transformations and shaping for the text in the element. + +
locked + Indicates whether the ElementFormat is locked.BooleanIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Indicates whether the ElementFormat is locked. If true the ElementFormat cannot be modified. + Call ElementFormat.clone() to get an unlocked copy of the ElementFormat object. + + textRotation + Sets the rotation applied to individual glyphs.StringIf set to any value which is not a member of TextRotation. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Sets the rotation applied to individual glyphs. Use constants defined in the TextRotation class + for this property. + +

The default value is TextRotation.AUTO.

+ +

The final rotation of any glyph is the sum of ElementFormat.textRotation, ContentElement.textRotation, and TextBlock.lineRotation.

+ +

You typically use this property for Asian text where characters must be rotated to display properly in vertical layout. + Use TextRotation.AUTO in combination with TextBlock.lineRotation = TextRotation.ROTATE_90 + to accomplish this.

+ +

Setting this property on fonts which do not contain vertical layout information can give undesirable results. + Fonts that contain a vmtx or VORG table, such as the Japanese font, "MS Mincho", work correctly because the + tables supply the data that the layout engine requires for correct layout. Fonts such as Verdana, which do not contain the necessary information, + do not.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTextRotation.ROTATE_0Glyphs are not rotated.TextRotation.ROTATE_90Glyphs are rotated 90 degrees clockwise.TextRotation.ROTATE_180Glyphs are rotated 180 degrees.TextRotation.ROTATE_270Glyphs are rotated 270 degrees clockwise.TextRotation.AUTOSpecifies a 90 degree counter clockwise rotation for full width and wide glyphs only, + as determined by the Unicode properties of the glyph. + This value is typically used with Asian text to rotate + only those glyphs that require rotation. + This rotation is applied only in vertical text to return full width and wide + characters to a vertical orientation without affecting other characters. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the rotation of the glyphs in the text element. + + TextRotationContentElement.textRotationTextBlock.lineRotationtrackingLeft + The tracking or manual kerning applied to the left of each glyph in pixels.NumberIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The tracking or manual kerning applied to the left of each glyph in pixels. + If kerning is enabled, the trackingLeft value is added to the values in the + kerning table for the font. If kerning is disabled, the trackingLeft value + is used as a manual kerning value. Supports both positive and negative values. + +

Typically, the desired tracking value is split between trackingRight and trackingLeft. + Otherwise, in mixed directionality text, there is twice the tracking at one bidi boundary and none at the other.

+ +

The default value is 0.0.

+ + SubclassEffect of setting propertyGraphicElementDetermines the tracking applied to the left side of the graphic.GroupElementHas no effect.TextElementDetermines the tracking applied to the left side of characters in the text element. + +

Example:

+ + + //positive tracking added to kerning + var ef1:ElementFormat = new ElementFormat(); + ef1.kerning = flash.text.engine.Kerning.ON; + ef1.trackingLeft = 0.5; + + //negative manual kerning + var ef2:ElementFormat = new ElementFormat(); + ef2.kerning = flash.text.engine.Kerning.OFF; + ef2.trackingLeft = -1.0; + + +
trackingRight + The tracking or manual kerning applied to the right of each glyph in pixels.NumberIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The tracking or manual kerning applied to the right of each glyph in pixels. + If kerning is enabled, the trackingRight value is added to the values in the + kerning table for the font. If kerning is disabled, the trackingRight value + is used as a manual kerning value. Supports both positive and negative values. + +

Typically, the desired tracking value is split between trackingRight and trackingLeft. + Otherwise, in mixed directionality text, there is twice the tracking at one bidi boundary and none at the other.

+ + +

The default value is 0.0.

+ + SubclassEffect of setting propertyGraphicElementDetermines the tracking applied to the right side of the graphic.GroupElementHas no effect.TextElementDetermines the tracking applied to the right side of characters in the text element. + +

Example:

+ + + //positive tracking added to kerning + var ef1:ElementFormat = new ElementFormat(); + ef1.kerning = flash.text.engine.Kerning.ON; + ef1.trackingRight = 0.5; + + //negative manual kerning + var ef2:ElementFormat = new ElementFormat(); + ef2.kerning = flash.text.engine.Kerning.OFF; + ef2.trackingRight = -1.0; + + +
typographicCase + The typographic case used for this text.StringIf set to a value not a member of TypographicCase. + ArgumentErrorArgumentErrorIf set after the ElementFormat object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The typographic case used for this text. Use constants defined in the TypographicCase class for this property. + +

The default value is TypographicCase.DEFAULT.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTypographicCase.DEFAULTSpecifies that normal case is used for all characters.TypographicCase.TITLESpecifies that uppercase characters use title glyphs on output.TypographicCase.CAPSSpecifies that spacing is adjusted for uppercase characters on output.TypographicCase.SMALL_CAPSSpecifies that uppercase characters use small caps glyphs on output.TypographicCase.UPPERCASESpecifies that all characters use uppercase glyphs on output.TypographicCase.LOWERCASESpecifies that all characters use lowercase glyphs on output.TypographicCase.CAPS_AND_SMALL_CAPSSpecifies that all lowercase characters use small caps glyphs on output. +

+ SubclassEffect of setting propertyGraphicElementHas no effect.GroupElementHas no effect.TextElementDetermines the typographic case used for the text in the element. + + TypographicCaseTextJustifier + The TextJustifier class is an abstract base class for the justifier types that you can apply to a TextBlock, specifically the + EastAsianJustifier and SpaceJustifier classes.Object + The TextJustifier class is an abstract base class for the justifier types that you can apply to a TextBlock, specifically the + EastAsianJustifier and SpaceJustifier classes. + +

You cannot instantiate the TextJustifier class directly. Invoking new TextJustifier() throws an ArgumentError + exception. Setting the properties of an EastAsianJustifier or SpaceJustifier object after you apply it to a TextBlock does not + invalidate the TextBlock.

+ +
EastAsianJustifierSpaceJustifierTextBlock.textJustifierTextJustifier + Calling the new TextJustifier() constructor throws an + ArgumentError exception.The locale specified is null or too short to represent a valid locale. + ArgumentErrorArgumentErrorThe lineJustification specified is not a member of LineJustification. + + ArgumentErrorArgumentErrorlocaleStringThe locale to determine the justification rules. + lineJustificationStringThe type of line justification for the paragraph. + Use LineJustification constants for this property. + + Calling the new TextJustifier() constructor throws an + ArgumentError exception. You can, however, call constructors for + the following subclasses of TextJustifier: + +
  • new SpaceJustifier()
  • new EastAsianJustifier()
+ +
EastAsianJustifierLineJustificationSpaceJustifier
clone + Constructs a cloned copy of the TextJustifier.A copy of the TextJustifier object. + + flash.text.engine:TextJustifier + Constructs a cloned copy of the TextJustifier. + +

Subclasses of TextJustifier must override this method.

+ +
getJustifierForLocale + Constructs a default TextJustifier subclass appropriate to the specified locale.The locale specified is null or too short to represent a valid locale. + + ArgumentErrorArgumentErrorA reference to a TextJustifier object. + + flash.text.engine:TextJustifierlocaleStringThe locale to determine the justifier constructed. + + Constructs a default TextJustifier subclass appropriate to the specified locale. + +

If the locale is Chinese, Korean, or Japanese, the method constructs a default EastAsianJustifier object. + Otherwise the text engine constructs a default SpaceJustifier object.

+ +
lineJustification + Specifies the line justification for the text in a text block.String + Specifies the line justification for the text in a text block. + +

Use the following constants defined by the LineJustification as valid values for this property:

+ + + String valueDescriptionLineJustification.UNJUSTIFIEDGenerates unjustified lines.LineJustification.ALL_BUT_LASTGenerates all lines justified except for the last one.LineJustification.ALL_INCLUDING_LASTGenerates all lines justified. + +
LineJustification
locale + Specifies the locale to determine the justification rules for the text in a text block.StringThe locale specified is null or too short to represent a valid locale. + + ArgumentErrorArgumentError + Specifies the locale to determine the justification rules for the text in a text block. + Standard locale identifiers are used. For example "en", "en_US" and "en-US" are all + English, "ja" is Japanese. + +
FontDescription + The FontDescription class represents the information necessary to describe a font.Object + The FontDescription class represents the information necessary to describe a font. + +

A FontDescription object is applied to an ElementFormat, + which is in turn applied to a ContentElement in a TextBlock. Once a FontDescription has been + applied to an ElementFormat, its locked property is set to true. + The properties of a locked FontDescription object cannot be changed. Instead, use the clone() + method to create an unlocked copy of the object, which can be modified and assigned to the ElementFormat.

+ +

Note: FTE (Flash Text Engine) does not support Type 1 fonts or bitmap fonts such as Type 3, + ATC, sfnt-wrapped CID, or Naked CID.

+ +

This example creates a FontDescription object, assigns + a device font to it, sets various font properties, + and assigns the new object to an ElementFormat object. + Additional font formatting is done within ElementFormat. A new + TextElement is created, using the ElementFormat, and + the TextElement is used as content for a TextBlock. A + line of text is created from the TextBlock.

+ + +package { + + import flash.display.Sprite; + import flash.text.engine.*; + + + public class FontDescriptionExample extends Sprite { + + public function FontDescriptionExample():void { + var fd:FontDescription = new FontDescription(); + fd.fontLookup = flash.text.engine.FontLookup.DEVICE; + fd.fontName = "Palatino"; + fd.fontWeight = flash.text.engine.FontWeight.BOLD; + fd.fontPosture = flash.text.engine.FontPosture.ITALIC; + + var ef1:ElementFormat = new ElementFormat(fd); + ef1.fontSize = 30; + ef1.color = 0xFF0000; + + var str:String = "This is flash text 0123456789"; + var tb:TextBlock = new TextBlock(); + var te1:TextElement = new TextElement(str, ef1); + tb.content = te1; + var line1:TextLine = tb.createTextLine(null, 600); + addChild(line1); + + } + } +} +
ElementFormat.fontDescriptionFontDescription + Creates a FontDescription object.The fontWeight specified is not a member of FontWeight. + ArgumentErrorArgumentErrorThe fontPosture specified is not a member of FontPosture. + ArgumentErrorArgumentErrorThe fontLookup specified is not a member of FontLookup. + ArgumentErrorArgumentErrorThe renderingMode specified is not a member of RenderingMode. + ArgumentErrorArgumentErrorThe cffHinting specified is not a member of CFFHinting. + + ArgumentErrorArgumentErrorfontNameString_serifThe name of the font to use, or a comma-separated list of font names. + fontWeightStringnormalSpecifies the font weight. + fontPostureStringnormalSpecifies the font posture. + fontLookupStringdeviceSpecifies how to look up the font. + renderingModeStringcffThe rendering mode used for this text. Use RenderingMode + constants for this property. + cffHintingStringhorizontalStemThe type of CFF (Compact Font Format) hinting used for this text. Use CFFHinting + constants for this property. + + Creates a FontDescription object. + + clone + Constructs an unlocked, cloned copy of the FontDescription.An unlocked copy of the FontDescription object. + + flash.text.engine:FontDescription + Constructs an unlocked, cloned copy of the FontDescription. + +

This example creates a FontDescription object, assigns + a device font to it, sets various font properties, + and assigns the new object (and therefore locking it) to an ElementFormat object. + A new TextElement is created, using the ElementFormat, and + the TextElement is used as content for a TextBlock. A + line of text is created from the TextBlock.

+

To modify the FontDescription object, first check its + locked property. If true, use the clone() method to + create an unlocked copy of the FontDescription, change its properties, + and assign it to a new ElementFormat object. Then re-link + the new ElementFormat to the TextBlock. + When the lines are re-broken, the new lines will have the new font settings.

+ + +package { + + import flash.display.Sprite; + import flash.text.engine.*; + + + public class FontDescription_cloneExample extends Sprite { + private var fd:FontDescription; + private var fd2:FontDescription; + + public function FontDescription_cloneExample():void { + fd = new FontDescription(); + fd.fontLookup = flash.text.engine.FontLookup.DEVICE; + fd.fontName = "Palatino"; + fd.fontWeight = flash.text.engine.FontWeight.BOLD; + fd.fontPosture = flash.text.engine.FontPosture.ITALIC; + + var ef1:ElementFormat = new ElementFormat(fd); + + var str:String = "This is flash text 0123456789"; + var tb:TextBlock = new TextBlock(); + var te1:TextElement = new TextElement(str, ef1); + tb.content = te1; + var line1:TextLine = tb.createTextLine(null, 600); + addChild(line1); + + fd2 = (fd.locked) ? fd.clone() : fd; + fd2.fontWeight = flash.text.engine.FontWeight.NORMAL; + var ef2:ElementFormat = new ElementFormat(fd2); + + tb.content.elementFormat=ef2; + var line2:TextLine = tb.createTextLine(null, 600); + addChild(line2); + + } + } +} +
isDeviceFontCompatible + Returns true if a usable device font is available with the specified fontName, fontWeight, and fontPosture.The fontWeight specified is not a member of FontWeight. + ArgumentErrorArgumentErrorThe fontPosture specified is not a member of FontPosture. + + ArgumentErrorArgumentErrortrue if a compatible device font is available, otherwise false. + + BooleanfontNameStringThe name of the device font to check. + fontWeightStringSpecifies the font weight. Use FontWeight. + fontPostureStringSpecifies the font posture. Use FontPosture. + + Returns true if a usable device font is available with the specified fontName, fontWeight, and fontPosture. + +

The flash.text.engine classes can only use OpenType and TrueType device fonts. If a font based on an older font technology is used, + the runtime falls back to known good device fonts on a glyph-by-glyph basis to render the text

+ +
fontLookupTextBlock.createTextLine()FontPostureFontWeight
isFontCompatible + Returns true if an embedded font is available with the specified fontName, fontWeight, and fontPosture + where Font.fontType is flash.text.FontType.EMBEDDED_CFF.The fontWeight specified is not a member of FontWeight. + ArgumentErrorArgumentErrorThe fontPosture specified is not a member of FontPosture. + + ArgumentErrorArgumentErrortrue if a compatible embedded font is available, otherwise false. + + BooleanfontNameStringThe name of the embedded font to check. + fontWeightStringSpecifies the font weight. Use FontWeight. + fontPostureStringSpecifies the font posture. Use FontPosture. + + Returns true if an embedded font is available with the specified fontName, fontWeight, and fontPosture + where Font.fontType is flash.text.FontType.EMBEDDED_CFF. Starting with Flash Player 10, + two kinds of embedded fonts can appear in application content. Normal embedded fonts are only used by TextField. + CFF embedded fonts are only used by the flash.text.engine classes. The two types are distinguised by the + fontType property of the Font class, as returned by the enumerateFonts() function. + +

The flash.text.engine classes cannot use a font of type EMBEDDED. If fontLookup is set + to FontLookup.EMBEDDED_CFF and the only font available at run time with the specified name, weight, and posture is of type + EMBEDDED, the runtime falls back to device fonts on a glyph-by-glyph basis to render the text, + as if no embedded font were available with the specified name and style.

+ +

If both EMBEDDED and EMBEDDED_CFF fonts are available with the same name, weight, and posture, the EMBEDDED_CFF + font is selected and text renders with the EMBEDDED_CFF font.

+ +
fontLookupTextBlock.createTextLine()FontType.EMBEDDED_CFFFontPostureFontWeight
cffHinting + The type of CFF hinting used for this text.StringIf set to any value which is not a member of CFFHinting. + ArgumentErrorArgumentErrorIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The type of CFF hinting used for this text. Use CFFHinting + constants for this property. This property applies only if the + RenderingMode property of the text is set to RenderingMode.CFF. + +

The type of CFF (Compact Font Format) hinting used determines whether the Flash runtime forces strong horizontal + stems to fit to a sub-pixel grid or not.

+ +

Applies only to embedded fonts.

+ +

The default value is CFFHinting.HORIZONTAL_STEM.

+ +

For the CFFHinting property, you can use the following constants from the CFFHinting class:

+ + String valueDescriptionCFFHinting.NONESpecifies no CFF hinting. Horizontal stems in the glyphs are not + forced to the sub-pixel grid. This setting is appropriate for animation or + for large font sizes.CFFHinting.HORIZONTAL_STEMSpecifies CFF hinting. Strong horizontal stems are fit to the sub-pixel grid on + a screen. To use this setting, the + RenderingMode property must be set to RenderingMode.CFF. + +
CFFHintingFontDescription.renderingModeRenderingMode
fontLookup + Specifies how the font should be looked up.StringIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies how the font should be looked up. + +

The default value is FontLookup.DEVICE.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionFontLookup.DEVICEThe runtime looks up a device font with the specified name + on the local system with which to render the text.FontLookup.EMBEDDED_CFFThe runtime looks up an embedded CFF font with the specified name + with which to render the text. Only fonts of type flash.text.Font.fontType.EMBEDDED_CFF + are considered. + If the specified CFF font is not embedded in the application, the runtime attempts + to use a fallback device font for each glyph. This method is less efficient + than selecting a device font in the first place. + +
CFFHintingFontLookup
fontName + The name of the font to use, or a comma-separated list of font names.StringIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The name of the font to use, or a comma-separated list of font names. The runtime renders + the element with the first available font in the list. For example "Arial, Helvetica, _sans" + causes the player to search for Arial, then Helvetica, if Arial is not found, then _sans, if neither is found. + +

Flash runtimes support three generic device font names: _sans (for sans serif fonts), _serif (for serif fonts), + and _typewriter (for mono-space fonts). These are mapped to specific device fonts depending on the platform.

+ +

The default value is "_serif".

+ +

Flash runtimes provide font fallback for glyphs which are not found in the selected font. + Whether the font in use is embedded or device, if the glyph is not found in the font, + the runtime attempts to render it using another device font likely to contain the glyph.

+ +
FontLookup
fontPosture + Specifies the font posture.StringIf set to any value which is not a member of FontPosture. + ArgumentErrorArgumentErrorIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies the font posture. + + +

The default value is FontPosture.NORMAL.

+ +

To set values for this property, use the following constants from the FontPosture class:

+ + ValueDescriptionFontPosture.NORMALNormal font posture.FontPosture.ITALICItalic font posture. + +
FontPosture
fontWeight + Specifies the font weight.StringIf set to any value which is not a member of FontWeight. + ArgumentErrorArgumentErrorIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Specifies the font weight. + + +

The default value is FontWeight.NORMAL.

+ +

To set values for this property, use the following constants from the FontWeight class:

+ + String valueDescriptionFontWeight.NORMALNormal font weight.FontWeight.BOLDBold font weight. + +
FontWeight
locked + Indicates whether or not the FontDescription is locked.BooleanIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + Indicates whether or not the FontDescription is locked. If true the FontDescription cannot be modified. + Call FontDescription.clone() to get an unlocked copy of the FontDescription object. + + renderingMode + The rendering mode used for this text.StringIf set to any value which is not a member of RenderingMode. + ArgumentErrorArgumentErrorIf set after the FontDescription object is locked (locked is true). + + IllegalOperationErrorflash.errors:IllegalOperationError + The rendering mode used for this text. Use RenderingMode + constants for this property. + +

Applies only to embedded fonts.

+ +

The default value is RenderingMode.CFF.

+ +

To set values for this property, use the following constants from the RenderingMode class:

+ + String valueDescriptionRenderingMode.NORMALApplies the regular text rendering, which matches the type of rendering that + Flash Player 7 and earlier versions used.RenderingMode.CFFApplies CFF (Compact Font Format) rendering, which makes text more legible. (This feature became + available in Flash Player 10.) CFF rendering allows for high-quality rendering + of font faces at small sizes. + +
RenderingMode
GroupElement + A GroupElement object groups a collection of TextElement, GraphicElement, or other GroupElement objects + that you can assign as a unit to the content property of a TextBlock object.flash.text.engine:ContentElement + A GroupElement object groups a collection of TextElement, GraphicElement, or other GroupElement objects + that you can assign as a unit to the content property of a TextBlock object. A GroupElement + object can also simply share common formatting within another GroupElement object. + +

When a GroupElement contains another GroupElement, the inner GroupElement retains its own formatting (ElementFormat settings). It does + not inherit the formatting of the outer GroupElement.

+ +

On a GroupElement, most of the format properties have no impact. For this reason, it is legal to create a text line for a GroupElement object + that has a null elementFormat parameter. A few format properties such as kerning and ligature + do affect formatting where intersections occur between members of the group. If the group has a null format, the format of the preceding + element determines the formatting where intersections occur between members of the group.

+ +
This example creates a red box as a GraphicElement object and combines + it with two TextElement objects to create a GroupElement object. It assigns the GroupElement + object to the content property of a TextBlock, from which it creates three lines. + + +package { + + import flash.display.Sprite; + import flash.display.MovieClip; + import flash.text.engine.ContentElement; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.GraphicElement; + import flash.text.engine.GroupElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + + public class GroupElementExample extends Sprite { + + public function GroupElementExample():void { + + var redBox:MovieClip = new MovieClip(); + redBox.graphics.beginFill(0xCC0000, 1.0); + redBox.graphics.drawRect(0, 0, 20, 20); + redBox.graphics.endFill(); + + var format:ElementFormat = new ElementFormat(); + var fontDescription:FontDescription = new FontDescription("Arial"); + format.fontSize = 16; + format.fontDescription = fontDescription; + + var str1:String = "This red box is a GraphicElement "; + var str2:String = " in the middle of two TextElements, " + + " which together make " + + "up a GroupElement in a TextBlock that is broken into three lines."; + + var textElement1:TextElement = new TextElement(str1,format); + var graphicElement:GraphicElement = new GraphicElement(redBox,redBox.width,redBox.height, format); + var textElement2:TextElement = new TextElement(str2, format); + var groupVector:Vector.<ContentElement> = new Vector.<ContentElement>(); + groupVector.push(textElement1, graphicElement, textElement2); + var groupElement = new GroupElement(groupVector); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = groupElement; + createTextLines(textBlock); + } + + private function createTextLines(textBlock:TextBlock):void + { + + var yPos = 20; + var line_length:Number = 450; + var textLine:TextLine = textBlock.createTextLine (null, line_length); + + while (textLine) + { + addChild(textLine); + textLine.x = 15; + yPos += textLine.height+8; + textLine.y = yPos; + textLine = textBlock.createTextLine(textLine, line_length); + } + } + } +} + + +
ContentElementGraphicElementTextBlockTextElementGroupElement + Creates a new GroupElement instance.The specified element contains null elements. + ArgumentErrorArgumentErrorThe specified element contains an element that is not a known subclass of ContentElement. + ArgumentErrorArgumentErrorThe specified element contains elements that are specified as the content of a TextBlock. + ArgumentErrorArgumentErrorThe specified element contains elements that are already members of a group, or appear more than once in + the elements. + ArgumentErrorArgumentErrorelementsnullA Vector of ContentElement objects to be contained in the GroupElement. + The Vector can be empty. The default value is null. + elementFormatflash.text.engine:ElementFormatnullThe element format for the group. The default value is null. + This format applies to the intersections between elements in the group; those elements do not inherit the format. + eventMirrorflash.events:EventDispatchernullThe EventDispatcher object that receives copies of every + event dispatched to text lines created based on this content element. The default value is null. + textRotationStringrotate0The rotation applied to the element as a unit. Use TextRotation constants for + this property. The default value is TextRotation.ROTATE_0. + + Creates a new GroupElement instance. + + ContentElementElementFormatflash.events.EventDispatcherTextLineMirrorRegionTextRotationgetElementAtCharIndex + Returns the element containing the character specified by the charIndex parameter.If charIndex is not in the range of 0 - rawText.length. + + RangeErrorRangeErrorThe element containing the character at charIndex. + + flash.text.engine:ContentElementcharIndexintThe zero-based index value for the character whose element you want to find. + A value of 0 corresponds to the first character in the group, not the first character in the TextBlock. + + + Returns the element containing the character specified by the charIndex parameter. + + getElementAt + Retrieves an element from within the group.If index is out of range. + + RangeErrorRangeErrorflash.text.engine:ContentElementindexintThe index of the element to retrieve. + + + Retrieves an element from within the group. + + getElementIndex + Returns the index of the element specified by the element parameter.The index of the element specified by element, or -1 if the element is not in the group. + + intelementflash.text.engine:ContentElementThe element in the group whose index you want to retrieve. + + + Returns the index of the element specified by the element parameter. + + groupElements + Replaces the range of elements that the beginIndex and endIndex + parameters specify with a new GroupElement containing those elements.If beginIndex or endIndex is out of range. + + RangeErrorRangeErrorThe new group. + + flash.text.engine:GroupElementbeginIndexintThe zero-based index value for the start position of the range to group. + endIndexintThe zero-based index value following the end position of the range to group. + + Replaces the range of elements that the beginIndex and endIndex + parameters specify with a new GroupElement containing those elements. + As designed, the elements from beginIndex to endIndex-1 are replaced. + + mergeTextElements + Merges the text from the range of elements that the beginIndex and endIndex + parameters specify into the element specified by beginIndex without affecting the format of that element.If beginIndex or endIndex is out of range. + RangeErrorRangeErrorIf any of the elements in the specified range is not TextElement. + + ArgumentErrorArgumentErrorThe first text element in the range, now containing all the text in the range. + + flash.text.engine:TextElementbeginIndexintThe zero-based index value for the start position of the range to merge. + endIndexintThe zero-based index value following the end position of the range to merge. + + Merges the text from the range of elements that the beginIndex and endIndex + parameters specify into the element specified by beginIndex without affecting the format of that element. + As designed, the text from elements from beginIndex to endIndex-1 are merged. + After their text has been merged, elements from beginIndex+1 to endIndex-1 are removed from the group and orphaned, + with null group properties. + + TextElementreplaceElements + Replaces the range of elements that the beginIndex and + endIndex parameters specify with the contents + of the newElements parameter.The beginIndex or endIndex specified is out of range. + RangeErrorRangeErrorThe newElements specified contain null elements. + ArgumentErrorArgumentErrorThe newElements specified contain this. + ArgumentErrorArgumentErrorThe newElements specified contain elements that are not a known subclass of ContentElement . + ArgumentErrorArgumentErrorThe newElements specified contain elements that are specified as the content of a TextBlock. + ArgumentErrorArgumentErrorThe newElements specified contain elements that are already members of a group or appear + more than once in the elements. + ArgumentErrorArgumentErrorIf the operation would result in nested rotations within the GroupElement. + + ArgumentErrorArgumentErrorA Vector containing the elements that were replaced. + + beginIndexintThe zero-based index value for the start position of the replacement range. + endIndexintThe zero-based index value following the end position of the replacement range. + newElementsThe elements to use to replace the specified range of elements. + + Replaces the range of elements that the beginIndex and + endIndex parameters specify with the contents + of the newElements parameter. + The elements from beginIndex to endIndex-1 are replaced. +

To delete elements, pass null for newElements. + To insert an element, pass the same value for beginIndex and endIndex. + The new element is inserted before the specified index. + To append an element, pass elementCount for beginIndex and endIndex.

+

After the operation, the replaced elements are orphaned, with null group properties and returned.

+
setElements + Sets the elements in the group to the contents of the Vector.The value specified contains null elements. + ArgumentErrorArgumentErrorThe value specified contains this. + ArgumentErrorArgumentErrorThe value specified contains elements that are not a known subclass of ContentElement . + ArgumentErrorArgumentErrorThe value specified contains elements that are specified as the content of a TextBlock. + ArgumentErrorArgumentErrorThe value specified contains elements that are already members of a group, or appear more than once + in the value. + ArgumentErrorArgumentErrorIf the operation would result in nested rotations within the GroupElement. + + ArgumentErrorArgumentErrorvalue + Sets the elements in the group to the contents of the Vector. + + splitTextElement + Splits a TextElement into two, creating a new TextElement at the specified position.If elementIndex or charIndex is out of range. + RangeErrorRangeErrorIf the element at elementIndex is not a TextElement. + + ArgumentErrorArgumentErrorThe new text element containing the latter portion of the original text element. + + flash.text.engine:TextElementelementIndexintThe zero-based index value for the position of the element in the group. + splitIndexintThe zero-based index value for the character in the TextElement where the split is to occur. + The specified character is the first character in the new TextElement. + + Splits a TextElement into two, creating a new TextElement at the specified position. + + TextElementungroupElements + Ungroups the elements in a nested GroupElement that groupIndex specifies within an outer + GroupElement object.If groupIndex is out of range. + RangeErrorRangeErrorIf the element at groupIndex is not a GroupElement. + + ArgumentErrorArgumentErrorgroupIndexintThe zero-based index value for the position of the group to be split. + + + Ungroups the elements in a nested GroupElement that groupIndex specifies within an outer + GroupElement object. After the operation, the ungrouped elements replace the nested GroupElement, which becomes an orphan + with a null group property. + + elementCount + The number of elements in the group.int + The number of elements in the group. + +
ContentElement + The ContentElement class serves as a base class for the element types that can appear in a GroupElement, namely a GraphicElement, + another GroupElement, or a TextElement.Object + The ContentElement class serves as a base class for the element types that can appear in a GroupElement, namely a GraphicElement, + another GroupElement, or a TextElement. + +

ContentElement is an abstract base class; therefore, you cannot instantiate ContentElement directly. + Invoking new ContentElement() throws an ArgumentError exception.

+ +

You can assign a ContentElement element to exactly one GroupElement or to the content property of exactly one text + block.

+ +
ElementFormatGraphicElementGroupElementTextBlock.contentTextElementTextLineMirrorRegionTextRotationContentElement + Calling the new ContentElement() constructor throws an + ArgumentError exception.elementFormatflash.text.engine:ElementFormatnullThe element format for the text in the element. The default value is null. + eventMirrorflash.events:EventDispatchernullThe EventDispatcher object that receives copies of every + event dispatched to valid text lines created based on this content element. The default value is null. + textRotationStringrotate0The rotation applied the element as a unit. Use TextRotation + constants for this property. The default value is TextRotation.ROTATE_0. + + Calling the new ContentElement() constructor throws an + ArgumentError exception. You can, however, call constructors for + the following subclasses of ContentElement: + +
  • new GraphicElement()
  • new GroupElement()
  • new TextElement()
+ +
GRAPHIC_ELEMENT + Indicates the presence of a graphic element in the text.0xFDEFuint + Indicates the presence of a graphic element in the text. + + rawTextuserData + Provides a way for an application to associate arbitrary data with the element. + Provides a way for an application to associate arbitrary data with the element. + +

The default value is null.

+ +
elementFormat + The ElementFormat object used for the element.flash.text.engine:ElementFormat + The ElementFormat object used for the element. + +

The default value is null.

+ +

When the elementFormat property is set, the ElementFormat object provided is locked: its locked + property is set to true. A locked ElementFormat cannot be modified.

+ +
ElementFormatTextBlockTextElement
eventMirror + The EventDispatcher object that receives copies of every + event dispatched to valid text lines based on this content element.flash.events:EventDispatcher + The EventDispatcher object that receives copies of every + event dispatched to valid text lines based on this content element. + The specified object can be used to set up listeners for a text link or other + interactive piece of text, as it can be difficult to determine at runtime which parts + of lines have resulted from particular content elements. + You can also use listeners to apply decorations such as underlines, the metrics of which + you cannot determine until after the text is laid out. + The default value is null, which means no mirrored events are dispatched. + +

Event mirrors manifest themselves in text lines as instances of the TextLineMirrorRegion + class. Depending on bidirectional processing and line breaking, one or more mirror regions can be produced.

+ +

The default value is null.

+ +
flash.events.EventDispatcherTextLineMirrorRegion
groupElement + The GroupElement object that contains this element, or + null if it is not in a group.flash.text.engine:GroupElement + The GroupElement object that contains this element, or + null if it is not in a group. + +

The default value is null.

+ +
GroupElement
rawText + A copy of the text in the element, including any U+FDEF characters.String + A copy of the text in the element, including any U+FDEF characters. The Unicode character, U+FDEF, marks the location of + a graphic element in the String. + + textBlockBeginIndex + The index in the text block of the first character of this element.int + The index in the text block of the first character of this element. + This value is not cached; it is calculated whenever this method is called. + +

The default value is -1.

+ +
textBlock + The TextBlock to which this element belongs.flash.text.engine:TextBlock + The TextBlock to which this element belongs. + +

The default value is null.

+ +
TextBlock
textRotation + The rotation to apply to the element as a unit.StringIf set to any value that is not a member of TextRotation. + ArgumentErrorArgumentErrorIf set to TextRotation.AUTO. + ArgumentErrorArgumentErrorIf the operation would result in nested rotations within a GroupElement. + + ArgumentErrorArgumentError + The rotation to apply to the element as a unit. Use TextRotation + constants for this property. + +

The default value is TextRotation.ROTATE_0.

+ +

The final rotation of any glyph is the sum of ElementFormat.textRotation, ContentElement.textRotation, and TextBlock.lineRotation.

+ +

ContentElement.textRotation is used to create a short run of text whose + rotation differs from the containing line. TCY runs in Japanese text are an example. TCY stands for Tate-Chu-Yoko + and refers to a little horizontal run of text (usually a number) in some vertical Japanese text. + To create a Paragraph of vertical Japanese text containing a TCY run, do the following:

+
  1. Set TextBlock.lineRotation=TextRotation.ROTATE_90
  2. Set TextBlock.content to a GroupElement, consisting of three TextElement objects. + The first of these elements is the Japanese text before the TCY run, the second is the Latin text of the TCY run, and the third is + the Japanese text after the TCY run.
  3. Set the textRotation property of the TCY TextElement to TextRotation.ROTATE_270. + The TCY text element rotates as a unit. It starts with a 90 degree rotation inherited + from the line. Adding another 270 degrees takes it around to horizontal.
+ +

Rotated content elements cannot be nested. In any hierarchy of content elements, no matter how complex, + only one content element can have its textRotation property set. The following methods and property setters throw an + argument error if nested rotations are detected:

+
  1. ContentElement.textRotation
  2. GroupElement.setElements
  3. GroupElement.replaceElements
+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTextRotation.ROTATE_0Element is not rotated.TextRotation.ROTATE_90Element is rotated 90 degrees clockwise.TextRotation.ROTATE_180Element is rotated 180 degrees.TextRotation.ROTATE_270Element is rotated 270 degrees clockwise.TextRotation.AUTONot supported. + +
TextRotationElementFormat.textRotationTextBlock.lineRotation
text + A copy of the text in the element, not including any U+FDEF characters, which represent graphic elements in the String.String + A copy of the text in the element, not including any U+FDEF characters, which represent graphic elements in the String. + + TextElement.text
TextBlock + The TextBlock class is a factory for the creation of TextLine objects, which you can + render by placing them on the display list.Object + The TextBlock class is a factory for the creation of TextLine objects, which you can + render by placing them on the display list. + +

The TextBlock class is intended to contain a single paragraph because the Unicode + bidirectional and line-break algorithms operate on one paragraph at a time. For applications + that compose multiple paragraphs of text, use a markup language, or text analysis to + divide the text into paragraphs and create one TextBlock per paragraph.

+ +

The TextBlock object stores its content in the content property, which is an + instance of the ContentElement class. Because you can't create an instance of the ContentElement + class, set content to an instance of one of its subclasses: TextElement, + GraphicElement, or GroupElement. Use TextElement for purely text content, GraphicElement for + an image or graphic content, and GroupElement for content that contains a combination of TextElement, + GraphicElement, and other GroupElement objects. See the ContentElement class and + its subclasses for details on managing formatted runs of text, embedded sub-runs, and graphic elements.

+ +

After you create the TextBlock instance and set the content property, call the + createTextLine() method to create lines of text, which are instances of the TextLine class.

+ +
This example displays three TextBlock paragraphs of Japanese and English + text. The Japanese text is converted to Strings from Unicode character codes. + When you click on the button, the example rotates the text from horizontal to + vertical or from veritcal to horizontal. + +package { + import fl.controls.Button; + import flash.text.engine.TextBlock; + import flash.text.engine.TextLine; + import flash.text.engine.TextElement; + import flash.text.engine.ElementFormat; + import flash.text.engine.TextRotation; + import flash.text.engine.TextBaseline; + import flash.text.engine.LineJustification; + import flash.text.engine.FontDescription; + import flash.text.engine.EastAsianJustifier; + import flash.display.Loader; + import flash.display.Sprite; + import flash.display.Stage; + import flash.events.MouseEvent; + import flash.system.Capabilities; + + public class TextBlockExample extends Sprite { + + var vertical:Boolean; + var container:Sprite; + var textBlocks:Vector.<TextBlock>; + var loader:Loader = new Loader(); + var directionButton:Button = new Button(); + + public function TextBlockExample():void { + addChild(directionButton); + directionButton.width = 30; + directionButton.move(50, 350); + directionButton.addEventListener(MouseEvent.CLICK, clickHandler); + createContent(); + createLines(); + } + + private function createEmptyBlock():TextBlock { + + var textBlock:TextBlock = new TextBlock(); + textBlock.baselineZero = TextBaseline.IDEOGRAPHIC_CENTER; + textBlock.textJustifier = new EastAsianJustifier("ja", LineJustification.ALL_BUT_LAST); + textBlock.lineRotation = vertical? TextRotation.ROTATE_90: TextRotation.ROTATE_0; + return textBlock; + } + + private function paragraph1(format:ElementFormat):TextBlock { + + var textBlock:TextBlock = createEmptyBlock(); + textBlock.content = new TextElement( + String.fromCharCode( + 0x5185, 0x95A3, 0x5E9C, 0x304C, 0x300C, 0x653F, 0x5E9C, 0x30A4, + 0x30F3, 0x30BF, 0x30FC, 0x30CD, 0x30C3, 0x30C8, 0x30C6, 0x30EC, + 0x30D3, 0x300D, 0x306E, 0x52D5, 0x753B, 0x914D, 0x4FE1, 0x5411, + 0x3051, 0x306B, 0x30A2, 0x30C9, 0x30D3, 0x30B7, 0x30B9, 0x30C6, + 0x30E0, 0x30BA, 0x793E, 0x306E + ) + + "FMS 2" + + String.fromCharCode(0x3092, 0x63A1, 0x7528, 0x3059, 0x308B, 0x3068, + 0x767a, 0x8868, 0x3057, 0x307e, 0x3057, 0x305F, 0x3002), format); + return textBlock; + } + + private function paragraph2(format:ElementFormat):TextBlock { + + var textBlock:TextBlock = createEmptyBlock(); + textBlock.content = new TextElement( + String.fromCharCode( + 0x30AF, 0x30ED, 0x30B9, 0x30D7, 0x30E9, 0x30C3, 0x30C8, 0x30D5, + 0x30A9, 0x30FC, 0x30E0, 0x4E0A, 0x3067, 0x518D, 0x751F, 0x53EF, + 0x80FD, 0x306A + ) + + "Flash Video" + + String.fromCharCode( + 0x3092, 0x914D, 0x4FE1, 0x3001, 0x653F, 0x5E9C, 0x6700, 0x65B0, + 0x60C5, 0x5831, 0x3092, 0x3088, 0x308A, 0x591A, 0x304F, 0x306E, + 0x56FD, 0x6C11, 0x306B, 0x9AD8, 0x54C1, 0x8CEA, 0x306A, 0x753B, + 0x50CF, 0x3067, 0x7C21, 0x5358, 0x304B, 0x3064, 0x30EA, 0x30A2, + 0x30EB, 0x30BF, 0x30A4, 0x30E0, 0x306B, 0x63D0, 0x4F9B, 0x3059, + 0x308B, 0x3053, 0x3068, 0x304C, 0x53EF, 0x80FD, 0x306B, 0x306A, + 0x308A, 0x307e, 0x3057, 0x305F, 0x3002), format); + return textBlock; + } + + private function paragraph3(format:ElementFormat):TextBlock { + + var textBlock:TextBlock = createEmptyBlock(); + textBlock.content = new TextElement( + String.fromCharCode(0x3010) + + "2007" + + String.fromCharCode(0x5E74) + "2" + String.fromCharCode(0x6708) + + "21" + + String.fromCharCode(0x65E5, 0x3011), + format); + return textBlock; + } + + private function createContent():void { + + var font:FontDescription = new FontDescription(); + if (Capabilities.os.search("Mac OS") > -1) + font.fontName = String.fromCharCode(0x5C0F, 0x585A, 0x660E, 0x671D) + " Pro R"; // "Kozuka Mincho Pro R" koFont.fontName = "Adobe " + String.fromCharCode(0xBA85, 0xC870) + " Std M"; // "Adobe Myungjo Std M" + else + font.fontName = "Kozuka Mincho Pro R"; + var format:ElementFormat = new ElementFormat(); + format.fontDescription = font; + format.fontSize = 12; + format.locale = "ja"; + format.color = 0x000000; + if (!vertical) + format.textRotation = TextRotation.ROTATE_0; + textBlocks = new Vector.<TextBlock>(); + textBlocks.push( + paragraph1(format), + paragraph2(format), + paragraph3(format)//, + ); + } + + private function createLines():void { + + if (container != null) { + removeChild(container); + } + container = new Sprite(); + container.y = 45; + container.x = 40; + addChild(container); + var linePosition:Number = vertical? this.stage.stageWidth - 120: 12; + + for (var i:uint = 0; i < textBlocks.length; i++) { + var textBlock:TextBlock = textBlocks[i]; + var previousLine:TextLine = null; + + while (true) { + var textLine:TextLine = textBlock.createTextLine( + previousLine, + 300); + if (textLine == null) + break; + if (vertical) + { + textLine.x = linePosition; + linePosition -= 24; + directionButton.label = " -- "; + } + else + { + textLine.y = linePosition+50; + linePosition += 24; + directionButton.label = " | "; + } + container.addChild(textLine); + previousLine = textLine; + } + if (vertical) + linePosition -= 16; + else + linePosition += 16; + } + } + + private function clickHandler(event:MouseEvent):void { + + vertical = !vertical; + createContent(); + createLines(); + } + } +} +
ContentElementGraphicElementGroupElementTextBaselineTextElementTextJustifierTextLineTextRotationTabStopTextBlock + Creates a TextBlock object + + The content specified is not a known subclass of ContentElement. + ArgumentErrorArgumentErrorThe content specified is already a member of a group. + ArgumentErrorArgumentErrorThe lineRotation specified is not a member of TextRotation. + ArgumentErrorArgumentErrorThe baselineZero specified is not a member of TextBaseline. + ArgumentErrorArgumentErrorThe bidiLevel specified is less than 0. + ArgumentErrorArgumentErrorThe tabStops specified contain null elements. + ArgumentErrorArgumentErrorThe tabStops specified are not sorted by increasing position. + ArgumentErrorArgumentErrorThe baselineFontSize specified is less than 0. + + ArgumentErrorArgumentErrorcontentflash.text.engine:ContentElementnullThe contents of the text block. + tabStopsnullThe tab stops for the text in the text block. + textJustifierflash.text.engine:TextJustifiernullThe TextJustifier object to use during line creation for this block. + If no justifier is provided, a default justifier is constructed based on an English locale. + lineRotationStringrotate0The rotation applied to the text lines generated from the text block as units. + baselineZeroStringromanSpecifies which baseline is at y=0 for all lines in the block. + bidiLevelint0The default bidirectional embedding level of the text in the text block. + applyNonLinearFontScalingBooleantrueSpecifies that you want to enhance screen appearance at the expense of WYSIWYG print fidelity. + baselineFontDescriptionflash.text.engine:FontDescriptionnullSpecifies a font description from which to derive line baselines for all lines in the block. + baselineFontSizeNumber12.0Specifies the size to use with the baselineFontDescription. + This parameter is ignored if baselineFontDescription is null. + + Creates a TextBlock object + + applyNonLinearFontScalingbaselineFontDescriptionbaselineFontSizebaselineZerobidiLevellineRotationtabStopsTextJustifiercreateTextLine + Instructs the text block to create a line of text from its content, beginning at the point + specified by the previousLine parameter and breaking at the point specified by the + width parameter.If the TextLine specified by previousLine is not valid. + ArgumentErrorArgumentErrorIf the TextLine specified by previousLine is owned by a different TextBlock. + ArgumentErrorArgumentErrorIf width is less than zero, unless fitSomething is true. + ArgumentErrorArgumentErrorIf width is greater than TextLine.MAX_LINE_WIDTH. + ArgumentErrorArgumentErrorIf one or more elements in the content of the text block has a null ElementFormat. + IllegalOperationErrorflash.errors:IllegalOperationErrorA text line, or null if the text block is empty or the width specified is less than the width of the next element. + To distinguish between these cases, check the textLineCreationResult property of the text block. + + flash.text.engine:TextLinepreviousLineflash.text.engine:TextLinenullSpecifies the previously broken line after which breaking is to commence. Can be null + when breaking the first line. + widthNumber1000000Specifies the desired width of the line in pixels. The actual width may be less. + lineOffsetNumber0.0An optional parameter which specifies the difference in pixels between the origin of the line and the origin of the tab stops. + This can be used when lines are not aligned, but it is desirable for their tabs to be so. + The default value for this parameter is 0.0. + fitSomethingBooleanfalseAn optional parameter which instructs Flash Player to fit at least one character into the text line, no matter what + width has been specified (even if width is zero or negative, which would otherwise result in an exception being thrown). + + + Instructs the text block to create a line of text from its content, beginning at the point + specified by the previousLine parameter and breaking at the point specified by the + width parameter. The text line is a TextLine object, which you can add + to the display list. + +

Breaking lines over a range of a text block that has already been broken can change the validity + of lines in and beyond the area where breaking takes place. The status of lines can change from VALID to INVALID or + POSSIBLY_INVALID. If a newly broken line aligns perfectly with a previously broken line which has a status + of POSSIBLY_INVALID, that previously broken line and all following POSSIBLY_INVALID lines change back + to a status of VALID. The validity of lines that have been set to values that are not members of + TextLineValidity do not change to VALID, but could change to INVALID. + Check the firstInvalidLine property after any change to the text block + to see where to begin or continue rebreaking text lines.

+ +

You can create artificial word breaks by including the Unicode Zero Width Space (ZWSP) character in the text. + This can be useful for languages such as Thai, which require a dictionary for correct line breaking. + The Flash runtime does not include such a dictionary.

+ +

In order to reduce memory overhead, when all the desired lines have been created, unless it is expected that the + lines will need to be repeatedly rebroken due to, for example, the resizing of the container, the user should call + the releaseLineCreationData() method allowing the text block to dispose of the temporary data associated with line breaking.

+ +
This example calls the createTextLine() method to create + lines of text in a text block. It accomplishes this by performing the following tasks: +
  • Creating a TextElement from a String and giving it a font size of 20
  • Creating a TextBlock and assigning the TextElement to it
  • Calling createTextLine() to create lines 300 pixels wide from the text block
  • Placing each line on Stage (addChild()) and setting its position (x and y)
+ + +package { + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + + public class TextBlock_createTextLineExample extends Sprite { + + public function TextBlock_createTextLineExample():void { + + var str:String = "I am a TextElement, created from a String and assigned " + + "to the content property of a TextBlock. The createTextLine() method " + + "then created these lines, 300 pixels wide, for display." ; + + var fontDescription:FontDescription = new FontDescription("Arial"); + var format:ElementFormat = new ElementFormat(fontDescription); + format.fontSize = 16; + var textElement:TextElement = new TextElement(str, format); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = textElement; + createLines(textBlock); + } + + private function createLines(textBlock:TextBlock):void + { + var lineWidth:Number = 300; + var xPos:Number = 15.0; + var yPos:Number = 20.0; + + var textLine:TextLine = textBlock.createTextLine (null, lineWidth); + while (textLine) + { + textLine.x = xPos; + textLine.y = yPos; + yPos += textLine.height + 2; + addChild (textLine); + textLine = textBlock.createTextLine (textLine, lineWidth); + } + } + } +} +
TextLineTextLine.validityTextLineValidityTextBlock.releaseLineCreationData()
dump + Dumps the underlying contents of the TextBlock as an XML string.String + Dumps the underlying contents of the TextBlock as an XML string. + This can be useful in automated testing, and includes text, formatting, and layout information. + +

The following describes the output:

+ +
+	 >block<
+	 	[0-N LINE]
+	 >/block<
+	 
+ +

For a description of the output for each line, see the TextLine.dump() method.

+ +

Note: The content and format of the output may change in the future. Adobe does not guarantee backward compatibility + of this method.

+ +
TextLine.dump()
findNextAtomBoundary + Finds the index of the next atom boundary from the specified character index, not including the character at the specified index.The index specified is out of range. + RangeErrorRangeErrorThe TextLine to which the indexed character belongs is not valid. + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the next atom boundary from the specified character index. + + intafterCharIndexintSpecifies the index of the character from which to search for the next atom boundary. + + Finds the index of the next atom boundary from the specified character index, not including the character at the specified index. + The characters between atom boundaries combine to form one atom in a TextLine, such as an 'e' and a combining acute accent. + + TextLine.atomCountfindNextWordBoundary + Finds the index of the next word boundary from the specified character index, not including the character at the specified index.The index specified is out of range. + RangeErrorRangeErrorThe TextLine to which the indexed character belongs is not valid. + + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the next word boundary from the specified character index. + + intafterCharIndexintSpecifies the index of the character from which to search for the next word boundary. + + Finds the index of the next word boundary from the specified character index, not including the character at the specified index. + Word boundaries are determined based on the Unicode properties of the characters. + + findPreviousAtomBoundary + Finds the index of the previous atom boundary to the specified character index, not including the character at the specified index.The index specified is out of range. + RangeErrorRangeErrorThe TextLine to which the indexed character belongs is not valid. + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the previous atom boundary to the specified character index. + + intbeforeCharIndexintSpecifies the index of the character from which to search for the previous atom boundary. + + Finds the index of the previous atom boundary to the specified character index, not including the character at the specified index. + The characters between atom boundaries combine to form one atom in a TextLine, such as an 'e' and a combining acute accent. + + TextLine.atomCountfindPreviousWordBoundary + Finds the index of the previous word boundary to the specified character index, not including the character at the specified index.The index specified is out of range. + RangeErrorRangeErrorThe TextLine to which the indexed character belongs is not valid. + + IllegalOperationErrorflash.errors:IllegalOperationErrorThe index of the previous word boundary to the specified character index. + + intbeforeCharIndexintSpecifies the index of the character from which to search for the previous word boundary. + + Finds the index of the previous word boundary to the specified character index, not including the character at the specified index. + Word boundaries are determined based on the Unicode properties of the characters. + + getTextLineAtCharIndex + Returns the TextLine containing the character specified by the charIndex parameter.The character index specified is out of range. + + RangeErrorRangeErrorThe TextLine containing the character at charIndex. + + flash.text.engine:TextLinecharIndexintThe zero-based index value of the character (for example, the first character is 0, + the second character is 1, and so on). + + + Returns the TextLine containing the character specified by the charIndex parameter. + + recreateTextLine + Instructs the text block to re-use an existing text line to create a line of text from its content, beginning at the point + specified by the previousLine parameter and breaking at the point specified by the + width parameter.If textLine is null. + ArgumentErrorArgumentErrorIf the TextLine specified by previousLine is not valid. + ArgumentErrorArgumentErrorIf the TextLine specified by previousLine is owned by a different TextBlock. + ArgumentErrorArgumentErrorIf the TextLine specified by previousLine is also specified by textLine. + ArgumentErrorArgumentErrorIf width is less than zero, unless fitSomething is true. + ArgumentErrorArgumentErrorIf width is greater than TextLine.MAX_LINE_WIDTH. + ArgumentErrorArgumentErrorIf one or more elements in the content of the text block has a null ElementFormat. + IllegalOperationErrorflash.errors:IllegalOperationErrorA text line, or null if the text block is empty or the width specified is less than the width of the next element. + To distinguish between these cases, check the textLineCreationResult property of the text block. + + flash.text.engine:TextLinetextLineflash.text.engine:TextLineSpecifies a previously created TextLine to be re-used. + previousLineflash.text.engine:TextLinenullSpecifies the previously broken line after which breaking is to commence. Can be null + when breaking the first line. + widthNumber1000000Specifies the desired width of the line in pixels. The actual width may be less. + lineOffsetNumber0.0An optional parameter which specifies the difference in pixels between the origin of the line and the origin of the tab stops. + This can be used when lines are not aligned, but it is desirable for their tabs to be so. + The default value for this parameter is 0.0. + fitSomethingBooleanfalseAn optional parameter which instructs Flash Player to fit at least one character into the text line, no matter what + width has been specified (even if width is zero or negative, which would otherwise result in an exception being thrown). + + + Instructs the text block to re-use an existing text line to create a line of text from its content, beginning at the point + specified by the previousLine parameter and breaking at the point specified by the + width parameter. The text line is a TextLine object, which you can add + to the display list. By re-using an existing text line, performance is enhanced due to reduced object creation. + +

The textLine being recreated is released from whatever text block it is in, if any. + In addition, all properties, including inherited properties from DisplayObjectContainer, + InteractiveObject, and DisplayObject are reset to their default values. + Finally, all children of the line are removed including graphic elements and other decorations, and all event + listeners on the line are removed. To improve performance, the only exception to this complete reset is that + the line itself is not removed from its parent.

+ +

Breaking lines over a range of a text block that has already been broken can change the validity + of lines in and beyond the area where breaking takes place. The status of lines can change from VALID to INVALID or + POSSIBLY_INVALID. If a newly broken line aligns perfectly with a previously broken line which has a status + of POSSIBLY_INVALID, that previously broken line and all following POSSIBLY_INVALID lines change back + to a status of VALID. The validity of lines that have been set to values that are not members of + TextLineValidity do not change to VALID, but could change to INVALID. + Check the firstInvalidLine property after any change to the text block + to see where to begin or continue rebreaking text lines.

+ +

You can create artificial word breaks by including the Unicode Zero Width Space (ZWSP) character in the text. + This can be useful for languages such as Thai, which require a dictionary for correct line breaking. + The Flash runtime does not include such a dictionary.

+ +

In order to reduce memory overhead, when all the desired lines have been created, unless it is expected that the + lines will need to be repeatedly rebroken due to, for example, the resizing of the container, the user should call + the releaseLineCreationData() method allowing the text block to dispose of the temporary data associated with line breaking.

+ +
This example re-uses the TextLine object textLine: + +var elementFormat:ElementFormat = new ElementFormat(); +elementFormat.fontDescription = new FontDescription("Arial"); +elementFormat.fontSize = 48; + +var textElement:TextElement = new TextElement("Text you'll never see", elementFormat) +var textBlock:TextBlock = new TextBlock(textElement); +var textLine:TextLine = textBlock.createTextLine(); +textLine.x = 50; +textLine.y = 50; +addChild(textLine); + +// Reuse the element format to preserve the text formatting +var elementTwo:TextElement = new TextElement("Text you see", elementFormat); +textBlock.content = elementTwo; +textBlock.recreateTextLine(textLine); + +// Set the position (and any other display object properties like alpha, children, etc.) +// otherwise, they're all set to default properties. +textLine.x = 50; +textLine.y = 50; +
TextBaselineTextLineTextLine.validityTextLineValidityTextBlock.releaseLineCreationData()
releaseLineCreationData + Instructs the text block to release all the temporary data associated with the creation of text lines. + Instructs the text block to release all the temporary data associated with the creation of text lines. + To minimize an application's memory foot print, you should call the releaseLineCreationData() method when you are + done creating text lines from a text block. However, to maximize performance for rebreaking the lines + (for example when the container is resized) the releaseLineCreationData() method should not be called. + It is up to the application to balance memory vs. performance. + +

The recommended process for text that is not expected to change is: initialize a text block, + call the createTextLine() method as often as necessary to create the desired output, and then call + the releaseLineCreationData() method.

+ +
TextBlock.createTextLine()
releaseLines + Removes a range of text lines from the list of lines maintained by the TextBlock.If the TextLine specified by firstLine or lastLine is not + in the list of text lines maintained by the text block. + + ArgumentErrorArgumentErrorfirstLineflash.text.engine:TextLineSpecifies the first line to release. + lastLineflash.text.engine:TextLineSpecifies the last line to release. + + + Removes a range of text lines from the list of lines maintained by the TextBlock. + This allows the lines to be garbage-collected if no other references exist. + +

Sets the textBlock, nextLine, and previousLine + members of the removed lines to null. + Sets the validity of the removed lines and of all lines which follow + the removed lines in the TextBlock to TextLineValidity.INVALID.

+ +
TextLine
userData + Provides a way for the application to associate arbitrary data with the text block. + Provides a way for the application to associate arbitrary data with the text block. The data could be information that refers to the content, + such as a revision date or the name of the author, or it could be cached data that you use during processing. + + applyNonLinearFontScaling + Specifies that you want to enhance screen appearance at the expense of what-you-see-is-what-you-get (WYSIWYG) print fidelity.Boolean + Specifies that you want to enhance screen appearance at the expense of what-you-see-is-what-you-get (WYSIWYG) print fidelity. + For platforms and fonts that do not support sub pixel glyph positioning during device font rendering, but + do support non-linear scaling, setting this property to true enables the use of those metrics at some cost to + WYSIWYG print fidelity, particularly for small point sizes. Non linear font scaling works by selectivly scaling the width + of individual glyphs to conceal unsightly gaps caused by pixel snapping. + +

On platforms which do support sub-pixel glyph positioning, this flag is ignored.

+ +

This flag has no effect on embedded font rendering

+ +

The default value is true.

+ +
baselineFontDescription + The font used to determine the baselines for all the lines created from the block, independent of their content.flash.text.engine:FontDescription + The font used to determine the baselines for all the lines created from the block, independent of their content. Baselines depend on font and font size. + +

The default value is null. When the baseline font is null, the baseline font size is ignored and + the baseline for any given line is based on the font and size of the largest text in the line. When you specify both + baselineFontDescription and baselineFontSize, they determine the baselines for all the lines + in the text block, independent of their content. This combination is most often useful in Asian typography.

+ +
baselineFontSizeFontDescription
baselineFontSize + The font size used to calculate the baselines for the lines created from the block.NumberThe baselineFontSize specified is less than 0. + + ArgumentErrorArgumentError + The font size used to calculate the baselines for the lines created from the block. Baselines depend on font and font size. + +

The default value is 12. When the baseline font is null, the baseline font size is ignored and + the baseline for any given line is based on the font and size of the largest text in the line.

+ +
baselineFontDescriptionFontDescription
baselineZero + Specifies which baseline is at y=0 for lines created from this block.StringIf set to any value which is not a member of TextBaseline. + + ArgumentErrorArgumentError + Specifies which baseline is at y=0 for lines created from this block. + Valid values for this property are found in the members of the + TextBaseline class. + +

The default value is TextBaseline.ROMAN.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionTextBaseline.ROMANThe roman baseline of the lines is at y=0.TextBaseline.ASCENTThe ascent baseline of the lines is at y=0.TextBaseline.DESCENTThe descent baseline of the lines is at y=0.TextBaseline.IDEOGRAPHIC_TOPThe ideographic top baseline of the lines is at y=0.TextBaseline.IDEOGRAPHIC_CENTERThe ideographic center baseline of the lines is at y=0.TextBaseline.IDEOGRAPHIC_BOTTOMThe ideographic bottom baseline of the lines is at y=0. + +
TextBaseline
bidiLevel + Specifies the default bidirectional embedding level of the text in the text block.intIf set to a value which is less than 0. + + ArgumentErrorArgumentError + Specifies the default bidirectional embedding level of the text in the text block. + An even value means left-to-right and an odd value means right-to-left. You can increment bidiLevel to + indicate the number of levels by which particular text is embedded with respect to left-to-right + and right-to-left. + +

The default value is 0.

+ +

Modifying bidiLevel changes the validity of all previously broken lines to TextLineValidity.INVALID. After + changing bidiLevel, the firstInvalidLine property equals the firstLine property, and you must + rebreak all the lines in the TextBlock.

+ +
This example shows the same text string (logical order: a, b, c, alef, bet, gimel) + rendered first with bidiLevel even and second with bidiLevel odd. + + +package { + + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + + public class TextBlock_bidiLevelExample extends Sprite { + + public function TextBlock_bidiLevelExample():void { + var fontSize:Number = 36; + + var format:ElementFormat = new ElementFormat(); + format.fontDescription = new FontDescription("Adobe Hebrew"); + format.fontSize = fontSize; + var y:Number = 0; + var leading:Number = fontSize * 0.2; + var text:String = "abc" + String.fromCharCode(0x05D0, 0x05D1, 0x05D2); + + var textBlock:TextBlock = new TextBlock(); + textBlock.content = new TextElement(text, format); + + // bidiLevel even + textBlock.bidiLevel = 0; + var textLine = textBlock.createTextLine(null, 400); + y += leading + textLine.ascent; + textLine.y = y; + y += textLine.descent; + addChild(textLine); + + // bidiLevel odd + textBlock.content = new TextElement(text, format); + textBlock.bidiLevel = 1; + textLine = textBlock.createTextLine(null, 400); + y += leading + textLine.ascent; + textLine.y = y; + addChild(textLine); + } + } +} +
createTextLine()
content + Holds the contents of the text block.flash.text.engine:ContentElementIf set to a value which is not a known subclass of ContentElement. + ArgumentErrorArgumentErrorThe value specified is already a member of a group. + + ArgumentErrorArgumentError + Holds the contents of the text block. Because ContentElement is a base class, assign content + an instance of a ContentElement subclass: TextElement, GraphicElement, or GroupElement. A TextElement object + contains a String, a GraphicElement object contains a DisplayObject, and a GroupElement contains a Vector object that + contains one or more TextElement, GraphicElement, or other GroupElement objects. Use a TextElement for a + paragraph of homogenous text, a GraphicElement for a graphic, and a GroupElement for a combination of text and graphic + elements or multiples instances of these elements, as well as other GroupElement objects. + +

The default value is null.

+ +

Modifying the content property changes the validity of all previously created lines to + TextLineValidity.INVALID. After changing content, the firstInvalidLine property + equals the firstLine property and you must rebreak all lines in the TextBlock.

+ +
ContentElementGraphicElementGroupElementTextElementcreateTextLine()
firstInvalidLine + Identifies the first line in the text block in which TextLine.validity is not equal to + TextLineValidity.VALID.flash.text.engine:TextLine + Identifies the first line in the text block in which TextLine.validity is not equal to + TextLineValidity.VALID. + +

The default value is null.

+ + + +
TextLine.validityTextLineValidity
firstLine + The first TextLine in the TextBlock, if any.flash.text.engine:TextLine + The first TextLine in the TextBlock, if any. + +

The default value is null.

+ +
TextLine
lastLine + The last TextLine in the TextBlock, if any.flash.text.engine:TextLine + The last TextLine in the TextBlock, if any. + +

The default value is null.

+ +
TextLine
lineRotation + Rotates the text lines in the text block as a unit.StringIf set to any value which is not a member of TextRotation. + ArgumentErrorArgumentErrorIf set to TextRotation.AUTO. + ArgumentErrorArgumentError + Rotates the text lines in the text block as a unit. Call the createTextLine() method after + setting lineRotation for it to take effect. The default value is TextRotation.ROTATE_0. + +

The final rotation of any glyph depends on the values of + ElementFormat.textRotation, ContentElement.textRotation, and TextBlock.lineRotation.

+ +

TextBlock.lineRotation is typically used for Asian text. + To create a paragraph of vertical Japanese text, do the following:

+
  1. Set the TextBlock.lineRotation property to TextRotation.ROTATE_90.
  2. Leave the ElementFormat.textRotation property of the content as the default, TextRotation.AUTO.
+ +

Use the following constants, which are defined in the TextRotation class, to set the + value for this property:

+ + String valueDescriptionTextRotation.ROTATE_0Lines are not rotated.TextRotation.ROTATE_90Lines are rotated 90 degrees clockwise.TextRotation.ROTATE_180Lines are rotated 180 degrees.TextRotation.ROTATE_270Lines are rotated 270 degrees clockwise.TextRotation.AUTONot supported. + +
This example adds Japanese text to a TextBlock and sets the + lineRotation property to TextRotation.ROTATE_90 to display the line + vertically. + + +package { + import flash.display.Sprite; + import flash.text.engine.FontDescription; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.TextRotation; + import flash.text.engine.ElementFormat; + + public class TextBlock_lineRotationExample extends Sprite { + + public function TextBlock_lineRotationExample():void { + var Japanese:String = String.fromCharCode( + 0x5185, 0x95A3, 0x5E9C, 0x304C, 0x300C, 0x653F, 0x5E9C, 0x30A4, + 0x30F3, 0x30BF, 0x30FC, 0x30CD, 0x30C3, 0x30C8, 0x30C6, 0x30EC, + 0x30D3, 0x300D, 0x306E, 0x52D5, 0x753B, 0x914D, 0x4FE1, 0x5411, + 0x3051, 0x306B, 0x30A2, 0x30C9, 0x30D3, 0x30B7, 0x30B9, 0x30C6, + 0x30E0, 0x30BA, 0x793E, 0x306E + ) + + "FMS 2" + + String.fromCharCode(0x3092, 0x63A1, 0x7528, 0x3059, 0x308B, 0x3068, + 0x767a, 0x8868, 0x3057, 0x307e, 0x3057, 0x305F, 0x3002); + + var fontDescription:FontDescription = new FontDescription("MS Mincho"); + var format:ElementFormat = new ElementFormat(); + format.fontSize = 15; + format.fontDescription = fontDescription; + + var textElement:TextElement = new TextElement(Japanese, format); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = textElement; + textBlock.lineRotation = TextRotation.ROTATE_90; + + var linePosition:Number = this.stage.stageWidth - 120; + var previousLine:TextLine = null; + + while (true) { + var textLine:TextLine = textBlock.createTextLine( + previousLine, + 300); + if (textLine == null) + break; + textLine.y = 30; + textLine.x = linePosition; + linePosition -= 24; + addChild(textLine); + previousLine = textLine; + } + } + } +} +
ContentElement.textRotationElementFormat.textRotationTextLineTextRotation
tabStops + Specifies the tab stops for the text in the text block, + in the form of a Vector of TabStop objects.The tabStops specified contain null elements. + ArgumentErrorArgumentErrorThe tabStops specified are not sorted by increasing position. + + ArgumentErrorArgumentError + Specifies the tab stops for the text in the text block, + in the form of a Vector of TabStop objects. + +

The default value is null, which means no tab stops are specified. When no tab stops are specified (or the insertion point is beyond the last specified tab stop) + the runtime creates half-inch tabs by default.

+ +

When the tabStops property is set, the TextBlock makes a copy of the Vector for internal use. + Modifying the original Vector or its contents does not affect the TextBlock. When the tabStops property is queried, a copy + of the internal Vector is returned. Again, modifying this returned vector or its contents does not affect the TextBlock.

+ +
TabStop
textJustifier + Specifies the TextJustifier to use during line creation.flash.text.engine:TextJustifierIf set to a value which is not a known subclass of TextJustifier. + + ArgumentErrorArgumentError + Specifies the TextJustifier to use during line creation. + +

The default value is a constructed default TextJustifier object.

+ +

When the textJustifier property is set, the TextBlock makes a copy of the object for internal use. + Modifying the original object does not affect the TextBlock. When the textJustifier property is queried, a copy + of the internal object is returned. Again, modifying this returned object does not affect the TextBlock.

+ +
EastAsianJustifierSpaceJustifierTextJustifier
textLineCreationResult + Indicates the result of a createTextLine() operation.String + Indicates the result of a createTextLine() operation. + Changing the content of the block invalidates previously broken lines and resets + this property to null. + +

The default value is null.

+ +

Values for this property are found in TextLineCreationResult

+ + String valueDescriptionTextLineCreationResult.SUCCESSThe line was successfully broken.TextLineCreationResult.COMPLETEEither the new line created aligned perfectly with following lines which + have transitioned from POSSIBLY_INVALID to VALID, or + no line was created because all text in the block had already been broken.TextLineCreationResult.INSUFFICIENT_WIDTHNo line was created because no text could fit in the specified width. +
TextLineCreationResult
TextLineCreationResult +The TextLineCreationResult class is an enumeration of constant values used with TextBlock.textLineCreationResult.Object +The TextLineCreationResult class is an enumeration of constant values used with TextBlock.textLineCreationResult. + +TextBlock.createTextLine()TextBlock.textLineCreationResultCOMPLETE + Indicates no line was created because all text in the block had already been broken.completeString + Indicates no line was created because all text in the block had already been broken. + + EMERGENCY + Indicates the line was created with an emergency break because no break opportunity + was available in the specified width.emergencyString + Indicates the line was created with an emergency break because no break opportunity + was available in the specified width. + + INSUFFICIENT_WIDTH + Indicates no line was created because no text could fit in the specified width + and fitSomething was not specified in the call to createTextLine().insufficientWidthString + Indicates no line was created because no text could fit in the specified width + and fitSomething was not specified in the call to createTextLine(). + + SUCCESS + Indicates the line was successfully broken.successString + Indicates the line was successfully broken. + + LigatureLevel +The LigatureLevel class is an enumeration of constant values used in setting the ligatureLevel property +of the ElementFormat class.Object +The LigatureLevel class is an enumeration of constant values used in setting the ligatureLevel property +of the ElementFormat class. A ligature occurs where two or more letter-forms are joined as a single glyph. Ligatures +usually replace consecutive characters sharing common components, such as the letter pairs 'fi', 'fl', or 'ae'. +They are used with both Latin and Non-Latin character sets. +

Note: When working with Arabic or Syriac fonts, ligatureLevel must be set to MINIMUM or above.

+ +
ElementFormat.ligatureLevelCOMMON + Used to specify common ligatures.commonString + Used to specify common ligatures. + + EXOTIC + Used to specify exotic ligatures.exoticString + Used to specify exotic ligatures. + + MINIMUM + Used to specify minimum ligatures.minimumString + Used to specify minimum ligatures. + + NONE + Used to specify no ligatures.noneString + Used to specify no ligatures. + + UNCOMMON + Used to specify uncommon ligatures.uncommonString + Used to specify uncommon ligatures. + +
TextRotation +The TextRotation class is an enumeration of constant values used with the following properties: +ElementFormat.textRotation, ContentElement.textRotation, +TextBlock.lineRotation, and TextLine.getAtomTextRotation().Object +The TextRotation class is an enumeration of constant values used with the following properties: +ElementFormat.textRotation, ContentElement.textRotation, +TextBlock.lineRotation, and TextLine.getAtomTextRotation(). + +

The final rotation of any glyph is the sum of TextBlock.lineRotation, +ElementFormat.textRotation, and ContentElement.textRotation

+ +
ElementFormat.textRotationContentElement.textRotationTextBlock.lineRotationTextLine.getAtomTextRotation()AUTO + Specifies a 90 degree counter clockwise rotation for full width and wide glyphs only, + as determined by the Unicode properties of the glyph.autoString + Specifies a 90 degree counter clockwise rotation for full width and wide glyphs only, + as determined by the Unicode properties of the glyph. + This value is typically used with Asian text to rotate + only those glyphs that require rotation. + This rotation is applied only in vertical text to return full width and wide + characters to a vertical orientation without affecting other characters. + + ROTATE_0 + Specifies no rotation.rotate0String + Specifies no rotation. + + ROTATE_180 + Specifies a 180 degree rotation.rotate180String + Specifies a 180 degree rotation. + + ROTATE_270 + Specifies a 270 degree clockwise rotation.rotate270String + Specifies a 270 degree clockwise rotation. + + ROTATE_90 + Specifies a 90 degree clockwise rotation.rotate90String + Specifies a 90 degree clockwise rotation. + +
TabAlignment +The TabAlignment class is an enumeration of constant values that you can use to set the tabAlignment property +of the TabStop class.Object +The TabAlignment class is an enumeration of constant values that you can use to set the tabAlignment property +of the TabStop class. + + +TabStop.alignmentTextBlock.tabStopsCENTER + Positions the center of the tabbed text at the tab stop.centerString + Positions the center of the tabbed text at the tab stop. + + DECIMAL + Positions the alignment token of the tabbed text at the tab stop.decimalString + Positions the alignment token of the tabbed text at the tab stop. + + TabStop.decimalAlignmentTokenEND + Positions the end of the tabbed text at the tab stop.endString + Positions the end of the tabbed text at the tab stop. + + START + Positions the start of the tabbed text at the tab stop.startString + Positions the start of the tabbed text at the tab stop. + + GraphicElement + The GraphicElement class represents a graphic element in a TextBlock or GroupElement object.flash.text.engine:ContentElement + The GraphicElement class represents a graphic element in a TextBlock or GroupElement object. Assign a GraphicElement object to the + content property of a TextBlock object to display a graphic or an image with TextBlock.createTextLine(). + Assign it to a GroupElement object to combine it with other graphic and text elements. + + The following example creates a TextBlock with a GraphicElement (a red box) and + displays it, adding a second TextBlock beneath it that contains a caption. + + +package { + + import flash.display.Sprite; + import flash.display.MovieClip; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.GraphicElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + + public class GraphicElementExample extends Sprite { + + public function GraphicElementExample():void { + + var format:ElementFormat = new ElementFormat(); + format.fontSize = 14; + var redBox:MovieClip = new MovieClip(); + redBox.graphics.beginFill(0xCC0000, 1.0); + redBox.graphics.drawRect(0,0, 200, 200); + redBox.graphics.endFill(); + var graphicElement:GraphicElement = new GraphicElement(redBox,redBox.width,redBox.height, format); + var textBlock:TextBlock = new TextBlock(); + textBlock.content = graphicElement; + var textLine1:TextLine = textBlock.createTextLine(null,redBox.width); + addChild(textLine1); + textLine1.x = 15 + textLine1.y = 215 + var str:String = "Your picture here ..."; + var textElement:TextElement = new TextElement(str, format); + textBlock = new TextBlock(); + textBlock.content = textElement; + var textLine2 = textBlock.createTextLine(null, 300); + addChild(textLine2); + textLine2.x = textLine1.x; + textLine2.y += textLine1.y + format.fontSize; + } + } +} +ContentElementGroupElementTextBlockGraphicElement + Creates a new GraphicElement instance.graphicflash.display:DisplayObjectnullThe DisplayObject to populate the GraphicElement. The default value is null. + elementWidthNumber15.0The width of the area reserved for the element in pixels. The default value is 15. + elementHeightNumber15.0The height of the area reserved for the element in pixels. The default value is 15. + elementFormatflash.text.engine:ElementFormatnullThe element format for the element. The default value is null. + eventMirrorflash.events:EventDispatchernullThe EventDispatcher object that receives copies of every + event dispatched to text lines created based on this content element. The default value is null. + textRotationStringrotate0The rotation applied to the element as a unit. Use flash.text.engine.TextRotation + constants for this property. The default value is flash.text.engine.TextRotation.ROTATE_0. + + Creates a new GraphicElement instance. + +

The registration point of the graphic aligns with the upper-left corner + of the region defined by elementHeight, elementWidth + and elementFormat.baselineShift. The graphic is not scaled to match the size of the region. + If the GraphicElement has an eventMirror, the elementWidth and elementHeight + properties, and not the graphic, determine the size and position of the resulting mirror region. If a loader + is used, the graphic might not be loaded at the time the text line and the mirror regions are created.

+ +
GroupElement
elementHeight + The height in pixels to reserve for the graphic in the line.Number + The height in pixels to reserve for the graphic in the line. + It is the responsibility of the caller to scale the graphic. + +

The default value is 15.0.

+ +
elementWidth + The width in pixels to reserve for the graphic in the line.Number + The width in pixels to reserve for the graphic in the line. + It is the responsibility of the caller to scale the graphic. + +

The default value is 15.0.

+ +
graphic + The DisplayObject to be used as a graphic for the GraphicElement.flash.display:DisplayObject + The DisplayObject to be used as a graphic for the GraphicElement. + +

The default value is null.

+ +

When the GraphicElement becomes part of a text line, the graphic + is added as a child of the line. Setting the graphic removes + the old graphic from the line and adds the new one.

+ +
FontWeight +The FontWeight class is an enumeration of constant values used with FontDescription.fontWeight.Object +The FontWeight class is an enumeration of constant values used with FontDescription.fontWeight. + +flash.text.engine.FontDescription.fontWeightBOLD + Used to indicate bold font weight.boldString + Used to indicate bold font weight. + + NORMAL + Used to indicate normal font weight.normalString + Used to indicate normal font weight. + + TextBaseline +The TextBaseline class is an enumeration of constant values to use in setting the dominantBaseline and +alignmentBaseline properties of the ElementFormat class.Object +The TextBaseline class is an enumeration of constant values to use in setting the dominantBaseline and +alignmentBaseline properties of the ElementFormat class. You can also use it in the +baselineZero property of the TextBlock class. +Consider this situation: +

+

The line consists of four TextElement objects, containing 'a', 'b', 'cccccccc', and 'X' respectively. +The element containing 'X' determines the line baselines because it is the largest element in the line. +The roman baseline of the 'X' element is aligned with the roman baseline of the line. +The ideographic top of the 'a' element is aligned with the ideographic top of the line. +The ideographic bottom of the 'b' element is aligned with the ideographic bottom of the line. +The ideographic center of the 'cccccccc' element is aligned with the ideographic center of the line.

+ +
ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroASCENT + Specifies an ascent baseline.ascentString + Specifies an ascent baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text engine uses the geometric top of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroDESCENT + Specifies a descent baseline.descentString + Specifies a descent baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text element uses the geometric bottom of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroIDEOGRAPHIC_BOTTOM + Specifies an ideographic bottom baseline.ideographicBottomString + Specifies an ideographic bottom baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text engine uses the geometric bottom of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroIDEOGRAPHIC_CENTER + Specifies an ideographic center baseline.ideographicCenterString + Specifies an ideographic center baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text engine uses the geometric center of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroIDEOGRAPHIC_TOP + Specifies an ideographic top baseline.ideographicTopString + Specifies an ideographic top baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text engine uses the geometric top of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroROMAN + Specifies a roman baseline.romanString + Specifies a roman baseline. + For a text element, the font and point size of the text determine this value. + For a graphic element, the text engine uses the geometric bottom of the element. + + ElementFormat.dominantBaselineElementFormat.alignmentBaselineTextBlock.baselineZeroUSE_DOMINANT_BASELINE + Specifies that the alignmentBaseline is the same as the dominantBaseline.useDominantBaselineString + Specifies that the alignmentBaseline is the same as the dominantBaseline. + Use this value only to set ElementFormat.alignmentBaseline. + + ElementFormat.alignmentBaseline
BreakOpportunity +The BreakOpportunity class is an enumeration of constant values that you can use to set the breakOpportunity property +of the ElementFormat class.Object +The BreakOpportunity class is an enumeration of constant values that you can use to set the breakOpportunity property +of the ElementFormat class. +This property determines which characters can be used for breaking when wrapping text is broken into multiple lines. + + +ElementFormat.breakOpportunityALL + Treats all characters in the ContentElement object as line break opportunities, meaning that a line break will occur + afer each character.allString + Treats all characters in the ContentElement object as line break opportunities, meaning that a line break will occur + afer each character. You can use this option to generate the shortest possible lines, + which you can use to create text on a line or similar effects. + + ANY + Treats any character in the ContentElement object as a line break opportunity.anyString + Treats any character in the ContentElement object as a line break opportunity. + This value is typically used when Roman text is embedded in Asian text and it is desirable for breaks to happen + in the middle of words. + + AUTO + Bases line break opportunities on Unicode character properties.autoString + Bases line break opportunities on Unicode character properties. This setting implements + the Unicode line breaking properties defined by the Unicode Standard Annex #14. + Article on Unicode line breaking properties.NONE + Treats no characters in the ContentElement object as line break opportunities.noneString + Treats no characters in the ContentElement object as line break opportunities. + + DigitWidth +The DigitWidth class is an enumeration of constant values used in setting the digitWidth property +of the ElementFormat class.Object +The DigitWidth class is an enumeration of constant values used in setting the digitWidth property +of the ElementFormat class. + + +flash.text.engine.ElementFormat.digitWidthDEFAULT + Used to specify default digit width.defaultString + Used to specify default digit width. The results are font-dependent; characters use the settings specified by the font designer + without any features applied. + + PROPORTIONAL + Used to specify proportional digit width.proportionalString + Used to specify proportional digit width. + + TABULAR + Used to specify tabular digit width.tabularString + Used to specify tabular digit width. + + CFFHinting +The CFFHinting class defines values for cff hinting in the FontDescription class.Object +The CFFHinting class defines values for cff hinting in the FontDescription class. + +

Hinting adjusts the display of an outline font so it lines up with the pixel grid. +At small screen sizes, hinting produces a clear, legible text for human readers. +

+ +
flash.text.engine.FontDescriptionHORIZONTAL_STEM + Fits strong horizontal stems to the pixel grid for improved readability.horizontalStemString + Fits strong horizontal stems to the pixel grid for improved readability. + This constant is used in setting the cffHinting property of the + FontDescription class. Use the syntax CFFHinting.HORIZONTAL_STEM. + +

Note: Not recommended for animation.

+ +
flash.text.engine.FontDescription.cffHinting
NONE + No hinting is applied.noneString + No hinting is applied. Horizontal stems in the glyphs are not forced to the pixel grid. + This constant is used in setting the cffHinting property of the + FontDescription class. Recommended setting for animation or for large font sizes. + Use the syntax CFFHinting.NONE. + + flash.text.engine.FontDescription.cffHinting
Kerning +The Kerning class is an enumeration of constant values used with ElementFormat.kerning.Object +The Kerning class is an enumeration of constant values used with ElementFormat.kerning. + +ElementFormat.kerningAUTO + Used to indicate that kerning is enabled except where inappropriate in Asian typography.autoString + Used to indicate that kerning is enabled except where inappropriate in Asian typography. Kerning is + applied between two characters if neither is Kanji, Hiragana, or Katakana. + + OFF + Used to indicate kerning is disabled.offString + Used to indicate kerning is disabled. + + ON + Used to indicate kerning is enabled.onString + Used to indicate kerning is enabled. + + TextLineMirrorRegion + The TextLineMirrorRegion class represents a portion of a text line wherein events are mirrored to another event dispatcher.Object + The TextLineMirrorRegion class represents a portion of a text line wherein events are mirrored to another event dispatcher. + +

After normal event-dispatching for a text line finishes, if the line is valid and event propagation has not been stopped, + events are re dispatched to the mirror regions of the line.

+ +

Mirroring of mouse events is a special case. Because mirror regions aren't actually display objects, mouseOver and mouseOut + events are simulated for them. The rollOver and rollOut events are not simulated. All naturally occuring + mouseOver, mouseOut, rollOver and rollOut events (whether targetted at the + text line or at children of the text line) are ignored - they are not mirrored.

+ +

You cannot create a TextLineMirrorRegion object directly from ActionScript code. + If you call new TextLineMirrorRegion(), an exception is thrown. A TextLineMirrorRegion is created and associated with a text line when that + text line is created from a ContentElement object with an event mirror set.

+ +

The TextLineMirrorRegion class is final; it cannot be subclassed.

+ +
This example displays a block of text with mirror regions that turn red when you click + them. + + +package { + + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextLine; + import flash.text.engine.TextElement; + import flash.text.engine.ElementFormat; + import flash.text.engine.FontDescription; + import flash.text.engine.ContentElement; + import flash.text.engine.GroupElement; + import flash.text.engine.TextLineMirrorRegion; + import flash.events.MouseEvent; + import flash.events.EventDispatcher; + import flash.ui.Mouse; + + public class TextLineMirrorRegionExample extends Sprite { + + var myEvent:EventDispatcher = new EventDispatcher(); + var fontDescription:FontDescription = new FontDescription(); + var textBlock:TextBlock = new TextBlock(); + + public function TextLineMirrorRegionExample():void { + + fontDescription.fontWeight = "bold"; + var blackFormat:ElementFormat = new ElementFormat(); + blackFormat.fontSize = 18; + blackFormat.color = 0x000000; + blackFormat.fontDescription = fontDescription; + + var textElement1 = new TextElement("Click on different parts of me to find the ", blackFormat); + var textElement2 = new TextElement("mirror regions",blackFormat); + var textElement3 = new TextElement(". If I am a mirror region, I'll ",blackFormat); + var textElement4 = new TextElement("turn red",blackFormat); + var textElement5 = new TextElement(".",blackFormat); + + myEvent.addEventListener("click", clickHandler); + myEvent.addEventListener("mouseOut", mouseOutHandler); + myEvent.addEventListener("mouseOver", mouseOverHandler); + + var groupVector:Vector.<ContentElement> = new Vector.<ContentElement>; + groupVector.push(textElement1, textElement2, textElement3, textElement4, textElement5); + var groupElement:GroupElement = new GroupElement(groupVector); + + textElement2.eventMirror=myEvent; + textElement4.eventMirror=myEvent; + + textBlock.content = groupElement; + createLines(textBlock); + } + + private function clickHandler(event:MouseEvent):void + { + var redFormat:ElementFormat = new ElementFormat(); + redFormat.color = 0xCC0000; + redFormat.fontSize = 18; + redFormat.fontDescription = fontDescription; + var line:TextLine = event.target as TextLine; + var region:TextLineMirrorRegion = line.getMirrorRegion(myEvent); + region.element.elementFormat = redFormat; + createLines(textBlock); + } + + private function mouseOverHandler(event:MouseEvent):void + { + Mouse.cursor = "button"; + } + + private function mouseOutHandler(event:MouseEvent):void + { + Mouse.cursor = "arrow"; + } + + private function createLines(textBlock:TextBlock):void + { + var purgeLine:TextLine = textBlock.firstLine; + + while (purgeLine) + { + removeChild (purgeLine); + purgeLine = purgeLine.nextLine; + } + var lineWidth:Number = 150; + var xPos:Number = 15.0; + var yPos:Number = 20.0; + var textLine:TextLine = textBlock.createTextLine (null, lineWidth); + + while (textLine) + { + textLine.x = xPos; + textLine.y = yPos; + yPos += textLine.height + 2; + addChild (textLine); + textLine = textBlock.createTextLine (textLine, lineWidth); + } + } + } +} +
ContentElement.eventMirrorTextBlock.createTextLine()TextLine.mirrorRegionsbounds + The bounds of the mirror region, relative to the text line.flash.geom:Rectangle + The bounds of the mirror region, relative to the text line. + + element + The ContentElement object from which the mirror region was derived.flash.text.engine:ContentElementThe TextLine to which this element belongs is not valid. + + IllegalOperationErrorflash.errors:IllegalOperationError + The ContentElement object from which the mirror region was derived. + + mirror + The EventDispatcher object to which events affecting the mirror region are mirrored.flash.events:EventDispatcher + The EventDispatcher object to which events affecting the mirror region are mirrored. + This includes mouse events that specifically occur in the mirror region, and all other events + that target the text line. + + nextRegion + The next TextLineMirrorRegion in the set derived from the text element, or null if the current region is the last mirror region + in the set.flash.text.engine:TextLineMirrorRegion + The next TextLineMirrorRegion in the set derived from the text element, or null if the current region is the last mirror region + in the set. May be on the same line or on another text line. + + previousRegion + The previous TextLineMirrorRegion in the set derived from the text element, or null if the current region is the first mirror + region in the set.flash.text.engine:TextLineMirrorRegion + The previous TextLineMirrorRegion in the set derived from the text element, or null if the current region is the first mirror + region in the set. May be on the same line or on another text line. + + textLine + The TextLine containing this mirror region.flash.text.engine:TextLine + The TextLine containing this mirror region. + +
LineJustification +The LineJustification class is an enumeration of constant values used in setting the lineJustfication property +of the TextJustifier subclasses.Object +The LineJustification class is an enumeration of constant values used in setting the lineJustfication property +of the TextJustifier subclasses. + +TextJustifier.lineJustificationALL_BUT_LAST + Justify all but the last line.allButLastString + Justify all but the last line. + + ALL_INCLUDING_LAST + Justify all lines.allIncludingLastString + Justify all lines. + + UNJUSTIFIED + Do not justify lines.unjustifiedString + Do not justify lines. + + SpaceJustifier + The SpaceJustifier class represents properties that control the justification options for text lines in a text block.flash.text.engine:TextJustifier + The SpaceJustifier class represents properties that control the justification options for text lines in a text block. + +

Use the constructor new SpaceJustifier() to create a SpaceJustifier object before setting its properties. + Setting the properties of a SpaceJustifier object after you apply it to a TextBlock does not invalidate the TextBlock.

+ +
The following example uses letter spacing and justifies all of a block of text + except for the last line. + + +package { + import flash.display.Sprite; + import flash.text.engine.TextBlock; + import flash.text.engine.TextElement; + import flash.text.engine.TextLine; + import flash.text.engine.ElementFormat; + import flash.text.engine.SpaceJustifier; + import flash.text.engine.LineJustification; + + public class SpaceJustifierExample extends Sprite { + + public function SpaceJustifierExample():void { + var str:String = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " + + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut " + + "enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " + + "aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " + + "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur " + + "sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt " + + "mollit anim id est laborum."; + + var format:ElementFormat = new ElementFormat(null, 12, 0xCC0000); + var textElement:TextElement = new TextElement(str, format); + var spaceJustifier:SpaceJustifier = new SpaceJustifier("en", LineJustification.ALL_BUT_LAST); + spaceJustifier.letterSpacing = true; + var textBlock:TextBlock = new TextBlock(); + textBlock.content = textElement; + textBlock.textJustifier = spaceJustifier; + createLines(textBlock); + } + + private function createLines(textBlock:TextBlock):void { + + var yPos = 20; + var textLine:TextLine = textBlock.createTextLine (null, 150); + + while (textLine) + { + addChild(textLine); + textLine.x = 15; + yPos += textLine.textHeight+2; + textLine.y = yPos; + textLine = textBlock.createTextLine(textLine, 150); + } + } + } +} +
LineJustificationTextBlock.textJustifierTextJustifierSpaceJustifier + Creates a SpaceJustifier object.The locale specified is null or too short to represent a valid locale. + ArgumentErrorArgumentErrorThe lineJustification specified is not a member of LineJustification. + + ArgumentErrorArgumentErrorlocaleStringenThe locale to determine the justification rules. + The default value is "en". + lineJustificationStringunjustifiedThe type of line justification for the paragraph. + Use LineJustification constants for this property. + The default value is LineJustification.UNJUSTIFIED. + letterSpacingBooleanfalseSpecifies whether to use letter spacing during justification. + The default value is false. + + Creates a SpaceJustifier object. The LineJustification class contains constants for specifying the types of + line justification that you can apply. + + LineJustificationclone + Constructs a cloned copy of the SpaceJustifier.A copy of the SpaceJustifier object. + + flash.text.engine:TextJustifier + Constructs a cloned copy of the SpaceJustifier. + + letterSpacing + Specifies whether to use letter spacing during justification.Boolean + Specifies whether to use letter spacing during justification. + +

The default value is false

+ +
maximumSpacing + Specifies the maximum spacing (as a multiplier of the width of a normal space) between words to use during justification.NumberThe value specified is less than optimumSpacing. + + ArgumentErrorArgumentError + Specifies the maximum spacing (as a multiplier of the width of a normal space) between words to use during justification. + If letterSpacing is true, letter spacing will be used after the spaces between words reach the maximum. + If letterSpacing is false, the spaces between words will be expanded beyond the maximum. + +

The default value is 1.5

+ +
minimumSpacing + Specifies the minimum spacing (as a multiplier of the width of a normal space) between words to use during justification.NumberThe value specified is less than zero or greater than optimumSpacing. + + ArgumentErrorArgumentError + Specifies the minimum spacing (as a multiplier of the width of a normal space) between words to use during justification. + +

The default value is 0.5

+ +
optimumSpacing + Specifies the optimum spacing (as a multiplier of the width of a normal space) between words to use during justification.NumberThe value specified is less than minimumSpacing or greater than maximumSpacing. + + ArgumentErrorArgumentError + Specifies the optimum spacing (as a multiplier of the width of a normal space) between words to use during justification. + +

The default value is 1.0

+ +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.text.ime.xml b/language-server/playerglobal_docs/flash.text.ime.xml new file mode 100644 index 0000000..39d3e6d --- /dev/null +++ b/language-server/playerglobal_docs/flash.text.ime.xml @@ -0,0 +1,174 @@ +flash.text.imeIIMEClient + +Interface for IME (input method editor) clients. +Interface for IME (input method editor) clients. Components based on the flash.text.engine package must implement +this interface to support editing text inline using an IME. This interface is not used with TextField objects. +TextLayoutFramework (TLF) uses this interface to support inline IME, so clients using TLF do not need to implement this +interface. +

To support inline IME, set the imeClient property of an ImeEvent.IME_START_COMPOSITION event to +an object which implements this interface.

+ +

The following terms are often used in the IME related API:

+
  • A conversation is the interchange between the IME and the application. During a conversation, a composition is +updated one or more times and then confirmed by the user.
  • A composition identifies the text entered by the user through the IME; including associated input state information +such as the selected range and the extent of any clauses.
  • A clause is a range of the composition possibly sharing semantic information, such as indicating whether the input is +in a selected or converted state. A composition contains zero or more clauses.
+
flash.text.ime.CompositionAttributeRangeflash.events.IMEEvent.imeClienttextInput + Dispatched when the user enters text.flash.events.TextEvent.TEXT_INPUTflash.events.TextEvent + Dispatched when the user enters text. For IME (input method editor) clients, the receiver should + insert the string contained in the event object's text property at the current insertion point. + imeStartComposition + Dispatched when the user begins to use an IME (input method editor).flash.events.IMEEvent.IME_START_COMPOSITIONflash.events.IMEEvent + Dispatched when the user begins to use an IME (input method editor). + confirmComposition + Use this callback to end the inline editing session and confirm the text.textStringnull the final state of the text in the inline session (the confirmed text). + preserveSelectionBooleanfalse when true, you should not reset the current selection to the end of the confirmed text. + + Use this callback to end the inline editing session and confirm the text. + + getTextBounds + The IME uses this method to query the bounding box of the text currently edited with the IME client.The bounding box of the specified range of text, or null if one or both of the indexes are invalid. + This method returns the same value if startIndex is greater or less than endIndex. The same value should be returned whether or not startIndex is greater or less than endIndex. + flash.geom:RectanglestartIndexintAn integer that specifies the starting location of the range of text from the bounding box you are measuring. + endIndexintOptional; an integer that specifies the ending location of the range of text from the bounding box you are measuring. + + + The IME uses this method to query the bounding box of the text currently edited with the IME client. + Use this method to place the candidate window and set the mouse cursor in the IME client when the mouse is over the + text field or other component that supports IME. + + getTextInRange + Gets the specified range of text from the component.The requested text, or null if no text is available in the requested range + or if either or both of the indexes are invalid. The same value should be returned + independant of whether startIndex is greater or less than endIndex. + + StringstartIndexintan integer that specifies the starting location of the range of text to be retrieved. + endIndexintan integer that specifies the ending location of the range of text to be retrieved. + + + Gets the specified range of text from the component. This method is called during IME reconversion. + + selectRange + Sets the range of selected text in the component.anchorIndexintThe zero-based index value of the character at the anchor end of the selection + activeIndexintThe zero-based index value of the character at the active end of the selection. + + + Sets the range of selected text in the component. + If either of the arguments is out of bounds the selection should not be changed. + + updateComposition + Callback for updating the contents of the inline editing session.textString Contains the text of the inline edit session from the IME. + attributes Contains an array of composition clauses with adornment info. + compositionStartIndexint Start of the inline session relative to the start of the text object. + compositionEndIndexint End of the inline session relative to the start of the text object. + + Callback for updating the contents of the inline editing session. + This method is called whenever the text being edited with the IME has changed + and its contents are used by the client to redraw the entire inline editing session. + + compositionEndIndex + The zero-based character index value of the end of the current edit session text (such as + all text in the inline session that is not confirmed to the document).int + The zero-based character index value of the end of the current edit session text (such as + all text in the inline session that is not confirmed to the document). + + compositionStartIndex + The zero-based character index value of the start of the current edit session text (such as + all text in the inline session that is not confirmed to the document).int + The zero-based character index value of the start of the current edit session text (such as + all text in the inline session that is not confirmed to the document). + + selectionActiveIndex + The zero-based character index value of the last character in the current selection.int + The zero-based character index value of the last character in the current selection. + + selectionAnchorIndex + The zero-based character index value of the first character in the current selection.int + The zero-based character index value of the first character in the current selection. + + verticalTextLayout + Indicates whether the text in the component is vertical or not.Boolean + Indicates whether the text in the component is vertical or not. This property directs the positioning + of the candidate window (such as beside vertical text or below horizontal text). + +
CompositionAttributeRange +The CompositionAttributeRange class represents a range of composition attributes for use with IME (input method editor) events.Object +The CompositionAttributeRange class represents a range of composition attributes for use with IME (input method editor) events. +For example, when editing text in the IME, the text is divided by the IME into composition ranges. +These composition ranges are flagged as selected (such as currently being lengthened, shortened, or edited), +and/or converted (meaning the range went through the IME dictionary lookup, already). + +

By convention, the client should adorn these composition ranges with underlining or highlighting according to +the flags.

+ +

For example:

+ + !converted = thick gray underline (raw text) + !selected && converted = thin black underline + selected && converted = thick black underline + + +
flash.text.ime.IIMEClientCompositionAttributeRange + Creates a CompositionAttributeRange object.relativeStartint The zero based index of the first character included in the character range. + relativeEndint The zero based index of the last character included in the character range. + selectedBoolean Defines the current composition clause as active or not. + convertedBoolean Defines the current clause as processed by the IME and waiting for user confirmation. + + Constructor for CompositionAttributeRange objects. + + Creates a CompositionAttributeRange object. + + converted + A property defining the current clause has been processed by the IME + and the clause is waiting to be accepted or confirmed by the user.Boolean + A property defining the current clause has been processed by the IME + and the clause is waiting to be accepted or confirmed by the user. + + relativeEnd + The position of the end of the composition clause, relative to the beginning + of the inline edit session.int + The position of the end of the composition clause, relative to the beginning + of the inline edit session. + For example, 0 equals the start of the text the IME reads (however, text might exist + before that position in the edit field). + + relativeStart + The relative start position from the beginning of the current inline editing session.int + The relative start position from the beginning of the current inline editing session. + For example, 0 equals the start of the text the IME reads (however, text might exist + before that position in the edit field). + + selected + A property defining the current composition clause is active and + lengthened or shortened or edited with the IME while the neighboring + clauses are not changing.Boolean + A property defining the current composition clause is active and + lengthened or shortened or edited with the IME while the neighboring + clauses are not changing. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.text.xml b/language-server/playerglobal_docs/flash.text.xml new file mode 100644 index 0000000..75f937d --- /dev/null +++ b/language-server/playerglobal_docs/flash.text.xml @@ -0,0 +1,5223 @@ +flash.textTextExtent + + The TextExtent class contains information about the extents of some + text in a text field.Object + The TextExtent class contains information about the extents of some + text in a text field. Objects of this class are returned by the + TextFormat.getTextExtent method. + TextExtentwidthNumberheightNumbertextFieldWidthNumbertextFieldHeightNumberascentNumberdescentNumberascentNumberdescentNumberheightNumbertextFieldHeightNumbertextFieldWidthNumberwidthNumberCSMSettings + The CSMSettings class contains properties for use with the + TextRenderer.setAdvancedAntiAliasingTable() method + to provide continuous stroke modulation (CSM).Object + The CSMSettings class contains properties for use with the + TextRenderer.setAdvancedAntiAliasingTable() method + to provide continuous stroke modulation (CSM). CSM is the continuous + modulation of both stroke weight and edge sharpness. + + TextRenderer.setAdvancedAntiAliasingTable()CSMSettings + Creates a new CSMSettings object which stores stroke values for custom anti-aliasing settings.fontSizeNumberThe size, in pixels, for which the settings apply. + insideCutoffNumberThe inside cutoff value, above which densities are set to a maximum density + value (such as 255). + outsideCutoffNumberThe outside cutoff value, below which densities are set to zero. + + + Creates a new CSMSettings object which stores stroke values for custom anti-aliasing settings. + fontSize + The size, in pixels, for which the settings apply.Number + The size, in pixels, for which the settings apply. + +

The advancedAntiAliasingTable array passed to the + setAdvancedAntiAliasingTable() method can contain multiple + entries that specify CSM settings for different font sizes. Using this + property, you can specify the font size to which the other settings apply. +

+
TextRenderer.setAdvancedAntiAliasingTable()
insideCutoff + The inside cutoff value, above which densities are set to a maximum density + value (such as 255).Number + The inside cutoff value, above which densities are set to a maximum density + value (such as 255). + + TextRenderer.setAdvancedAntiAliasingTable()outsideCutoff + The outside cutoff value, below which densities are set to zero.Number + The outside cutoff value, below which densities are set to zero. + + TextRenderer.setAdvancedAntiAliasingTable()
TextColorType +The TextColorType class provides color values for the flash.text.TextRenderer class.Object +The TextColorType class provides color values for the flash.text.TextRenderer class. + +flash.text.TextRendererDARK_COLOR + Used in the colorType parameter in the setAdvancedAntiAliasingTable() method.Bob Pappas + darkString + Used in the colorType parameter in the setAdvancedAntiAliasingTable() method. + Use the syntax TextColorType.DARK_COLOR. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()LIGHT_COLOR + Used in the colorType parameter in the setAdvancedAntiAliasingTable() method.lightString + Used in the colorType parameter in the setAdvancedAntiAliasingTable() method. + Use the syntax TextColorType.LIGHT_COLOR. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()GridFitType +The GridFitType class defines values for grid fitting in the TextField class.Object +The GridFitType class defines values for grid fitting in the TextField class. + +flash.text.TextFieldNONE + Doesn't set grid fitting.Bob Pappas + + noneString + Doesn't set grid fitting. Horizontal and vertical lines + in the glyphs are not forced to the pixel grid. + This constant is used in setting the gridFitType property of the + TextField class. This is often a good setting for animation + or for large font sizes. + Use the syntax GridFitType.NONE. + flash.text.TextField.gridFitTypePIXEL + Fits strong horizontal and vertical lines to the pixel grid.Bob Pappas + + pixelString + Fits strong horizontal and vertical lines to the pixel grid. + This constant is used in setting the gridFitType property of the + TextField class. This setting only works for left-justified text + fields and acts like the GridFitType.SUBPIXEL constant in static + text. This setting generally provides the best readability for left-aligned text. + Use the syntax GridFitType.PIXEL. + flash.text.TextField.gridFitTypeSUBPIXEL + Fits strong horizontal and vertical lines to the sub-pixel + grid on LCD monitors.Bob Pappas + + subpixelString + Fits strong horizontal and vertical lines to the sub-pixel + grid on LCD monitors. (Red, green, and blue are actual pixels on an LCD screen.) + This is often a good setting for right-aligned or center-aligned dynamic + text, and it is sometimes a useful tradeoff for animation vs. text quality. + This constant is used in setting the gridFitType property of the + TextField class. + Use the syntax GridFitType.SUBPIXEL. + flash.text.TextField.gridFitTypeStaticText + This class represents StaticText objects on the display list.flash.display:DisplayObject + This class represents StaticText objects on the display list. + You cannot create a StaticText object using ActionScript. Only the authoring tool + can create a StaticText object. An attempt to create a new StaticText object generates + an ArgumentError. + +

To create a reference to an existing static text field in ActionScript 3.0, + you can iterate over the items in the display list. For example, the following snippet checks + to see if the display list contains a static text field and assigns the field to + a variable:

+ + + var i:uint; + for (i = 0; i < this.numChildren; i++) { + var displayitem:DisplayObject = this.getChildAt(i); + if (displayitem instanceof StaticText) { + trace("a static text field is item " + i + " on the display list"); + var myFieldLabel:StaticText = StaticText(displayitem); + trace("and contains the text: " + myFieldLabel.text); + } + } + +
text + Returns the current text of the static text field.String + Returns the current text of the static text field. The authoring tool may export multiple text field + objects comprising the complete text. For example, for vertical text, the authoring tool will create + one text field per character. +
TextField + The TextField class is used to create display objects for text display and input.The TextField class is used to create display objects for text display and input. + + flash.display:InteractiveObject + The TextField class is used to create display objects for text display and input. + You can use the TextField class to perform low-level text rendering. + However, in Flex, you typically use the Label, Text, TextArea, and TextInput controls to process text. + + You can give a text field an instance name in the Property inspector and + use the methods and properties of the TextField class to manipulate it with ActionScript. + TextField instance names are displayed in the Movie Explorer and in the Insert Target Path dialog box + in the Actions panel. + +

To create a text field dynamically, use the TextField() constructor.

+ +

The methods of the TextField class let you set, select, and manipulate text in a dynamic or input + text field that you create during authoring or at runtime.

+ +

ActionScript provides several ways to + format your text at runtime. The TextFormat class lets you set character and paragraph formatting + for TextField objects. You can apply Cascading Style Sheets (CSS) styles + to text fields by using the TextField.styleSheet property and the StyleSheet class. You can use CSS to + style built-in HTML tags, define new formatting tags, or apply styles. + You can assign HTML formatted text, which optionally uses CSS styles, directly to a text + field. HTML text that you assign to a text field can contain embedded + media (movie clips, SWF files, GIF files, PNG files, and JPEG files). The text wraps around the + embedded media in the same way that a web browser wraps text around media embedded in an HTML document.

+ +

Flash Player supports a subset of HTML tags that you can use to format text. See the list of supported + HTML tags in the description of the htmlText property.

+ +
The following example uses the TextFieldExample class to + display a text message. This is accomplished by using the following steps: +
  1. A label property of type TextField is created.
  2. The class constructor calls the configureLabel() function.
  3. The configureLabel() method first creates a new TextField object and assigns it to + the label property, and then sets its parameters to the following: +
    • Left-justify the text field.
    • Enable the background fill.
    • Enable the border.
    +
  4. The configureLabel() method creates the format variable and assigns it to + a new TextFormat instance with its parameters set to the following: +
    • Font type = Verdana
    • Font color = solid red
    • Font size = 10
    • Font underline = true
    +
  5. The defaultTextFormat property of the label text field + is set to format, and the label instance is added to the display list, + which initially displays a text field with no text on the stage.
  6. The constructor sets the text of the label text field to + "Hello world and welcome to the show." by calling the + setLabel() method.
+ +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + + public class TextFieldExample extends Sprite { + private var label:TextField; + private var labelText:String = "Hello world and welcome to the show."; + + public function TextFieldExample() { + configureLabel(); + setLabel(labelText); + } + + public function setLabel(str:String):void { + label.text = str; + } + + private function configureLabel():void { + label = new TextField(); + label.autoSize = TextFieldAutoSize.LEFT; + label.background = true; + label.border = true; + + var format:TextFormat = new TextFormat(); + format.font = "Verdana"; + format.color = 0xFF0000; + format.size = 10; + format.underline = true; + + label.defaultTextFormat = format; + addChild(label); + } + } +} +
flash.text.TextFormatflash.text.StyleSheethtmlTexttextInteractionModeChange + Flash Player dispatches the textInteractionModeChange event when a user + changes the interaction mode of a text field.flash.events.Event + Flash Player dispatches the textInteractionModeChange event when a user + changes the interaction mode of a text field. + for example on Android, one can toggle from NORMAL mode to SELECTION mode using context menu + options + textInput + Flash Player dispatches the textInput event when a user enters one or more + characters of text.flash.events.TextEvent.TEXT_INPUTflash.events.TextEvent + Flash Player dispatches the textInput event when a user enters one or more + characters of text. Various + text input methods can generate this event, including standard keyboards, + input method editors (IMEs), voice or speech recognition systems, and even the act + of pasting plain text with no formatting or style information. + The following example defines two TextField objects: + the first TextField object is an input text field, and the second TextField object + is a dynamic text field. As you enter text characters in + the first text field, the textInput event is dispatched, the textInputHandler() handler is called, and the characters display in the second + text field. When you paste a + block of text into the input field, the event handler copies the entire block + into the other field. + + +package +{ + import flash.display.Sprite; + import flash.text.*; + import flash.events.Event; + import flash.events.TextEvent; + import flash.events.MouseEvent; + + public class TextInputExample extends Sprite + { + private var myTextBox1:TextField = new TextField(); + private var myTextBox2:TextField = new TextField(); + + public function TextInputExample() + { + myTextBox1.type = TextFieldType.INPUT; + myTextBox1.width = 200; + myTextBox1.height = 20; + myTextBox1.background = true; + myTextBox1.border = true; + + myTextBox2.x=220; + + addChild(myTextBox1); + addChild(myTextBox2); + myTextBox1.addEventListener(TextEvent.TEXT_INPUT,textInputHandler); + } + + public function textInputHandler(event:TextEvent):void + { + myTextBox2.text=event.text; + } + } +} +scroll + Dispatched by a TextField object after the user scrolls.flash.events.Event.SCROLLflash.events.Event + Dispatched by a TextField object after the user scrolls. + The following example defines two TextField objects. + The first TextField object has two associated event handlers. When you click the mouse + inside this first text field, the mouseDown event is dispatched, and the associated mouseDownScroll handler is called. The + mouseDownScroll() handler causes the field to scroll. Then, the + scroll event is dispatched, and the associated scrollHandler() + handler updates the second text field to display the current scroll position. + + +package +{ + import flash.display.Sprite; + import flash.text.*; + import flash.events.Event; + import flash.events.TextEvent; + import flash.events.MouseEvent; + + public class TextScrollExample extends Sprite + { + private var myTextBox1:TextField = new TextField(); + private var myTextBox2:TextField = new TextField(); + private var myText:String = "Hello world and welcome to the show. It's really nice to meet you. Take your coat off and stay a while. OK, show is over. Hope you had fun. You can go home now. Don't forget to tip your waiter. There are mints in the bowl by the door. Thank you. Please come again."; + + public function TextScrollExample() + { + myTextBox1.text = myText; + myTextBox1.width = 200; + myTextBox1.height = 50; + myTextBox1.multiline = true; + myTextBox1.wordWrap = true; + myTextBox1.background = true; + myTextBox1.border = true; + + myTextBox2.x=220; + myTextBox2.text="scrolled to line: " + myTextBox1.scrollV; + + addChild(myTextBox1); + addChild(myTextBox2); + myTextBox1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll); + myTextBox1.addEventListener(Event.SCROLL, scrollHandler); + } + + public function mouseDownScroll(event:MouseEvent):void + { + myTextBox1.scrollV++; + } + public function scrollHandler(event:Event):void + { + myTextBox2.text="scrolled to line: " + myTextBox1.scrollV; + } + } +} +link + Dispatched when a user clicks a hyperlink in an + HTML-enabled text field, where the URL begins with "event:".flash.events.TextEvent.LINKflash.events.TextEvent + Dispatched when a user clicks a hyperlink in an + HTML-enabled text field, where the URL begins with "event:". The remainder of the URL after + "event:" is placed in the text property of the LINK event. +

Note: The default behavior, adding the text to the text field, + occurs only when Flash Player generates the event, which in this case happens when + a user attempts to input text. You cannot put text into a text field by sending it textInput + events.

+
In the following example, the playMP3() function is defined. + A TextField object named list is created and populated with HTML text. + The text "Track 1" and "Track 2" are links inside the text field. + The playMP3() function is called when the user clicks either link. The name of the MP3 + file, which follows the string "event:" in the href attribute of the + HTML tag, is passed to the linkHandler() method as the text + property of the link event object. + + +package { + import flash.display.Sprite; + import flash.errors.IOError; + import flash.events.IOErrorEvent; + import flash.events.TextEvent; + import flash.media.Sound; + import flash.media.SoundChannel; + import flash.net.URLRequest; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class TextField_event_link extends Sprite + { + private var myMP3:Sound; + public function TextField_event_link() { + myMP3 = new Sound(); + var list:TextField = new TextField(); + list.autoSize = TextFieldAutoSize.LEFT; + list.multiline = true; + list.htmlText = "<a href=\"event:track1.mp3\">Track 1</a><br>"; + list.htmlText += "<a href=\"event:track2.mp3\">Track 2</a><br>"; + addEventListener(TextEvent.LINK, linkHandler); + addChild(list); + } + + private function playMP3(mp3:String):void { + try { + myMP3.load(new URLRequest(mp3)); + myMP3.play(); + } + catch(err:Error) { + trace(err.message); + } + myMP3.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + } + + private function linkHandler(linkEvent:TextEvent):void { + playMP3(linkEvent.text); + } + + private function errorHandler(errorEvent:IOErrorEvent):void { + trace(errorEvent.text); + } + } +} +
change + Dispatched after a control value is modified, unlike + the textInput event, which is dispatched before the value is modified.flash.events.Event.CHANGEflash.events.Event + Dispatched after a control value is modified, unlike + the textInput event, which is dispatched before the value is modified. + Unlike the W3C DOM Event Model version of the change event, which dispatches the + event only after the control loses focus, the ActionScript 3.0 version of the + change event is dispatched any time the control changes. For example, if a user + types text into a text field, a change event is dispatched after every keystroke. + In the following example, the text that the user enters (user input) is immediately copied + (echoed) into another text field with a different text format. + +

Two text fields are created, one for the user input and the other + (headingTextField) for the copy of the user input. A TextFormat + object is also created and the default text format is assigned to the + headingTextField text field. When the content of the text field + is changed, the changeHandler() method is invoked, which assigns + the text in the inputTextField text field to the headingTextField + text field. (If the method was called for the TextEvent.TEXT_INPUT event + instead of the Event.CHANGE event, the content of the user input + is copied only after the user has entered more text.)

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + import flash.text.TextFormatAlign; + import flash.events.Event; + + import flash.events.TextEvent; + + public class TextField_Event_changeExample extends Sprite { + private var inputTextField:TextField = new TextField(); + private var headingTextField:TextField = new TextField(); + private var newFormat:TextFormat = new TextFormat(); + + public function TextField_Event_changeExample() { + headingTextField.x = 10; + headingTextField.y = 10; + headingTextField.height = 30; + headingTextField.width = 400; + headingTextField.background = true; + headingTextField.backgroundColor = 0xF5F5DC; + headingTextField.selectable = false; + + inputTextField.x = 10; + inputTextField.y = 70; + inputTextField.height = 20; + inputTextField.width = 230; + inputTextField.background = true; + inputTextField.border = true; + inputTextField.maxChars = 40; + inputTextField.wordWrap = true; + inputTextField.type = TextFieldType.INPUT; + + inputTextField.addEventListener(Event.CHANGE, changeHandler); + + newFormat.bold = true; + newFormat.size = 18; + newFormat.color = 0xFF0000; + newFormat.align = TextFormatAlign.CENTER; + + headingTextField.defaultTextFormat = newFormat; + + this.addChild(inputTextField); + this.addChild(headingTextField); + } + + private function changeHandler(e:Event):void { + headingTextField.text = inputTextField.text; + } + } +} +
TextField + Creates a new TextField instance. + Creates a new TextField instance. After you create the TextField instance, call the + addChild() or addChildAt() method of the parent + DisplayObjectContainer object to add the TextField instance to the display list. +

The default size for a text field is 100 x 100 pixels.

+ + + +
The following example shows how you can dynamically create an input TextField object in ActionScript 3.0 by setting the text field object's type property to the TextFieldType.INPUT constant. + Example provided by + ActionScriptExamples.com. + +var theTextField:TextField = new TextField(); +theTextField.type = TextFieldType.INPUT; +theTextField.border = true; +theTextField.x = 10; +theTextField.y = 10; +theTextField.multiline = true; +theTextField.wordWrap = true; +addChild(theTextField); +
appendText + Appends the string specified by the newText parameter to the end of the text + of the text field.newTextStringThe string to append to the existing text. + + Appends text to the end of the existing text of the TextField. + + + Appends the string specified by the newText parameter to the end of the text + of the text field. This method is more efficient than an addition assignment (+=) on + a text property (such as someTextField.text += moreText), + particularly for a text field that contains a significant amount of content. + + The following example displays the time if it's not the weekend or the text, "It's the weekend," + if it is. It also counts the number of characters up to a certain position and the number of lines in the text field. + +

The outputText text field is set to automatically fit the text and to resize as a + left-justified text using autoSize property. The outputText.text property writes the first + line of the content and the method appendText() appends the rest of the content. (It is not + necessary to start with the text property. The appendText() method could also be + used to append text from the outset.) Setting the text property a second time will overwrite + the original text. Use += operator to append content with the text property.

+ +

The if statement checks if the date is Saturday (6) or Sunday (0). If it's not, the + toLocaleTimeString() method returns the local time, which is appended to the text field's content.

+ +

The text field's length property is used to read the number of characters until right + before the function is called, and the property numLines is used to count the number of lines + in the text field. Note that the empty lines are counted in the number of lines and the empty spaces and + line breaks (\n) are counted in determining the content length.

+ + + package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class TextField_appendTextExample extends Sprite { + + public function TextField_appendTextExample() { + var outputText:TextField = new TextField(); + var today:Date = new Date(); + + outputText.x = 10; + outputText.y = 10; + outputText.background = true; + outputText.autoSize = TextFieldAutoSize.LEFT; + + outputText.text = "WHAT TIME IS IT?" + "\n\n"; + + if((today.day == 0) || (today.day == 6)) { + outputText.appendText("It's the weekend."); + outputText.appendText("\n\n"); + + } else { + outputText.appendText("The time is: "); + outputText.appendText(today.toLocaleTimeString() + ".\n\n"); + } + + outputText.appendText("Number of characters including line breaks and spaces so far: "); + outputText.appendText(outputText.length.toString() + "\n"); + outputText.appendText("Number of lines in the outputText: "); + outputText.appendText(outputText.numLines.toString()); + + this.addChild(outputText); + } + } +} +
getCharBoundaries + Returns a rectangle that is the bounding box of the character.A rectangle with x and y minimum and maximum values + defining the bounding box of the character. + + flash.geom:RectanglecharIndexintThe zero-based index value for the character (for example, the first + position is 0, the second position is 1, and so on). + + Returns a rectangle that is the bounding box of the character. + + + Returns a rectangle that is the bounding box of the character. + + In the following example the getCharBoundaries() method is used to mark + (put a spotlight on) a character that is selected by the user. + +

The class defines the spotlight Shape object that will be used to draw a rectangle around + each character that is selected. When the user clicks on the myTextField text field, the + clickHandler() method is invoked.

+ +

In the clickHandler() method, the getCharIndexAtPoint() method gets the clicked character's + index based on the localX and localY coordinates of the mouse click, which is relative + to the containing Sprite. The getCharIndexAtPoint() method returns -1 if + the point (mouse click) was not over any character. Since the text field could be larger than the text, the returned + integer (index) is checked to make sure the user has clicked on a character. The index integer + is also used by getCharBoundaries() to get a Rectangle object that holds the boundary + of the character. The clear() method clears any previously displayed spotlight Shape object. A + new rectangle the size of the character's width and height boundaries is produced at the location of the character + (offset from the (10, 10) coordinates) using the returned frame rectangle's x and y coordinates. + To put the spotlight on the character, the spotlight Shape object is filled with color yellow and the + opacity is set to 35 percent, so the character can be seen. Note that spaces are also considered a character.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.geom.Rectangle; + import flash.events.MouseEvent; + import flash.text.TextFieldAutoSize; + import flash.display.Shape; + + public class TextField_getCharBoundariesExample extends Sprite + { + private var myTextField:TextField = new TextField(); + private var spotlight:Shape = new Shape(); + + public function TextField_getCharBoundariesExample() { + + myTextField.x = 10; + myTextField.y = 10; + myTextField.border = true; + myTextField.selectable = false; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + myTextField.text = "Selected a character from this text by clicking on it." + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(myTextField); + this.addChild(spotlight); + } + + private function clickHandler (e:MouseEvent):void { + var index:int = myTextField.getCharIndexAtPoint(e.localX, e.localY); + + if (index != -1) { + var frame:Rectangle = myTextField.getCharBoundaries(index); + + spotlight.graphics.clear(); + spotlight.graphics.beginFill(0xFFFF00, .35); + spotlight.graphics.drawRect((frame.x + 10), (frame.y + 10), frame.width, frame.height); + spotlight.graphics.endFill(); + } + } + } +} +
flash.geom.Rectangle
getCharIndexAtPoint + Returns the zero-based index value of the character at the point specified by the x + and y parameters.The zero-based index value of the character (for example, the first position is 0, + the second position is 1, and so on). Returns -1 if the point is not over any character. + + intxNumberThe x coordinate of the character. + + yNumberThe y coordinate of the character. + + Returns the zero-based index value of the character. + + + Returns the zero-based index value of the character at the point specified by the x + and y parameters. + + In the following example, when a user clicked on a character, the character is echoed + in another text field above the text. + +

The first text field holds the text the user is going to select. In order to make sure the text + is clicked but not selected, selectable property is set to false. When the user clicks + on the firstTextField text field, the clickHandler() method is invoked.

+ +

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's + index based on the localX and localY coordinates of the mouse click. Since the text field + could be larger than the text, the return integer (index) is checked to make sure the user has clicked + on a character. (The getCharIndexAtPoint() method returns -1, if the point (mouse click) + was not over a character.) The mouse coordinates is used to set the coordinates of the new text field where the + echoed character will appear. The color of the character in the second text field is set to red. Finally + the text of the second field is set to the selected character, which is retrieved using the charAt() method. + Note that using the text property instead of the appendText() method will overwrite the character + in the second text field, instead of appending it.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.geom.Rectangle; + import flash.events.MouseEvent; + import flash.text.TextFieldAutoSize; + + public class TextField_getCharIndexAtPointExample extends Sprite { + private var firstTextField:TextField = new TextField(); + private var secondTextField:TextField = new TextField(); + + public function TextField_getCharIndexAtPointExample() { + + firstTextField.x = 100; + firstTextField.y = 100; + firstTextField.width = 260; + firstTextField.height = 20; + firstTextField.border = true; + firstTextField.background = true; + firstTextField.selectable = false; + + firstTextField.text = "Selected a character from this text by clicking on it." + + firstTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(firstTextField); + this.addChild(secondTextField); + } + + private function clickHandler (e:MouseEvent):void { + var index:int = firstTextField.getCharIndexAtPoint(e.localX, e.localY); + + if (index != -1) { + secondTextField.x = mouseX; + secondTextField.y = 70; + secondTextField.border = true; + secondTextField.selectable = false; + secondTextField.background = true; + secondTextField.textColor = 0xFF0000; + secondTextField.autoSize = TextFieldAutoSize.LEFT; + secondTextField.text = firstTextField.text.charAt(index); + } + } + } +} +
getFirstCharInParagraph + Given a character index, returns the index of the first character in the same paragraph.The character index specified is out of range. + + RangeErrorRangeErrorThe zero-based index value of the first character in the same paragraph. + + intcharIndexintThe zero-based index value of the character (for example, the first character is 0, + the second character is 1, and so on). + + The zero-based index value of the character. + + + Given a character index, returns the index of the first character in the same paragraph. + + In the following example, paragraph formatting is applied to the text field content. + When the user clicks on a paragraph, the text of the paragraph will be aligned right and when the user + clicks on the paragraph again, it will return to the original (default) format (left-align). + +

In the constructor, the myTextField text field is set to text wrap. The getTextFormat + method returns the original format of the first character of the content of the text field, which is placed + in the originalFormat TextFormat object. A new TextFormat object (newFormat) is + also defined and its align property is assigned to right-justified. When the user clicks + on the text field, the clickHandler() method is invoked.

+ +

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's + index based on the localX and localY coordinates of the mouse click. The first if + statement checks to see if the use has clicked on a character. Using the clickIndex integer returned by the + getCharIndexAtPoint() method, the getFirstCharInParagraph() method returns the index of the + first character in the paragraph the user has clicked. The index of the last character in the paragraph is + determined by adding the length of the paragraph (using getParagraphLength() method) to the index of the first + character in the paragraph, minus the last character (\n). The second if statement + checks the format of the first character in the paragraph. If its alignment value is the same as the + original format (left-justified), the new format is applied to all the characters in the paragraph. + Otherwise, the format of the paragraph is set back to the original format. Alignment, along with formatting + like indent, bullet, tab stop, left and right margin are formats that are meant for paragraphs. + Note that once word wrap or line break is used, the formatting will only apply to the first line of the + paragraph if endIndex argument is not defined for the setTextFormat() method.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.MouseEvent; + import flash.text.TextFormat; + import flash.text.TextFormatAlign; + + public class TextField_getFirstCharInParagraphExample extends Sprite + { + private var myTextField:TextField = new TextField(); + private var originalFormat:TextFormat = new TextFormat(); + private var newFormat:TextFormat = new TextFormat(); + + public function TextField_getFirstCharInParagraphExample() { + myTextField.x = 10; + myTextField.y = 10; + myTextField.border = true; + myTextField.wordWrap = true; + myTextField.width = 300; + myTextField.height = 300; + myTextField.background = true; + + myTextField.appendText("The TextField class is used to create display objects for " + + "text display and input. All dynamic and input text fields in a SWF file " + + "are instances of the TextField class. You can use the TextField class " + + "to perform low-level text rendering. However, in Flex, you typically use " + + "the Label, Text, TextArea, and TextInput controls to process text. " + + "You can give a text field an instance name in the Property inspector " + + "and use the methods and properties of the TextField class to manipulate it with ActionScript. " + + "TextField instance names are displayed in the Movie Explorer and in the Insert " + + "Target Path dialog box in the Actions panel.\n\n" + + "To create a text field dynamically, use the TextField constructor.\n\n" + + "The methods of the TextField class let you set, select, and manipulate " + + "text in a dynamic or input text field that you create during authoring or at runtime.\n\n"); + + originalFormat = myTextField.getTextFormat(0); + + newFormat.align = TextFormatAlign.RIGHT; + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(myTextField); + } + + private function clickHandler(e:MouseEvent):void { + var clickIndex:int = myTextField.getCharIndexAtPoint(e.localX, e.localY); + + if(clickIndex != -1) { + var paragraphFirstIndex:int = myTextField.getFirstCharInParagraph(clickIndex); + var paragraphEndIndex:int = paragraphFirstIndex + ((myTextField.getParagraphLength(clickIndex) - 1)); + + if (myTextField.getTextFormat(paragraphFirstIndex).align == originalFormat.align) { + myTextField.setTextFormat(newFormat, paragraphFirstIndex, paragraphEndIndex); + }else { + myTextField.setTextFormat(originalFormat, paragraphFirstIndex, paragraphEndIndex); + } + } + } + } +} + +
getImageReference + Returns a DisplayObject reference for the given id, for an image or SWF file + that has been added to an HTML-formatted text field by using an &lt;img&gt; tag.The display object corresponding to the image or SWF file with the matching id + attribute in the <img> tag of the text field. For media loaded from an external source, + this object is a Loader object, and, once loaded, the media object is a child of that Loader object. For media + embedded in the SWF file, it is the loaded object. If no <img> tag with + the matching id exists, the method returns null. + + flash.display:DisplayObjectidStringThe id to match (in the id attribute of the + <img> tag). + + + Returns a DisplayObject reference for the given id, for an image or SWF file + that has been added to an HTML-formatted text field by using an <img> tag. + The <img> tag is in the following format: + +

   <img src = 'filename.jpg' id = 'instanceName' >

+ +
In the following example, when the text field is clicked, the image in the field is set to 25 percent opacity and + it rotates 90 degrees from its original rotation. The image will continue to rotate with each subsequent click. + +

The image (image.jpg) is included via the HTML. (Here it is assumed that an image file is in the same + directory as the SWF file.) An id attribute needs to be defined for the img tag in order + to access the image using getImageReference() method. The htmlText property is used to include + HTML-formatted string content. When the user clicks on the myTextField text field, the clickHandler() + method is invoked.

+ +

In the clickHandler() method, the getImageReference() method returns a reference to + the image as a DisplayObject. This reference can be used to manipulate the image, like any DisplayObject + object. Here, the alpha (transparency) and rotation properties are set. The transform + property can also be used to access the display object's matrix, color transform, and pixel bounds. Note also that + flash.display.DisplayObject needs to be imported.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.display.DisplayObject; + + import flash.text.TextFieldAutoSize; + + public class TextField_getImageReferenceExample extends Sprite + { + private var myTextField:TextField = new TextField(); + + public function TextField_getImageReferenceExample() + { + var myText1:String = "<p>Here is an image we want to mainpulate: <img src='image.jpg' id='testimage'></p>"; + + myTextField.x = 10; + myTextField.y = 10; + myTextField.width = 250; + myTextField.height = 250; + myTextField.background = true; + myTextField.border = true; + myTextField.border = true; + myTextField.multiline = true; + + myTextField.htmlText = myText1; + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(myTextField); + } + + private function clickHandler(e:MouseEvent):void { + var imageRef:DisplayObject = myTextField.getImageReference("testimage"); + + imageRef.rotation += 90; + imageRef.x = 125; + imageRef.y = 125; + imageRef.alpha = 0.25; + } + } +} +
htmlText
getLineIndexAtPoint + Returns the zero-based index value of the line at the point specified by the x + and y parameters.The zero-based index value of the line (for example, the first line is 0, the + second line is 1, and so on). Returns -1 if the point is not over any line. + + intxNumberThe x coordinate of the line. + + yNumberThe y coordinate of the line. + + The zero-based index value of the line at a specified point. + + + Returns the zero-based index value of the line at the point specified by the x + and y parameters. + + In the following example, when a user selects a line from the Shakespeare's sonnet, + it is copied (appended) into a new text field. + +

In the constructor, the poem text field is set not to wrap (since it's a poem). + The autoSize property also is used to set the text to automatically fit and to have + it resize as a left-justified text. The poemCopy text field is placed under the + poem text field. When a user clicks on some line of the poem, the clickHandler() + method is invoked.

+ +

In clickHandler() method, the getLineIndexAtPoint() method returns + the line index of where the user has clicked based on the localX and localY + coordinates of the mouse click. (Since the original poem fits the size of the text field here, + it is not necessary to check for out of range error (RangeError) thrown by + getCharIndexAtPoint() method.) The line index is then used to get the content of + the line as a string with the getLineText() method, which is then appended to the + poemCopy text field content. The copying can go on continuously but after a point, + the text will be outside of the range of the viewable poemCopy text field.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.MouseEvent; + import flash.text.TextFormat; + import flash.text.TextFieldAutoSize; + + public class TextField_getLineIndexAtPointExample extends Sprite { + private var poem:TextField = new TextField(); + private var poemCopy:TextField = new TextField(); + + public function TextField_getLineIndexAtPointExample() { + poem.border = true; + poem.autoSize = TextFieldAutoSize.LEFT; + poem.x = 10; + poem.wordWrap = false; + + poemCopy.height = 250; + poemCopy.width = 270; + poemCopy.y = 230; + poemCopy.x = 10; + poemCopy.background = true; + poemCopy.border = true; + poemCopy.wordWrap = false; + + poem.appendText("Let me not to the marriage of true minds\n" + + "Admit impediments. love is not love\n" + + "Which alters when it alteration finds\n" + + "Or bends with the remover to remove:\n" + + "O no! it is an ever-fixed mark\n" + + "That looks on tempests and is never shaken;\n" + + "It is the star to every wandering bark,\n" + + "Whose worth's unknown, although his height be taken.\n" + + "Love's not Time's fool, though rosy lips and cheeks\n" + + "Within his bending sickle's compass come:\n" + + "Love alters not with his brief hours and weeks,\n" + + "But bears it out even to the edge of doom.\n" + + "If this be error and upon me proved,\n" + + "I never writ, nor no man ever loved."); + + poem.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(poem); + this.addChild(poemCopy); + } + + private function clickHandler(e:MouseEvent):void { + var index:int = poem.getLineIndexAtPoint(e.localX, e.localY); + var s:String; + + s = poem.getLineText(index); + poemCopy.appendText(s + "\n"); + } + } +} +
getLineIndexOfChar + Returns the zero-based index value of the line containing the character specified + by the charIndex parameter.The character index specified is out of range. + + RangeErrorRangeErrorThe zero-based index value of the line. + + intcharIndexintThe zero-based index value of the character (for example, the first character is 0, + the second character is 1, and so on). + + The zero-based index value of the line containing the character that the + the charIndex parameter specifies. + + + Returns the zero-based index value of the line containing the character specified + by the charIndex parameter. + + In the following example, the getLineIndexOfChar() method returns + the line numbers for the 100th and 500th characters in the text field. + +

The myTextField text field is defined to wrap and resize as a left-justified text. + The getLineIndexOfChar() method returns the line index for the specified character + indexes (100 and 500). This information is then appended after the paragraph. Note that since + line index begins with 0, the line index (index) is increased by 1 to get the line number. + Also if the display is resized the line number may change but the information here will stay the same + since the method is only invoked once.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class TextField_getLineIndexOfCharExample extends Sprite + { + public function TextField_getLineIndexOfCharExample() + { + var myTextField:TextField = new TextField(); + + myTextField.x = 10; + myTextField.y = 10; + myTextField.width = 200; + myTextField.background = true; + myTextField.border = true; + myTextField.wordWrap = true; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + myTextField.appendText("The TextField class is used to create display objects for " + + "text display and input. All dynamic and input text fields in a SWF file" + + "are instances of the TextField class. You can use the TextField class " + + "to perform low-level text rendering. However, in Flex, you typically use " + + "the Label, Text, TextArea, and TextInput controls to process text. " + + "You can give a text field an instance name in the Property inspector " + + "and use the methods and properties of the TextField class to manipulate it with ActionScript. " + + "TextField instance names are displayed in the Movie Explorer and in the Insert " + + "Target Path dialog box in the Actions panel.\n\n"); + + var index:int = myTextField.getLineIndexOfChar(100); + myTextField.appendText("100th character is in line: " + (index + 1) + "\n"); + index = myTextField.getLineIndexOfChar(500); + myTextField.appendText("500th character is in line: " + (index + 1)); + + this.addChild(myTextField); + } + } +} +
getLineLength + Returns the number of characters in a specific text line.The line number specified is out of range. + + RangeErrorRangeErrorThe number of characters in the line. + + intlineIndexintThe line number for which you want the length. + Returns the number of characters in a specific text line. + + + Returns the number of characters in a specific text line. + + In the following example, once the user selects a line, its line length (number of characters) is + displayed in a separate text field. +

As an illustration, myTextField text field, which displays the text that will be counted, is set to + INPUT, meaning users can actually change the lines or add lines between the lines or at the end. + (There is an empty line created by using line break (\n) at the end of the last line.) The countLines + text field, where the result of counting the line length is displayed, is set below myTextField + text field and its text is not selectable. When the user clicks on a line in the myTextField text field, + the clickHandler() method is invoked.

+

In the clickHandler() method, the getLineIndexAtPoint() method returns the line index of + where the user clicked, by using the localX and localY coordinates of the mouse click. + The if statement checks to see if the use has clicked on a character. If so, the + getLineLength() method, using the index of line, returns the number of characters in the line. + Note that the empty lines between the lines include the second line break (\n) and have + a count of 1 character, while the line after the last line has a 0 count. Spaces also count as one character. + The users can write a new line or changes a line and get the character count of the line by clicking on it. + If text wrap is used and the screen is resized, the line index could change.

+ + package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.events.Event; + import flash.events.MouseEvent; + + public class TextField_getLineLengthExample extends Sprite { + private var myTextField:TextField = new TextField(); + private var countLines:TextField = new TextField(); + + public function TextField_getLineLengthExample() { + myTextField.x = 10; + myTextField.y = 10; + myTextField.width = 350; + myTextField.height = 150; + myTextField.background = true; + myTextField.border = true; + myTextField.type = TextFieldType.INPUT; + + myTextField.appendText("Click on the lines to count its number of characters:\n\n"); + myTextField.appendText("This is a short line.\n"); + myTextField.appendText("This is a longer line than the last line.\n\n"); + myTextField.appendText("This one is even longer than the one before. It has two sentences.\n"); + + this.addChild(myTextField); + + countLines.border = true; + countLines.x = 10; + countLines.y = 180; + countLines.height = 30; + countLines.width = 200; + countLines.background = true; + countLines.selectable = false; + + this.addChild(countLines); + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + } + + private function clickHandler(e:MouseEvent):void { + var index:int = myTextField.getLineIndexAtPoint(e.localX, e.localY); + + if (index != -1) { + var lenght:int = myTextField.getLineLength(index); + + countLines.text = "Number of characters in the line is: " + lenght.toString(); + } + } + } +} +
getLineMetrics + Returns metrics information about a given text line.The line number specified is out of range. + + RangeErrorRangeErrorA TextLineMetrics object. + flash.text:TextLineMetricslineIndexintThe line number for which you want metrics information. + Returns metrics information about a given text line. + + + Returns metrics information about a given text line. + + The following example displays some line metrics values for two differently formatted lines of text. + +

The text appended is two lines from the Song of Myself by Walt Whitman. A new TextFormat object + (newFormat) is used to set the format of the second line. The first line holds the + default format. The getLineMetrics() method returns a TextLineMetrics + object for a specific line. (Line index begins with 0.) Using metrics1 and metrics2 + TextLineMetrics objects for the line one and two, respectively, the ascent, descent, height, and weight + value of the line are retrieved and displayed. The result numbers are converted to + string but not rounded. Note that this value is for the line and not a specific character. It + reflects the range of characters for a line. For example, if a line has different characters with + different height formats, the character with the highest height will determine the value. This also + means that if one of the character's format is changes, some of the metrics values could also change.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextLineMetrics; + import flash.text.TextFieldAutoSize; + import flash.text.AntiAliasType; + import flash.text.TextFormat; + + public class TextField_getLineMetricsExample extends Sprite { + + public function TextField_getLineMetricsExample() { + var myTextField:TextField = new TextField(); + var newFormat:TextFormat = new TextFormat(); + + myTextField.x = 10; + myTextField.y = 10; + myTextField.background = true; + myTextField.wordWrap = false; + myTextField.autoSize = TextFieldAutoSize.LEFT; + + myTextField.appendText("A child said What is the grass? fetching it to me with full hands;\n"); + myTextField.appendText("How could I answer the child? I do not know what it is any more than he.\n\n"); + + newFormat.size = 14; + newFormat.font = "Arial"; + newFormat.italic = true; + myTextField.setTextFormat(newFormat, 67, 139); + + var metrics1:TextLineMetrics = myTextField.getLineMetrics(0); + + myTextField.appendText("Metrics ascent for the line 1 is: " + metrics1.ascent.toString() + "\n"); + myTextField.appendText("Metrics descent is: " + metrics1.descent.toString() + "\n"); + myTextField.appendText("Metrics height is: " + metrics1.height.toString() + "\n"); + myTextField.appendText("Metrics width is: " + metrics1.width.toString() + "\n\n"); + + var metrics2:TextLineMetrics = myTextField.getLineMetrics(1); + + myTextField.appendText("Metrics ascent for the line 2 is: " + metrics2.ascent.toString() + "\n"); + myTextField.appendText("Metrics descent is: " + metrics2.descent.toString() + "\n"); + myTextField.appendText("Metrics height is: " + metrics2.height.toString() + "\n"); + myTextField.appendText("Metrics width is: " + metrics2.width.toString() + "\n"); + + addChild(myTextField); + } + } +} +
flash.text.TextLineMetricsflash.text.TextLineMetrics
getLineOffset + Returns the character index of the first character in the line that + the lineIndex parameter specifies.The line number specified is out of range. + + RangeErrorRangeErrorThe zero-based index value of the first character in the line. + + intlineIndexintThe zero-based index value of the line (for example, the first line is 0, + the second line is 1, and so on). + + The zero-based index value of the first character in the line. + + + Returns the character index of the first character in the line that + the lineIndex parameter specifies. + + The following example checks for the first character of the line 4, which + will change if the screen (and the text field) is resized. + +

The myTextField text field is set to word wrap. The countField + text field will display the first character of line 4. When the user clicks on the myTextField + text field, the clickHandler() method is invoked.

+ +

In the clickHandler() method, the getLineOffset() method returns + the index of the first character in the line index 3, which is the fourth line of the text. + (First line has a 0 index.) The charAt() method is used to get the character + using the index of the first character of the fourth line. The countField text field + content is updated with this information using the text property of the + countField text field. Using the countField.text property means that + each time after the click the content of the countField text field will be overwritten. + If the user resizes the display, the content will wrap and the first character of the line 4 could + change. By clicking again on the myTextField field, the content of countField + text field is updated with the new first character for the fourth line.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.MouseEvent; + + public class TextField_getLineOffsetExample extends Sprite { + private var myTextField:TextField = new TextField(); + private var countField:TextField = new TextField(); + + public function TextField_getLineOffsetExample() { + myTextField.x = 10; + myTextField.y = 10; + myTextField.width = 150; + myTextField.height = 300; + myTextField.background = true; + myTextField.border = true; + myTextField.wordWrap = true; + + countField.height = 20; + countField.width = 200; + countField.x = 10; + countField.y = 320; + countField.selectable = false; + + myTextField.appendText("The TextField class is used to create display objects for " + + "text display and input. All dynamic and input text fields in a SWF file " + + "are instances of the TextField class. You can use the TextField class " + + "to perform low-level text rendering. However, in Flex, you typically use " + + "the Label, Text, TextArea, and TextInput controls to process text. " + + "You can give a text field an instance name in the Property inspector " + + "and use the methods and properties of the TextField class to manipulate it with ActionScript."); + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + this.addChild(myTextField); + this.addChild(countField); + } + + private function clickHandler(e:MouseEvent):void { + var c:String; + var index:int; + + index = myTextField.getLineOffset(3); + c = myTextField.text.charAt(index); + countField.text = "The first character of line 4 is: " + c; + } + } +} +
getLineText + Returns the text of the line specified by the lineIndex parameter.The line number specified is out of range. + + RangeErrorRangeErrorThe text string contained in the specified line. + + StringlineIndexintThe zero-based index value of the line (for example, the first line is 0, + the second line is 1, and so on). + + The text string contained in the specified line. + + + Returns the text of the line specified by the lineIndex parameter. + + In the following example, the line numbers of all the instances of the word "love" used in Shakespeare's + sonnet are found and displayed. + +

The poem text field is set to fit automatically the text and to resize as a left-justified text. + The wordWrap property is set to false, so the lines of the poem would not wrap, though + normally when using the autoSize property, this should not be a problem. The for loop iterates through the lines + of the sonnet using the property numLines of the text field. The getLineText() method + returns the content of the line as a string. (Note that the numLines property returns the number + of lines starting with line 1, while for the getLineText() method the line number begins with 0.) + Using the regular expression pattern (/love/i), the if statement looks for any substring + of the word in upper or lowercase. If the pattern is found, the search method returns the index of + the first matching substring, otherwise it returns -1 (if there is no match). The line number where + "love" was found ((i + 1)) is then placed in the string lineResult. The string method converts + the number argument ((i + 1)) to a string as long as there is another argument that is a string (" "). + The line result of the search will include lines with the words "loved" or "Love's." If the string "Love was found in lines:" + was appended before the for loop, the word "Love" in this line would also have been included.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.utils.Timer; + import flash.events.TimerEvent; + + public class TextField_getLineTextExample extends Sprite { + + public function TextField_getLineTextExample() { + var poem:TextField = new TextField(); + var lineResult:String = ""; + var pattern:RegExp = /love/i; + + poem.x = 10; + poem.y = 10; + poem.background = true; + poem.wordWrap = false; + poem.autoSize = TextFieldAutoSize.LEFT; + + poem.text = "Let me not to the marriage of true minds\n" + + "Admit impediments. love is not love\n" + + "Which alters when it alteration finds\n" + + "Or bends with the remover to remove:\n" + + "O no! it is an ever-fixed mark\n" + + "That looks on tempests and is never shaken;\n" + + "It is the star to every wandering bark,\n" + + "Whose worth's unknown, although his height be taken.\n" + + "Love's not Time's fool, though rosy lips and cheeks\n" + + "Within his bending sickle's compass come:\n" + + "Love alters not with his brief hours and weeks,\n" + + "But bears it out even to the edge of doom.\n" + + "If this be error and upon me proved,\n" + + "I never writ, nor no man ever loved.\n\n"; + + for (var i:int = 0; i < poem.numLines; i++) { + + var s:String = poem.getLineText(i); + + if(s.search(pattern) != -1) { + lineResult += (i + 1) + " "; + } + } + + poem.appendText("Love was found in lines: " + lineResult); + + this.addChild(poem); + } + } +} +
getParagraphLength + Given a character index, returns the length of the paragraph containing the given character.The character index specified is out of range. + RangeErrorRangeErrorReturns the number of characters in the paragraph. + + intcharIndexintThe zero-based index value of the character (for example, the first character is 0, + the second character is 1, and so on). + + The zero-based index value of the character. + + + Given a character index, returns the length of the paragraph containing the given character. + The length is relative to the first character in the paragraph (as returned by + getFirstCharInParagraph()), not to the character index passed in. + + In the following example, when a user selects a paragraph, the paragraph's length and number + of "s" characters in the paragraph are displayed in a separate text field. + +

The myTextField text field displays the paragraphs that the user will select. + When the user click on the text field, the MouseEvent.CLICK event is dispatched, and + the clickHandler() method is called. The paragraph length and number of "s" characters + will appear in countField text field, which is placed below myTextField text field.

+ +

In the clickHandler() method, the getCharIndexAtPoint() method returns the character's + index based on the localX and localY coordinates of the mouse click. The first if + statement checks to see if the use has clicked on a character. The getFirstCharInParagraph() method, + uses this index to return the index of the first character in the same paragraph. The paragraph length returned by + getParagraphLength() method is used with the index of the first character in the paragraph to determine the + index for the end of the paragraph. A for loop iterates through the paragraph looking for the number of "s" + characters.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.MouseEvent; + + public class TextField_getParagraphLengthExample extends Sprite { + private var myTextField:TextField = new TextField(); + private var countField:TextField = new TextField(); + + public function TextField_getParagraphLengthExample() { + myTextField.x = 10; + myTextField.y = 10; + myTextField.background = true; + myTextField.border = true; + myTextField.wordWrap = true; + myTextField.width = 300; + myTextField.height = 280; + + myTextField.appendText("The TextField class is used to create display objects for " + + "text display and input. All dynamic and input text fields in a SWF file" + + "are instances of the TextField class. You can use the TextField class " + + "to perform low-level text rendering. However, in Flex, you typically use " + + "the Label, Text, TextArea, and TextInput controls to process text. " + + "You can give a text field an instance name in the Property inspector " + + "and use the methods and properties of the TextField class to manipulate it with ActionScript. " + + "TextField instance names are displayed in the Movie Explorer and in the Insert " + + "Target Path dialog box in the Actions panel.\n\n" + + "To create a text field dynamically, use the TextField() constructor.\n\n" + + "The methods of the TextField class let you set, select, and manipulate " + + "text in a dynamic or input text field that you create during authoring or at runtime."); + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + countField.x = 10; + countField.y = 300; + countField.height = 50; + countField.width = 250; + countField.background = true; + countField.selectable = false; + + this.addChild(myTextField); + this.addChild(countField); + } + + private function clickHandler(e:MouseEvent):void { + var index:int = myTextField.getCharIndexAtPoint(e.localX, e.localY); + + if(index != -1) { + var beginParag:int = myTextField.getFirstCharInParagraph(index); + var paragLength:int = myTextField.getParagraphLength(index); + var endParag:int = beginParag + paragLength; + var sCount:uint = 0; + + for (var i:int = beginParag; i <= endParag; i++) { + if ((myTextField.text.charAt(i) == "s") || (myTextField.text.charAt(i) == "S")) { + sCount++; + } + + countField.text = "Paragraph length is: " + paragLength.toString() + "\n" + + "Number of 's' characters in the paragraph: " + sCount.toString(); + } + } + } + } +} +
flash.text.TextField.getFirstCharInParagraph()
getTextFormat + Returns a TextFormat object that contains formatting information for the range of text that the + beginIndex and endIndex parameters specify.The beginIndex or endIndex specified is out of range. + + RangeErrorRangeErrorThe TextFormat object that represents the formatting properties for the specified text. + + flash.text:TextFormatbeginIndexint-1Optional; an integer that specifies the starting location of a range of text within the text field. + + endIndexint-1Optional; an integer that specifies the position of the first character after the desired + text span. As designed, if you specify beginIndex and endIndex values, + the text from beginIndex to endIndex-1 is read. + + Returns a TextFormat object. + + + Returns a TextFormat object that contains formatting information for the range of text that the + beginIndex and endIndex parameters specify. Only properties + that are common to the entire text specified are set in the resulting TextFormat object. + Any property that is mixed, meaning that it has different values + at different points in the text, has a value of null. + +

If you do not specify + values for these parameters, this method is applied to all the text in the text field.

+ +

The following table describes three possible usages:

+ + UsageDescriptionmy_textField.getTextFormat()Returns a TextFormat object containing formatting information for all text in a text field. + Only properties that are common to all text in the text field are set in the resulting TextFormat + object. Any property that is mixed, meaning that it has different values at different + points in the text, has a value of null.my_textField.getTextFormat(beginIndex:Number)Returns a TextFormat object containing a copy of the text format of the character at the + beginIndex position.my_textField.getTextFormat(beginIndex:Number,endIndex:Number)Returns a TextFormat object containing formatting information for the span of + text from beginIndex to endIndex-1. Only properties that are common + to all of the text in the specified range are set in the resulting TextFormat object. Any property + that is mixed (that is, has different values at different points in the range) has its value set to null. + +
Please see the getFirstCharInParagraph() or + setTextFormat() method example for illustrations of how + to use the getTextFormat() method. + +
flash.text.TextFormatflash.text.TextField.defaultTextFormatflash.text.TextField.setTextFormat()
isFontCompatible + Returns true if an embedded font is available with the specified fontName and fontStyle + where Font.fontType is flash.text.FontType.EMBEDDED.The fontStyle specified is not a member of flash.text.FontStyle. + + ArgumentErrorArgumentErrortrue if a compatible embedded font is available, otherwise false. + + BooleanfontNameStringThe name of the embedded font to check. + fontStyleStringSpecifies the font style to check. Use flash.text.FontStyle + + Returns true if an embedded font is available with the specified fontName and fontStyle + where Font.fontType is flash.text.FontType.EMBEDDED. Starting with Flash Player 10, + two kinds of embedded fonts can appear in a SWF file. Normal embedded fonts are only used with + TextField objects. + CFF embedded fonts are only used with the flash.text.engine classes. The two types are distinguished by the + fontType property of the Font class, as returned by the enumerateFonts() function. + +

TextField cannot use a font of type EMBEDDED_CFF. If embedFonts is set to true + and the only font available at run time with the specified name and style is of type EMBEDDED_CFF, + Flash Player fails to render the text, as if no embedded font were available with the specified name and style.

+ +

If both EMBEDDED and EMBEDDED_CFF fonts are available with the same name and style, the EMBEDDED + font is selected and text renders with the EMBEDDED font.

+ +
flash.text.engine.FontDescription.fontLookupflash.text.engine.TextBlock.createTextLine()flash.text.FontType.EMBEDDED_CFF
replaceSelectedText + Replaces the current selection with the contents of the value parameter.This method cannot be used on a text field with a style sheet. + + ErrorErrorvalueStringThe string to replace the currently selected text. + + Replaces the current selection with the contents of the value parameter. + + + Replaces the current selection with the contents of the value parameter. + The text is inserted at the position of the current selection, using the current default character + format and default paragraph format. The text is not treated as HTML. + +

You can use the replaceSelectedText() method to insert and delete text without disrupting + the character and paragraph formatting of the rest of the text.

+

Note: This method does not work if a style sheet is applied to the text field.

+ + +
In the following example, the user erases some text from the first text field + by selecting it and replaces a selected text in the second text field with "NEW TEXT" string. + +

Two different TextField objects are created and event listeners are added for the + MouseEvent.MOUSE_UP events. Mouse up occurs when the user releases the mouse, + an event that normally happens after a selection of text is made. Note that the default + setting for a text field is for its text to be selected.

+ +

In the mouseHandler1() method, when a user release a mouse in the + myTextField1 text field, the text is erased by replacing it with an empty + string. This can continue until all the text is erased. In the mouseHandler2() + method, when a user selects some text in myTextField2 text field, properties + selectionBeginIndex and selectionEndIndex are checked to see if + any character was selected. (The selectionBeginIndex and selectionEndIndex + properties don't have the same value if some text were selected.) The selected text is then replaced + with "NEW TEXT" string. This can continue until all the original text of the second text field is + replaced with the "NEW TEXT" string.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.events.MouseEvent; + + public class TextField_replaceSelectedTextExample extends Sprite { + private var myTextField1:TextField = new TextField(); + private var myTextField2:TextField = new TextField(); + + public function TextField_replaceSelectedTextExample() { + myTextField1.x = 10; + myTextField1.width = 300; + myTextField1.height = 50; + myTextField1.background = true; + myTextField1.border = true; + myTextField1.text = "Select the text you want to remove from the line."; + + myTextField2.x = 10; + myTextField2.y = 60; + myTextField2.width = 300; + myTextField2.height = 50; + myTextField2.background = true; + myTextField2.border = true; + myTextField2.text = "Select the text you want to replace with NEW TEXT."; + + myTextField1.addEventListener(MouseEvent.MOUSE_UP, mouseHandler1); + myTextField2.addEventListener(MouseEvent.MOUSE_UP, mouseHandler2); + + this.addChild(myTextField1); + this.addChild(myTextField2); + } + + private function mouseHandler1(e:MouseEvent):void { + myTextField1.replaceSelectedText(""); + } + + private function mouseHandler2(e:MouseEvent):void { + if(myTextField2.selectionBeginIndex != myTextField2.selectionEndIndex) { + myTextField2.replaceSelectedText("NEW TEXT"); + } + } + } +} +
flash.display.Stage.focus
replaceText + Replaces the range of characters that the beginIndex and + endIndex parameters specify with the contents + of the newText parameter.This method cannot be used on a text field with a style sheet. + + ErrorErrorbeginIndexintThe zero-based index value for the start position of the replacement range. + endIndexintThe zero-based index position of the first character after the desired + text span. + newTextStringThe text to use to replace the specified range of characters. + + Replaces a range of characters. + + + Replaces the range of characters that the beginIndex and + endIndex parameters specify with the contents + of the newText parameter. As designed, the text from + beginIndex to endIndex-1 is replaced. +

Note: This method does not work if a style sheet is applied to the text field.

+ +
The following example uses the replaceText() method to delete, replace and insert + some text into a text field. + +

The outputText text field is set to automatically fit the text and to resize as a left-justified text. + With the first replaceText() method call, the first line ("This is the wrong heading") + is replaced with "THIS IS THE HEADING FOR EVERYONE." With the second method call, the text "CORRECT" + is inserted between "THE" and "HEADING." With the third method call, the words "FOR EVERYONE" are deleted. + Note that with each call to the method appendText(), the current text's begin and end index + are changed. Here, only the final text (after the changes have been made) will display.

+ +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class TextField_replaceTextExample extends Sprite { + + public function TextField_replaceTextExample() { + var outputText:TextField = new TextField(); + + outputText.x = 10; + outputText.y = 10; + outputText.background = true; + outputText.autoSize = TextFieldAutoSize.LEFT; + + outputText.appendText("This is the wrong heading"); + outputText.appendText("\n\n"); + outputText.appendText("This is the body of the text."); + + outputText.replaceText(0, 25, "THIS IS THE HEADING FOR EVERYONE"); + + outputText.replaceText(12, 12, "CORRECT "); + + outputText.replaceText(27, 40, ""); + + this.addChild(outputText); + } + } +} +
setSelection + Sets as selected the text designated by the index values of the + first and last characters, which are specified with the beginIndex + and endIndex parameters.beginIndexintThe zero-based index value of the first character in the selection + (for example, the first character is 0, the second character is 1, and so on). + + endIndexintThe zero-based index value of the last character in the selection. + + Sets a new text selection. + + + Sets as selected the text designated by the index values of the + first and last characters, which are specified with the beginIndex + and endIndex parameters. If the two parameter values are the same, + this method sets the insertion point, as if you set the + caretIndex property. + + In the following example, when the user clicks anywhere in the text field a predefined range + of text will be selected (highlighting the words "TEXT IN ALL CAPS"). + +

Two event listeners for the myTextField text field respond to the user's mouse clicks or mouse up events. + Mouse up will occur when the user releases the mouse, an event that normally happens after a selection of text is made. + Note that the default setting for a text field is for its text to be selected. When some text is clicked, + clickHandler() method is invoked. When some text is selected and the mouse is released, + mouseUpHandler() method is invoked.

+ +

In both clickHandler() and mouseUpHandler() methods, the setSelection() method + sets only the characters between indexes 54 and 70 (TEXT IN ALL CAPS) to be selected.

+ +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class TextField_setSelectionExample extends Sprite + { + private var myTextField:TextField = new TextField(); + + public function TextField_setSelectionExample() { + myTextField.autoSize = TextFieldAutoSize.LEFT; + myTextField.text = "No matter where you click on this text field only the TEXT IN ALL CAPS is selected."; + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + myTextField.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler); + + this.addChild(myTextField); + } + + private function clickHandler(event:MouseEvent):void { + myTextField.setSelection(54, 70); + } + + private function mouseUpHandler(event:MouseEvent):void { + myTextField.setSelection(54, 70); + } + + } +} +
selectableselectionBeginIndexselectionEndIndexcaretIndex
setTextFormat + Applies the text formatting that the format parameter specifies to the specified text in a text field.This method cannot be used on a text field with a style sheet. + ErrorErrorThe beginIndex or endIndex specified is out of range. + + RangeErrorRangeErrorformatflash.text:TextFormatA TextFormat object that contains character and paragraph formatting information. + + beginIndexint-1Optional; an integer that specifies the zero-based index position specifying the + first character of the desired range of text. + + endIndexint-1Optional; an integer that specifies the first character after the desired text span. + As designed, if you specify beginIndex and endIndex values, + the text from beginIndex to endIndex-1 is updated. + +

+ UsageDescriptionmy_textField.setTextFormat(textFormat:TextFormat)Applies the properties of textFormat to all text in the text + field.my_textField.setTextFormat(textFormat:TextFormat, beginIndex:int)Applies the properties of textFormat to the text starting with the + beginIndex position.my_textField.setTextFormat(textFormat:TextFormat, beginIndex:int, + endIndex:int)Applies the properties of the textFormat parameter to the span of + text from the beginIndex position to the endIndex-1 position. +

+ +

Notice that any text inserted manually by the user, or replaced by the + replaceSelectedText() method, receives the default text field formatting for new + text, and not the formatting specified for the text insertion point. To set a text field's + default formatting for new text, use the defaultTextFormat property.

+ + +
Applies text formatting. + +
+ Applies the text formatting that the format parameter specifies to the specified text in a text field. + The value of format must be a TextFormat object that specifies the + desired text formatting changes. Only the non-null properties of format are applied + to the text field. Any property of format that is set to null is not + applied. By default, all of the properties of a newly created TextFormat object are set to null. +

Note: This method does not work if a style sheet is applied to the text field.

+ +

The setTextFormat() method changes the text formatting applied to a range of + characters or to the entire body of text in a text field. To apply the properties of format to all text in the text + field, do not specify values for beginIndex and endIndex. To apply the + properties of the format to a range of text, specify values for the beginIndex and + the endIndex parameters. You can use the length property to determine + the index values.

+ +

The two types of formatting information in a TextFormat object are + character level formatting and paragraph level formatting. + Each character in a text field can have its own character formatting + settings, such as font name, font size, bold, and italic.

+ +

For paragraphs, the first character of the paragraph is examined for the paragraph formatting + settings for the entire paragraph. Examples of paragraph formatting settings are left margin, + right margin, and indentation.

+ +

Any text inserted manually by the user, or replaced by the + replaceSelectedText() method, receives the default text field formatting for new text, + and not the formatting specified for the text insertion point. To set the default + formatting for new text, use defaultTextFormat.

+ +
In the following example, when the text is clicked, a defined range of text, "TEXT IN ALL CAPS," switches + format between the default text format and the new format. + +

An event listener for the myTextField text field is added to respond to the mouse clicks by invoking + the clickHandler() method. In the clickHandler() method, the getTextFormat() + method returns the current format of a character (index 55) from the intended range of the text, which is then placed + in the currentTextFormat TextFormat object. The if statement checks the currentTextFormat + text format to see if the character in the range is using the new format (font point is set to 18). If not, the new format changes + the size to 18 point, color to red, and applies underline and italics to the range of text between 54-70 (TEXT IN ALL CAPS). + If the character in the range is using the new format, the format of the range is set back to the default (original) + format of the text field.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.text.TextFieldAutoSize; + import flash.events.MouseEvent; + + public class TextField_setTextFormatExample extends Sprite { + private var myTextField:TextField = new TextField(); + private var newFormat:TextFormat = new TextFormat(); + + public function TextField_setTextFormatExample() { + myTextField.autoSize = TextFieldAutoSize.LEFT; + myTextField.selectable = false; + myTextField.background = true; + myTextField.text = "No matter where you click on this text field only the TEXT IN ALL CAPS changes format."; + + myTextField.addEventListener(MouseEvent.CLICK, clickHandler); + + newFormat.color = 0xFF0000; + newFormat.size = 18; + newFormat.underline = true; + newFormat.italic = true; + + this.addChild(myTextField); + } + + private function clickHandler(event:MouseEvent):void { + var currentTextFormat:TextFormat = myTextField.getTextFormat(55); + + if(currentTextFormat.size != 18) { + myTextField.setTextFormat(newFormat, 54, 70); + } + else { + myTextField.setTextFormat(myTextField.defaultTextFormat); + } + } + } +} +
flash.text.TextFormatflash.text.TextField.defaultTextFormat
alwaysShowSelection + When set to true and the text field is not in focus, Flash Player highlights the + selection in the text field in gray.Booleanfalse + + + When set to true and the text field is not in focus, Flash Player highlights the + selection in the text field in gray. When set to false and the text field is not in + focus, Flash Player does not highlight the selection in the text field. + + Compile and run the following file. When you run the file, drag to select text + in each of the two text fields, and notice the difference in selection highlighting when you + select text in the two text fields (changing focus): + + + package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + + public class TextField_alwaysShowSelection extends Sprite { + public function TextField_alwaysShowSelection() { + var label1:TextField = createCustomTextField(0, 20, 200, 20); + label1.text = "This text is selected."; + label1.setSelection(0, 9); + label1.alwaysShowSelection = true; + + var label2:TextField = createCustomTextField(0, 50, 200, 20); + label2.text = "Drag to select some of this text."; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; result.y = y; + result.width = width; result.height = height; + addChild(result); + return result; + } + } +} +flash.display.Stage.focusantiAliasType + The type of anti-aliasing used for this text field.StringThe type of anti-aliasing used. + + + The type of anti-aliasing used for this text field. Use flash.text.AntiAliasType + constants for this property. You can control this setting only if the font is + embedded (with the embedFonts property set to true). + The default setting is flash.text.AntiAliasType.NORMAL. + +

To set values for this property, use the following string values:

+ + String valueDescriptionflash.text.AntiAliasType.NORMALApplies the regular text anti-aliasing. This value matches the type of anti-aliasing that + Flash Player 7 and earlier versions used.flash.text.AntiAliasType.ADVANCEDApplies advanced anti-aliasing, which makes text more legible. (This feature became + available in Flash Player 8.) Advanced anti-aliasing allows for high-quality rendering + of font faces at small sizes. It is best used with applications + with a lot of small text. Advanced anti-aliasing is not recommended for + fonts that are larger than 48 points. + +
flash.text.AntiAliasTypeflash.text.TextField.embedFonts
autoSize + Controls automatic sizing and alignment of text fields.StringThe autoSize specified is not a member of flash.text.TextFieldAutoSize. + + ArgumentErrorArgumentErrorControls automatic sizing and alignment of text fields. + + + Controls automatic sizing and alignment of text fields. + Acceptable values for the TextFieldAutoSize constants: TextFieldAutoSize.NONE (the default), + TextFieldAutoSize.LEFT, TextFieldAutoSize.RIGHT, and TextFieldAutoSize.CENTER. + +

If autoSize is set to TextFieldAutoSize.NONE (the default) no resizing occurs.

+ +

If autoSize is set to TextFieldAutoSize.LEFT, the text is + treated as left-justified text, meaning that the left margin of the text field remains fixed and any + resizing of a single line of the text field is on the right margin. If the text includes a line break + (for example, "\n" or "\r"), the bottom is also resized to fit the next + line of text. If wordWrap is also set to true, only the bottom + of the text field is resized and the right side remains fixed.

+ +

If autoSize is set to TextFieldAutoSize.RIGHT, the text is treated as + right-justified text, meaning that the right margin of the text field remains fixed and any resizing + of a single line of the text field is on the left margin. If the text includes a line break + (for example, "\n" or "\r"), the bottom is also resized to fit the next + line of text. If wordWrap is also set to true, only the bottom + of the text field is resized and the left side remains fixed.

+ +

If autoSize is set to TextFieldAutoSize.CENTER, the text is treated as + center-justified text, meaning that any resizing of a single line of the text field is equally distributed + to both the right and left margins. If the text includes a line break (for example, "\n" or + "\r"), the bottom is also resized to fit the next line of text. If wordWrap is also + set to true, only the bottom of the text field is resized and the left and + right sides remain fixed.

+ +
flash.text.TextFieldAutoSizeflash.text.TextField.autoSizeflash.text.TextField.wordWrap
backgroundColor + The color of the text field background.uint + The color of the text field background. The default value is 0xFFFFFF (white). + This property can be retrieved or set, even if there currently is no background, but the + color is visible only if the text field has the background property set to + true. + + flash.text.TextField.backgroundbackground + Specifies whether the text field has a background fill.Booleanfalse + + + Specifies whether the text field has a background fill. If true, the text field has a + background fill. If false, the text field has no background fill. + Use the backgroundColor property to set the background color of a text field. + + flash.text.TextField.backgroundColorborderColor + The color of the text field border.uint + The color of the text field border. The default value is 0x000000 (black). + This property can be retrieved or set, even if there currently is no border, but the + color is visible only if the text field has the border property set to + true. + + flash.text.TextField.borderborder + Specifies whether the text field has a border.Booleanfalse + + + Specifies whether the text field has a border. If true, the text field has a border. + If false, the text field has no border. Use the borderColor property + to set the border color. + + flash.text.TextField.borderColorbottomScrollV + An integer (1-based index) that indicates the bottommost line that is currently visible in + the specified text field.intAn integer that indicates the bottommost line in a text field. + + + An integer (1-based index) that indicates the bottommost line that is currently visible in + the specified text field. Think of the text field as a window onto a block of text. + The scrollV property is the 1-based index of the topmost visible line + in the window. + +

All the text between the lines indicated by scrollV and bottomScrollV + is currently visible in the text field.

+ +
flash.text.TextField.scrollV
caretIndex + The index of the insertion point (caret) position.intReturns the zero-based index value of the blinking insertion point. + + + The index of the insertion point (caret) position. If no insertion point is displayed, + the value is the position the insertion point would be if you restored focus to the field (typically where the + insertion point last was, or 0 if the field has not had focus). + +

Selection span indexes are zero-based (for example, the first position is 0, + the second position is 1, and so on).

+ + +
In this example, a TextField instance is created and populated with text. + An event listener is assigned so that when the user clicks on the TextField, the + printCursorPosition method is called. In that case, the values of the + caretIndex, selectionBeginIndex, and + selectionEndIndex properties are output. + +

Run this example and try clicking in the TextField to select text. Then click in the field without + selecting text. When you click in the text without making a selection, the + caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex + and selectionEndIndex properties equal the caretIndex property value.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldType; + + public class TextField_caretIndex extends Sprite { + public function TextField_caretIndex() { + var tf:TextField = createCustomTextField(10, 10, 100, 100); + tf.wordWrap = true; + tf.type = TextFieldType.INPUT; + tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text."; + tf.addEventListener(MouseEvent.CLICK, printCursorPosition); + } + + private function printCursorPosition(event:MouseEvent):void { + var tf:TextField = TextField(event.target); + trace("caretIndex:", tf.caretIndex); + trace("selectionBeginIndex:", tf.selectionBeginIndex); + trace("selectionEndIndex:", tf.selectionEndIndex); + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +
selectableselectionBeginIndexselectionEndIndex
condenseWhite + A Boolean value that specifies whether extra white space (spaces, line breaks, and so on) + in a text field with HTML text is removed.BooleanA Boolean value that specifies whether extra white space is removed in a text field + with HTML text. + + + A Boolean value that specifies whether extra white space (spaces, line breaks, and so on) + in a text field with HTML text is removed. The default value is false. + The condenseWhite property only affects text set with + the htmlText property, not the text property. If you set + text with the text property, condenseWhite is ignored. + +

If condenseWhite is set to true, use standard HTML commands such as + <BR> and <P> to place line breaks in the text field.

+ +

Set the condenseWhite property before setting the htmlText property.

+ + +
The following shows the difference between setting the condenseWhite + setting to false and setting it to true: + + +package { + import flash.display.Sprite; + import flash.text.TextField; + + public class TextField_condenseWhite extends Sprite { + public function TextField_condenseWhite() { + var tf1:TextField = createCustomTextField(0, 0, 200, 50); + tf1.condenseWhite = false; + tf1.htmlText = "keep on\n\ttruckin'"; + + var tf2:TextField = createCustomTextField(0, 120, 200, 50); + tf2.condenseWhite = true; + tf2.htmlText = "keep on\n\ttruckin'"; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.border = true; + addChild(result); + return result; + } + } +} +
flash.text.TextField.htmlText
defaultTextFormat + Specifies the format applied to newly inserted text, such as text entered by a user or text inserted with the + replaceSelectedText() method.flash.text:TextFormatThis method cannot be used on a text field with a style sheet. + + ErrorErrorSpecifies the text format for newly inserted text. + + + Specifies the format applied to newly inserted text, such as text entered by a user or text inserted with the + replaceSelectedText() method. + +

Note: When selecting characters to be replaced with setSelection() and + replaceSelectedText(), the defaultTextFormat will be applied only if the + text has been selected up to and including the last character. Here is an example:

+
+     var my_txt:TextField new TextField();
+     my_txt.text = "Flash Macintosh version";
+     var my_fmt:TextFormat = new TextFormat();
+     my_fmt.color = 0xFF0000;
+     my_txt.defaultTextFormat = my_fmt;
+     my_txt.setSelection(6,15); // partial text selected - defaultTextFormat not applied
+     my_txt.setSelection(6,23); // text selected to end - defaultTextFormat applied
+     my_txt.replaceSelectedText("Windows version");
+     
+ +

When you access the defaultTextFormat property, the returned TextFormat object has all + of its properties defined. No property is null.

+

Note: You can't set this property if a style sheet is applied to the text field.

+ +
flash.text.TextField.replaceSelectedText()flash.text.TextField.getTextFormat()flash.text.TextField.setTextFormat()
displayAsPassword + Specifies whether the text field is a password text field.Booleanfalse + + Specifies whether input characters are hidden. + + + Specifies whether the text field is a password text field. If the value of this property is true, + the text field is treated as a password text field and hides the input characters using asterisks instead of the + actual characters. If false, the text field is not treated as a password text field. When password mode + is enabled, the Cut and Copy commands and their corresponding keyboard shortcuts will + not function. This security mechanism prevents an unscrupulous user from using the shortcuts to discover + a password on an unattended computer. + + embedFonts + Specifies whether to render by using embedded font outlines.Booleanfalse + + Renders the text field with font outlines or device fonts. + + + Specifies whether to render by using embedded font outlines. + If false, Flash Player renders the text field by using + device fonts. + +

If you set the embedFonts property to true for a text field, + you must specify a font for that text by using the font property of + a TextFormat object applied to the text field. + If the specified font is not embedded in the SWF file, the text is not displayed.

+ +
Font.enumerateFonts()
gridFitType + The type of grid fitting used for this text field.Stringpixel + + The type of grid fitting used. + + + The type of grid fitting used for this text field. This property applies only if the + flash.text.AntiAliasType property of the text field is set to flash.text.AntiAliasType.ADVANCED. + +

The type of grid fitting used determines whether Flash Player forces strong horizontal and + vertical lines to fit to a pixel or subpixel grid, or not at all.

+ +

For the flash.text.GridFitType property, you can use the following string values:

+ + String valueDescriptionflash.text.GridFitType.NONESpecifies no grid fitting. Horizontal and vertical lines in the glyphs are not + forced to the pixel grid. This setting is recommended for animation or + for large font sizes.flash.text.GridFitType.PIXELSpecifies that strong horizontal and vertical lines are fit to the + pixel grid. This setting works only for left-aligned text fields. + To use this setting, the flash.dispaly.AntiAliasType property of the text field + must be set to flash.text.AntiAliasType.ADVANCED. + This setting generally provides the best legibility for + left-aligned text.flash.text.GridFitType.SUBPIXELSpecifies that strong horizontal and vertical lines are fit to the subpixel grid on + an LCD monitor. To use this setting, the + flash.text.AntiAliasType property of the text field must be set to + flash.text.AntiAliasType.ADVANCED. The flash.text.GridFitType.SUBPIXEL setting is often good + for right-aligned or centered + dynamic text, and it is sometimes a useful trade-off for animation versus text quality. + +
The following example shows three text fields with different + settings for the gridFitType property. When you use this example, + notice the difference in legibility for the first two lines. Also note the optimal use of + GridFitType.PIXEL for left-aligned text and GridFitType.SUBPIXEL + for right-aligned text. + + +package +{ + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.text.TextFieldAutoSize; + import flash.text.AntiAliasType; + import flash.text.GridFitType; + + public class gridFitTypeExample extends Sprite + { + public function gridFitTypeExample() + { + var format1:TextFormat = new TextFormat(); + format1.font="Arial"; + format1.size=12; + + var tf1:TextField = createCustomTextField(0,0,format1,"NONE",TextFieldAutoSize.LEFT,GridFitType.NONE); + + var tf2:TextField = createCustomTextField(0,30,format1,"PIXEL",TextFieldAutoSize.LEFT,GridFitType.PIXEL); + + var tf3:TextField = createCustomTextField(300,60,format1,"SUBPIXEL",TextFieldAutoSize.RIGHT,GridFitType.SUBPIXEL); + + } + private function createCustomTextField(x:Number,y:Number,fm:TextFormat,tl:String,tfs:String,gft:String):TextField + { + var result:TextField = new TextField(); + result.x=x; + result.y=y; + result.embedFonts=true; + result.antiAliasType=AntiAliasType.ADVANCED; + result.text="This text uses a gridFitType of " + tl; + result.autoSize=tfs; + result.gridFitType=gft; + result.setTextFormat(fm); + addChild(result); + return result; + } + } +} +
flash.text.GridFitTypeflash.text.TextField.antiAliasTypeflash.text.AntiAliasType
htmlText + Contains the HTML representation of the text field contents.StringThe HTML representation of the text field contents. + + + Contains the HTML representation of the text field contents. + +

Flash Player supports the following HTML tags:

+ + + + Tag + + Description + + Anchor tag + + The <a> tag creates a hypertext link and supports the following attributes: +
  • + target: Specifies the name of the target window where you load the page. + Options include _self, _blank, _parent, and + _top. The _self option specifies the current frame in the current window, + _blank specifies a new window, _parent specifies the parent of the + current frame, and _top specifies the top-level frame in the current window. +
  • + href: Specifies a URL or an ActionScript link event.The URL can + be either absolute or relative to the location of the SWF file that + is loading the page. An example of an absolute reference to a URL is + http://www.adobe.com; an example of a relative reference is + /index.html. Absolute URLs must be prefixed with + http://; otherwise, Flash Player or AIR treats them as relative URLs. + + You can use the link event to cause the link to execute an ActionScript + function in a SWF file instead of opening a URL. To specify a link event, use + the event scheme instead of the http scheme in your href attribute. An example + is href="event:myText" instead of href="http://myURL"; when the + user clicks a hypertext link that contains the event scheme, the text field dispatches a + link TextEvent with its text property set to "myText". You can then create an ActionScript + function that executes whenever the link TextEvent is dispatched. + + You can also define a:link, a:hover, and a:active + styles for anchor tags by using style sheets. +
+ +
+ Bold tag + + The <b> tag renders text as bold. A bold typeface must be available for the font used. + + Break tag + + The <br> tag creates a line break in the text field. Set the text field to + be a multiline text field to use this tag. + + Font tag + + The <font> tag specifies a font or list of fonts to display the text.The font tag + supports the following attributes: +
  • + color: Only hexadecimal color (#FFFFFF) values are supported. +
  • + face: Specifies the name of the font to use. As shown in the following example, + you can specify a list of comma-delimited font names, in which case Flash Player selects the first available + font. If the specified font is not installed on the local computer system or isn't embedded in the SWF file, + Flash Player selects a substitute font. +
  • + size: Specifies the size of the font. You can use absolute pixel sizes, such as 16 or 18, + or relative point sizes, such as +2 or -4. +
+ +
+ Image tag + + The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and + movie clips inside text fields. Text automatically flows around images you embed in text fields. You + must set the text field to be multiline to wrap text around an image. + +

The <img> tag supports the following attributes:

+ +
  • + src: Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip + symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, + and SWF files) do not show until they are downloaded completely. +
  • + width: The width of the image, SWF file, or movie clip being inserted, in pixels. +
  • + height: The height of the image, SWF file, or movie clip being inserted, in pixels. +
  • + align: Specifies the horizontal alignment of the embedded image within the text field. + Valid values are left and right. The default value is left. +
  • + hspace: Specifies the amount of horizontal space that surrounds the image where + no text appears. The default value is 8. +
  • + vspace: Specifies the amount of vertical space that surrounds the image where no + text appears. The default value is 8. +
  • + id: Specifies the name for the movie clip instance (created by Flash Player) that contains + the embedded image file, SWF file, or movie clip. This approach is used to control the embedded content with + ActionScript. +
  • + checkPolicyFile: Specifies that Flash Player checks for a URL policy file + on the server associated with the image domain. If a policy file exists, SWF files in the domains + listed in the file can access the data of the loaded image, for example, by calling the + BitmapData.draw() method with this image as the source parameter. + For more information related to security, see the Flash Player Developer Center Topic: + Security. + +
+

Flash displays media embedded in a text field at full size. To specify the dimensions of the media + you are embedding, use the <img> tag height and width + attributes.

+ +

In general, an image embedded in a text field appears on the line following the + <img> tag. However, when the <img> tag + is the first character in the text field, the image appears on the first line of the text field.

+ +

For AIR content in the application security sandbox, AIR ignores img tags in + HTML content in ActionScript TextField objects. This is to prevent possible phishing attacks,

+ +
+ Italic tag + + The <i> tag displays the tagged text in italics. An italic typeface must be available + for the font used. + + List item tag + + The <li> tag places a bullet in front of the text that it encloses. + Note: Because Flash Player and AIR do not recognize ordered and unordered list tags (<ol> + and <ul>, they do not modify how your list is rendered. All lists are unordered and all + list items use bullets. + + Paragraph tag + + The <p> tag creates a new paragraph. The text field must be set to be a multiline + text field to use this tag. + + The <p> tag supports the following attributes: +
  • + align: Specifies alignment of text within the paragraph; valid values are left, right, justify, and center. +
  • + class: Specifies a CSS style class defined by a flash.text.StyleSheet object. +
+ +
+ Span tag + + + The <span> tag is available only for use with CSS text styles. It supports the + following attribute: + +
  • + class: Specifies a CSS style class defined by a flash.text.StyleSheet object. +
+ +
+ Text format tag + +

The <textformat> tag lets you use a subset of paragraph formatting + properties of the TextFormat class within text fields, including line leading, indentation, + margins, and tab stops. You can combine <textformat> tags with the + built-in HTML tags.

+ +

The <textformat> tag has the following attributes:

+
  • + blockindent: Specifies the block indentation in points; corresponds to + TextFormat.blockIndent. +
  • + indent: Specifies the indentation from the left margin to the first character + in the paragraph; corresponds to TextFormat.indent. Both positive and negative + numbers are acceptable. +
  • + leading: Specifies the amount of leading (vertical space) between lines; + corresponds to TextFormat.leading. Both positive and negative numbers are acceptable. +
  • + leftmargin: Specifies the left margin of the paragraph, in points; corresponds + to TextFormat.leftMargin. +
  • + rightmargin: Specifies the right margin of the paragraph, in points; corresponds + to TextFormat.rightMargin. +
  • + tabstops: Specifies custom tab stops as an array of non-negative integers; + corresponds to TextFormat.tabStops. +
+ +
+ Underline tag + + The <u> tag underlines the tagged text. +
+ +

Flash Player and AIR support the following HTML entities:

+ + + Entity + + Description + + + &amp;lt; + + + + < (less than) + + + + &amp;gt; + + + + > (greater than) + + + + &amp;amp; + + + + & (ampersand) + + + &amp;quot; + + + + " (double quotes) + + + + &amp;apos; + + + + ' (apostrophe, single quote) + + + +

Flash Player and AIR also support explicit character codes, such as + &#38; (ASCII ampersand) and &#x20AC; (Unicode € symbol).

+ +
The following example creates a TextField called tf1, and assigns an + HTML-formatted String to its text property. When its htmlText property + is traced, the output is the HTML-formatted String, with additional tags (such as <P> and + <FONT>) automatically added by Flash Player. When the value of the text + property is traced, the unformatted string without HTML tags is displayed. + +

By way of comparison, the same steps are performed on another TextField object named + tf2, with the addition that a StyleSheet object is assigned to tf2's + styleSheet property before its htmlText property is set. In that case, + when the htmlText property is traced, it only includes the exact HTML text that was + originally assigned to the htmlText property, showing that no additional tags were + added by Flash Player.

+ + +package { + import flash.display.Sprite; + import flash.text.StyleSheet; + import flash.text.TextField; + + public class TextField_text extends Sprite { + public function TextField_text() { + var tf1:TextField = createCustomTextField(10, 10, 400, 22); + tf1.htmlText = "<b>Lorem ipsum dolor sit amet.</b>"; + + // htmlText: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">&lt;b&gt;Lorem ipsum dolor sit amet.&lt;/b&gt;</FONT></P> + trace("htmlText: " + tf1.htmlText); + // text: Lorem ipsum dolor sit amet. + trace("text: " + tf1.text); + + var tf2:TextField = createCustomTextField(10, 50, 400, 22); + tf2.styleSheet = new StyleSheet(); + tf2.htmlText = "<b>Lorem ipsum dolor sit amet.</b>"; + // htmlText: <b>Lorem ipsum dolor sit amet.</b> + trace("htmlText: " + tf2.htmlText); + // text: Lorem ipsum dolor sit amet. + trace("text: " + tf2.text); + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +
flash.text.TextField.textflash.text.StyleSheetflash.events.TextEvent
length + The number of characters in a text field.intThe number of characters in a text field. + + + The number of characters in a text field. A character such as tab (\t) counts as one + character. + + maxChars + The maximum number of characters that the text field can contain, as entered by a user.int0 + + The maximum number of characters that the text field can contain. + + + The maximum number of characters that the text field can contain, as entered by a user. + A script can insert more text than maxChars allows; the maxChars property + indicates only how much text a user can enter. If the value of this property is 0, + a user can enter an unlimited amount of text. + + maxScrollH + The maximum value of scrollH.intThe maximum value of scrollH. + + + The maximum value of scrollH. + + flash.text.TextField.scrollHmaxScrollV + The maximum value of scrollV.intThe maximum value of scrollV. + + + The maximum value of scrollV. + + flash.text.TextField.scrollVmouseWheelEnabled + A Boolean value that indicates whether Flash Player automatically scrolls multiline + text fields when the user clicks a text field and rolls the mouse wheel.BooleanIndicates whether Flash Player automatically scrolls multiline text fields. + + + A Boolean value that indicates whether Flash Player automatically scrolls multiline + text fields when the user clicks a text field and rolls the mouse wheel. + By default, this value is true. This property is useful if you want to prevent + mouse wheel scrolling of text fields, or implement your own text field scrolling. + + multiline + Indicates whether field is a multiline text field.Booleanfalse + + Indicates whether the text field is a multiline text field. + + + Indicates whether field is a multiline text field. If the value is true, + the text field is multiline; if the value is false, the text field is a single-line + text field. In a field of type TextFieldType.INPUT, the multiline value + determines whether the Enter key creates a new line (a value of false, + and the Enter key is ignored). + If you paste text into a TextField with a multiline value of false, + newlines are stripped out of the text. + + + numLinesnumLines + Defines the number of text lines in a multiline text field.intDefines the number of text lines in a multiline text field. + + + Defines the number of text lines in a multiline text field. + If wordWrap property is set to true, + the number of lines increases when text wraps. + + multilinewordWraprestrict + Indicates the set of characters that a user can enter into the text field.Stringnull + + A set of characters that a user can enter into a text field. + + + + + Indicates the set of characters that a user can enter into the text field. If the value of the + restrict property is null, you can enter any character. If the value of + the restrict property is an empty string, you cannot enter any character. If the value + of the restrict property is a string of characters, you can enter only characters in + the string into the text field. The string is scanned from left to right. You can specify a range by + using the hyphen (-) character. Only user interaction is restricted; a script can put any text into the + text field. This property does not synchronize with the Embed font options + in the Property inspector. + +

If the string begins with a caret (^) character, all characters are initially accepted and + succeeding characters in the string are excluded from the set of accepted characters. If the string does + not begin with a caret (^) character, no characters are initially accepted and succeeding characters in the + string are included in the set of accepted characters.

+ +

The following example allows only uppercase characters, spaces, and numbers to be entered into + a text field:

+
+     my_txt.restrict = "A-Z 0-9";
+     
+

The following example includes all characters, but excludes lowercase letters:

+
+     my_txt.restrict = "^a-z";
+     
+

You can use a backslash to enter a ^ or - verbatim. The accepted backslash sequences are \-, \^ or \\. + The backslash must be an actual character in the string, so when specified in ActionScript, a double backslash + must be used. For example, the following code includes only the dash (-) and caret (^):

+
+     my_txt.restrict = "\\-\\^";
+     
+

The ^ can be used anywhere in the string to toggle between including characters and excluding characters. + The following code includes only uppercase letters, but excludes the uppercase letter Q:

+
+     my_txt.restrict = "A-Z^Q";
+     
+

You can use the \u escape sequence to construct restrict strings. + The following code includes only the characters from ASCII 32 (space) to ASCII 126 (tilde).

+
+     my_txt.restrict = "\u0020-\u007E";
+     
+ +
scrollH + The current horizontal scrolling position.intThe current horizontal scrolling position. + + + The current horizontal scrolling position. If the scrollH property is 0, the text + is not horizontally scrolled. This property value is an integer that represents the horizontal + position in pixels. + + +

The units of horizontal scrolling are pixels, whereas the units of vertical scrolling are lines. + Horizontal scrolling is measured in pixels because most fonts you typically use are proportionally + spaced; that is, the characters can have different widths. Flash Player performs vertical scrolling by + line because users usually want to see a complete line of text rather than a + partial line. Even if a line uses multiple fonts, the height of the line adjusts to fit + the largest font in use.

+ +

Note: The scrollH property is zero-based, not 1-based like + the scrollV vertical scrolling property.

+ +
flash.text.TextField.maxScrollHflash.text.TextField.scrollV
scrollV + The vertical position of text in a text field.intThe vertical position of text in a text field. + + + The vertical position of text in a text field. The scrollV property is useful for + directing users to a specific paragraph in a long passage, or creating scrolling text fields. + +

The units of vertical scrolling are lines, whereas the units of horizontal scrolling are pixels. + If the first line displayed is the first line in the text field, scrollV is set to 1 (not 0). + Horizontal scrolling is measured in pixels because most fonts are proportionally + spaced; that is, the characters can have different widths. Flash performs vertical scrolling by line + because users usually want to see a complete line of text rather than a partial line. + Even if there are multiple fonts on a line, the height of the line adjusts to fit the largest font in + use.

+ + +
flash.text.TextField.scrollHflash.text.TextField.maxScrollV
selectable + A Boolean value that indicates whether the text field is selectable.Booleantrue + + Indicates whether the text field is selectable. + + + A Boolean value that indicates whether the text field is selectable. The value true + indicates that the text is selectable. The selectable property controls whether + a text field is selectable, not whether a text field is editable. A dynamic text field can + be selectable even if it is not editable. If a dynamic text field is not selectable, the user + cannot select its text. + +

If selectable is set to false, the text in the text field does not + respond to selection commands from the mouse or keyboard, and the text cannot be copied with the + Copy command. If selectable is set to true, the text in the text field + can be selected with the mouse or keyboard, and the text can be copied with the Copy command. + You can select text this way even if the text field is a dynamic text field instead of an input text field.

+ +
The following example creates two dynamic text fields: one text field with the selectable + property set to true, and the other text field with the selectable property set to false. + When you use this example, try to select the text in these fields with the mouse or the keyboard. + + +package +{ + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class selectableExample extends Sprite + { + public function selectableExample() + { + var tf1:TextField = createCustomTextField(10, 10); + tf1.text="This text can be selected"; + tf1.selectable=true; + + var tf2:TextField = createCustomTextField(10, 30); + tf2.text="This text cannot be selected"; + tf2.selectable=false; + } + + private function createCustomTextField(x:Number, y:Number):TextField + { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.autoSize=TextFieldAutoSize.LEFT; + addChild(result); + return result; + } + } +} +
setSelection()selectionBeginIndexselectionEndIndexsetSelection()caretIndex
selectionBeginIndex + The zero-based character index value of the first character in the current selection.intThe zero-based index value of the first character in the selection. + + + The zero-based character index value of the first character in the current selection. + For example, the first character is 0, the second character is 1, and so on. If no + text is selected, this property is the value of caretIndex. + + In this example, a TextField instance is created and populated with text. + An event listener is assigned so that when the user clicks on the TextField, the + printCursorPosition method is called. In that case, the values of the + caretIndex, selectionBeginIndex, and + selectionEndIndex properties are output. + +

Run this example and try clicking in the TextField to select text. Then click in the field without + selecting text. When you click in the text without making a selection, the + caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex + and selectionEndIndex properties equal the caretIndex property value.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldType; + + public class TextField_caretIndex extends Sprite { + public function TextField_caretIndex() { + var tf:TextField = createCustomTextField(10, 10, 100, 100); + tf.wordWrap = true; + tf.type = TextFieldType.INPUT; + tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text."; + tf.addEventListener(MouseEvent.CLICK, printCursorPosition); + } + + private function printCursorPosition(event:MouseEvent):void { + var tf:TextField = TextField(event.target); + trace("caretIndex:", tf.caretIndex); + trace("selectionBeginIndex:", tf.selectionBeginIndex); + trace("selectionEndIndex:", tf.selectionEndIndex); + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +
selectableselectionEndIndexsetSelection()caretIndex
selectionEndIndex + The zero-based character index value of the last character in the current selection.intThe zero-based index value of the last character in the selection. + + + The zero-based character index value of the last character in the current selection. + For example, the first character is 0, the second character is 1, and so on. If no + text is selected, this property is the value of caretIndex. + + In this example, a TextField instance is created and populated with text. + An event listener is assigned so that when the user clicks on the TextField, the + printCursorPosition method is called. In that case, the values of the + caretIndex, selectionBeginIndex, and + selectionEndIndex properties are output. + +

Run this example and try clicking in the TextField to select text. Then click in the field without + selecting text. When you click in the text without making a selection, the + caretIndex property indicates where the insertion point occurs, and the selectionBeginIndex + and selectionEndIndex properties equal the caretIndex property value.

+ + +package { + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.text.TextField; + import flash.text.TextFieldType; + + public class TextField_caretIndex extends Sprite { + public function TextField_caretIndex() { + var tf:TextField = createCustomTextField(10, 10, 100, 100); + tf.wordWrap = true; + tf.type = TextFieldType.INPUT; + tf.text = "Click in this text field. Compare the difference between clicking without selecting versus clicking and selecting text."; + tf.addEventListener(MouseEvent.CLICK, printCursorPosition); + } + + private function printCursorPosition(event:MouseEvent):void { + var tf:TextField = TextField(event.target); + trace("caretIndex:", tf.caretIndex); + trace("selectionBeginIndex:", tf.selectionBeginIndex); + trace("selectionEndIndex:", tf.selectionEndIndex); + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +
selectableselectionBeginIndexsetSelection()caretIndex
sharpness + The sharpness of the glyph edges in this text field.Number0 + + The sharpness of the glyph edges. + + + The sharpness of the glyph edges in this text field. This property applies + only if the flash.text.AntiAliasType property of the text field is set to + flash.text.AntiAliasType.ADVANCED. The range for + sharpness is a number from -400 to 400. If you attempt to set + sharpness to a value outside that range, Flash sets the property to + the nearest value in the range (either -400 or 400). + + The following example shows the effect of changing the sharpness + property for a TextField object. You need to embed the font, and set the + antiAliasType property to ADVANCED. + + +package +{ + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.AntiAliasType; + import flash.text.GridFitType; + import flash.text.TextFormat; + + public class sharpnessExample extends Sprite + { + public function sharpnessExample() + { + var format1:TextFormat = new TextFormat(); + format1.font="Arial"; + format1.size=24; + var lTxt:String = "The quick brown fox"; + + var tf1:TextField=createCustomTextField(0,lTxt,format1,-400); + var tf2:TextField=createCustomTextField(30,lTxt,format1,0); + var tf3:TextField=createCustomTextField(60,lTxt,format1,400); + } + + private function createCustomTextField(y:Number,fldTxt:String,format:TextFormat,fldSharpness:Number):TextField + { + var result:TextField = new TextField(); + result.y=y; + result.text=fldTxt; + result.embedFonts=true; + result.autoSize=TextFieldAutoSize.LEFT; + result.antiAliasType=AntiAliasType.ADVANCED; + result.gridFitType=GridFitType.PIXEL; + result.sharpness=fldSharpness; + result..setTextFormat(format); + addChild(result); + return result; + } + } +} +flash.text.TextField.antiAliasTypeflash.text.AntiAliasTypestyleSheet + Attaches a style sheet to the text field.flash.text:StyleSheetAttaches a style sheet to the text field. + + + Attaches a style sheet to the text field. For information on creating style sheets, see the StyleSheet class + and the ActionScript 3.0 Developer's Guide. + +

You can change the style sheet associated with a text field at any time. If you change + the style sheet in use, the text field is redrawn with the new style sheet. + You can set the style sheet to null or undefined + to remove the style sheet. If the style sheet in use is removed, the text field is redrawn without a style sheet.

+

Note: If the style sheet is removed, the contents of both TextField.text and + TextField.htmlText change to incorporate the formatting previously applied by the style sheet. To preserve + the original TextField.htmlText contents without the formatting, save the value in a variable before + removing the style sheet.

+ +
The following example defines a simple StyleSheet object + and assigns it to a text field with HTML content. Set the + stylesheet property before setting the content. + + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.StyleSheet; + + public class TextStylesheetExample extends Sprite { + var myLabel:TextField = new TextField(); + var labelText:String = "Hello world."; + var newStyle:StyleSheet = new StyleSheet(); + + public function TextStylesheetExample() + { + var styleObj:Object = new Object(); + styleObj.fontWeight = "bold"; + styleObj.color = "#660066"; + newStyle.setStyle(".defStyle", styleObj); + + myLabel.styleSheet=newStyle; + myLabel.htmlText=labelText; + addChild(myLabel); + } + } +} +
flash.text.StyleSheet
textColor + The color of the text in a text field, in hexadecimal format.uint0 (0x000000) + The color of the text in a text field, in hexadecimal format. + + + The color of the text in a text field, in hexadecimal format. + The hexadecimal color system uses six digits to represent + color values. Each digit has 16 possible values or characters. The characters range from + 0-9 and then A-F. For example, black is 0x000000; white is + 0xFFFFFF. + + The following ActionScript creates a TextField object and changes its + textColor property to red (0xFF0000). + + +package { + import flash.display.Sprite; + import flash.text.TextField; + + public class TextField_textColor extends Sprite { + public function TextField_textColor() { + var tf:TextField = createCustomTextField(10, 10, 100, 300); + tf.text = "This will be red text"; + tf.textColor = 0xFF0000; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +textHeight + The height of the text in pixels.NumberThe height of the text in pixels. + + + The height of the text in pixels. + + The following example creates a TextField object and assigns text to it. + The trace statements display the values of the textWidth and + textHeight properties. For comparison, the width and height + properties are also displayed. (Note that the values you see for textHeight and textWidth might + vary depending on the font that is used on your machine). + + +package { + import flash.display.Sprite; + import flash.text.TextField; + + public class TextField_textHeight extends Sprite { + public function TextField_textHeight() { + var tf:TextField = createCustomTextField(10, 10, 100, 150); + tf.text = "Sample text"; + + trace("textWidth: " + tf.textWidth); // textWidth: 55.75 + trace("textHeight: " + tf.textHeight); // textHeight: 13.450000000000001 + trace("width: " + tf.width); // width: 100 + trace("height: " + tf.height); // height: 150 + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.border = true; + result.background = true; + addChild(result); + return result; + } + } +} +flash.text.TextField.textWidthtextInteractionMode + The interaction mode property, Default value is TextInteractionMode.NORMAL.String + The interaction mode property, Default value is TextInteractionMode.NORMAL. + On mobile platforms, the normal mode implies that the text can be scrolled but not selected. + One can switch to the selectable mode through the in-built context menu on the text field. + On Desktop, the normal mode implies that the text is in scrollable as well as selection mode. + textWidth + The width of the text in pixels.NumberThe width of the text in pixels. + + + The width of the text in pixels. + + The following example creates a TextField object and assigns text to it. + The trace statements display the values of the textWidth and + textHeight properties. For comparison, the width and height + properties are also displayed. (Note that the values you see for textHeight and textWidth might + vary depending on the font that is used on your machine). + + +package { + import flash.display.Sprite; + import flash.text.TextField; + + public class TextField_textHeight extends Sprite { + public function TextField_textHeight() { + var tf:TextField = createCustomTextField(10, 10, 100, 150); + tf.text = "Sample text"; + + trace("textWidth: " + tf.textWidth); // textWidth: 55.75 + trace("textHeight: " + tf.textHeight); // textHeight: 13.450000000000001 + trace("width: " + tf.width); // width: 100 + trace("height: " + tf.height); // height: 150 + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.border = true; + result.background = true; + addChild(result); + return result; + } + } +} +flash.text.TextField.textHeighttext + A string that is the current text in the text field.StringA string that is the current text in the text field. + + + A string that is the current text in the text field. Lines are separated by the carriage + return character ('\r', ASCII 13). This property contains unformatted text in the text + field, without HTML tags. + +

To get the text in HTML form, use the htmlText property.

+ +
The following example creates a TextField called tf1, and assigns an + HTML-formatted String to its text property. When its htmlText property + is traced, the output is the HTML-formatted String, with additional tags (such as <P> and + <FONT>) automatically added by Flash Player. When the value of the text + property is traced, the unformatted string without HTML tags is displayed. + +

By way of comparison, the same steps are performed on another TextField object named + tf2, with the addition that a StyleSheet object is assigned to tf2's + styleSheet property before its htmlText property is set. In that case, + when the htmlText property is traced, it only includes the exact HTML text that was + originally assigned to the htmlText property, showing that no additional tags were + added by Flash Player.

+ + +package { + import flash.display.Sprite; + import flash.text.StyleSheet; + import flash.text.TextField; + + public class TextField_text extends Sprite { + public function TextField_text() { + var tf1:TextField = createCustomTextField(10, 10, 400, 22); + tf1.htmlText = "<b>Lorem ipsum dolor sit amet.</b>"; + + // htmlText: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">&lt;b&gt;Lorem ipsum dolor sit amet.&lt;/b&gt;</FONT></P> + trace("htmlText: " + tf1.htmlText); + // text: Lorem ipsum dolor sit amet. + trace("text: " + tf1.text); + + var tf2:TextField = createCustomTextField(10, 50, 400, 22); + tf2.styleSheet = new StyleSheet(); + tf2.htmlText = "<b>Lorem ipsum dolor sit amet.</b>"; + // htmlText: <b>Lorem ipsum dolor sit amet.</b> + trace("htmlText: " + tf2.htmlText); + // text: Lorem ipsum dolor sit amet. + trace("text: " + tf2.text); + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + addChild(result); + return result; + } + } +} +
flash.text.TextField.htmlText
thickness + The thickness of the glyph edges in this text field.Number0 + + The thickness of the glyph edges. + + + The thickness of the glyph edges in this text field. This property applies only + when flash.text.AntiAliasType is set to flash.text.AntiAliasType.ADVANCED. + +

The range for thickness is a number from -200 to 200. If you attempt to + set thickness to a value outside that range, the property is set to the + nearest value in the range (either -200 or 200).

+ +
The following example shows the effect of changing the thickness + property for a TextField object. You need to embed the font, and set the antiAliasType + property to ADVANCED. + + +package +{ + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.AntiAliasType; + import flash.text.GridFitType; + import flash.text.TextFormat; + + public class thicknessExample extends Sprite + { + public function thicknessExample() + { + var format1:TextFormat = new TextFormat(); + format1.font="Arial"; + format1.size=24; + var lTxt:String = "The quick brown fox"; + + var tf1:TextField=createCustomTextField(0,lTxt,format1,-200); + var tf2:TextField=createCustomTextField(30,lTxt,format1,0); + var tf3:TextField=createCustomTextField(60,lTxt,format1,200); + } + + private function createCustomTextField(y:Number,fldTxt:String,format:TextFormat,fldThickness:Number):TextField + { + var result:TextField = new TextField(); + result.y=y; + result.text=fldTxt; + result.embedFonts=true; + result.autoSize=TextFieldAutoSize.LEFT; + result.antiAliasType=AntiAliasType.ADVANCED; + result.gridFitType=GridFitType.PIXEL; + result.thickness=fldThickness; + result.setTextFormat(format); + addChild(result); + return result; + } + } +} +
flash.text.TextField.antiAliasTypeflash.text.AntiAliasType
type + The type of the text field.StringThe type specified is not a member of flash.text.TextFieldType. + + ArgumentErrorArgumentErrordynamic + + The type of the text field. + + + The type of the text field. + Either one of the following TextFieldType constants: TextFieldType.DYNAMIC, + which specifies a dynamic text field, which a user cannot edit, or TextFieldType.INPUT, + which specifies an input text field, which a user can edit. + + The following example creates two text fields: tfDynamic and + tfInput. Text is entered into both text fields. However, + tfDynamic has its type property set to + TextFieldType.DYNAMIC, and tfInput has its + type property set to TextFieldType.INPUT, so the user can + modify the text in tfInput but can only view the text in tfDynamic. + + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + + public class TextField_type extends Sprite { + public function TextField_type() { + var tfDynamic:TextField = createCustomTextField(10, 10, 100, 20); + tfDynamic.type = TextFieldType.DYNAMIC; + tfDynamic.text = "hello"; + + var tfInput:TextField = createCustomTextField(10, 45, 100, 20); + tfInput.type = TextFieldType.INPUT; + tfInput.text = "world"; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.background = true; + result.border = true; + addChild(result); + return result; + } + } +} +flash.text.TextFieldTypeuseRichTextClipboard + Specifies whether to copy and paste the text formatting along with the text.Boolean + Specifies whether to copy and paste the text formatting along with the text. When set to true, + Flash Player copies and pastes formatting (such as alignment, bold, and italics) when you copy and paste between text fields. Both the origin and destination text fields for the copy and paste procedure must have + useRichTextClipboard set to true. The default value + is false. + + This example creates an input text field (tf1) and two dynamic + text fields (tf2 and tf3). + The code assigns each dynamic text field a TextFormat object (Courier Bold font). + The tf2 text field has useRichTextClipboard property set to + false. The tf3 text field has the + useRichTextClipboard property set to true. + When you copy the text from the tf2 text field + and paste it into the tf1 text field, the pasted text does not include + the formatting. When you copy the text from the tf3 text field (which has + useRichTextClipboard set to true) and paste it into the + tf1 text field, the pasted text includes the formatting. + + +package +{ + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + + public class useRichTextClipboard extends Sprite + { + public function useRichTextClipboard() + { + var format1:TextFormat = new TextFormat(); + format1.font="Courier"; + format1.bold=true; + + var tf1:TextField = createCustomTextField(10, 10, 200, 20); + tf1.type=TextFieldType.INPUT; + tf1.useRichTextClipboard=true; + + var tf2:TextField = createCustomTextField(220, 10, 200, 20); + tf2.text="1.Text loses format"; + tf2.setTextFormat(format1); + tf2.useRichTextClipboard=false; + + var tf3:TextField = createCustomTextField(220, 50, 200, 20); + tf3.text="2.Text includes format"; + tf3.setTextFormat(format1); + tf3.useRichTextClipboard=true; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField + { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.background = true; + result.border = true; + addChild(result); + return result; + } + } +} +wordWrap + A Boolean value that indicates whether the text field has word wrap.BooleanIndicates whether the text field has word wrap. + + + A Boolean value that indicates whether the text field has word wrap. If the value of + wordWrap is true, the text field has word wrap; + if the value is false, the text field does not have word wrap. The default + value is false. + + This example demonstrates the difference between setting the wordWrap + property to true and setting it to false. Two TextField instances are + created whose contents are too large for their widths. The wordWrap property of + the first (named tfWrap) is set to true; it is set to false + for the second (tfNoWrap). + + +package { + import flash.display.Sprite; + import flash.text.TextField; + + public class TextField_wordWrap extends Sprite { + public function TextField_wordWrap() { + var tfWrap:TextField = createCustomTextField(10, 10, 100, 100); + tfWrap.wordWrap = true; + tfWrap.text = "(wordWrap = true):\nThis is very long text that will certainly extend beyond the width of this text field"; + + var tfNoWrap:TextField = createCustomTextField(10, 150, 100, 100); + tfNoWrap.wordWrap = false; + tfNoWrap.text = "(wordWrap = false):\nThis is very long text that will certainly extend beyond the width of this text field"; + } + + private function createCustomTextField(x:Number, y:Number, width:Number, height:Number):TextField { + var result:TextField = new TextField(); + result.x = x; + result.y = y; + result.width = width; + result.height = height; + result.background = true; + result.border = true; + addChild(result); + return result; + } + } +} +
TextFormat + The TextFormat class represents character formatting information.Creates text formatting for text fields. + + Object + The TextFormat class represents character formatting information. Use the TextFormat class + to create specific text formatting for text fields. You can apply text formatting + to both static and dynamic text fields. The properties of the TextFormat class apply to device and + embedded fonts. However, for embedded fonts, bold and italic text actually require specific fonts. If you + want to display bold or italic text with an embedded font, you need to embed the bold and italic variations + of that font. + +

You must use the constructor new TextFormat() to create a TextFormat object + before setting its properties. + When you apply a TextFormat object to a text field using the TextField.defaultTextFormat property + or the TextField.setTextFormat() method, only its defined properties are applied. Use + the TextField.defaultTextFormat property to apply formatting BEFORE you add text to the TextField, + and the setTextFormat() method to add formatting AFTER you add text to the TextField. + The TextFormat properties are null by default + because if you don't provide values for the properties, Flash Player uses its own default formatting. + The default formatting that Flash Player uses for each property (if property's value is null) + is as follows:

+ + align = "left"blockIndent = 0bold = falsebullet = falsecolor = 0x000000font = "Times New Roman" (default font is Times on Mac OS X)indent = 0italic = falsekerning = falseleading = 0leftMargin = 0letterSpacing = 0rightMargin = 0size = 12tabStops = [] (empty array)target = "" (empty string)underline = falseurl = "" (empty string) + +

The default formatting for each property is also described in each property description.

+ +
The following example creates the TextFieldExample class to display a text message with + the default location (x = 0, y = 0). This is accomplished using the following steps: +
  1. A property label of type TextField is created.
  2. The class constructor calls the function configureLabel()
  3. The configureLabel() function first creates a new TextField object and assigns it to + label then sets its parameters to +
    • Left-justify the text field
    • Enable the background fill
    • Enable the border.
    +
  4. Next, configureLabel() creates the local variable, format, and assigns it to + a new TextFormat instance with its parameters set to: +
    • Font type = Verdana
    • Font Color = solid red
    • Font size = 10
    • Font underline = true.
    +
  5. The label's defaultTextFormat property is set to format, and the + label instance is added to the display list, which initially displays a text field with + no text (as tiny box with a white background) on the stage.
  6. Finally (back in the constructor), the label's text is then set to display "Hello + World and welcome to the show", at coordinates x = 0, y = 0 by calling setLabel().
+ + package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFormat; + + + public class TextFormatExample extends Sprite { + private var label:TextField; + + public function TextFormatExample() { + configureLabel(); + setLabel("Hello World and welcome to the show"); + } + + public function setLabel(str:String):void { + label.text = str; + } + + private function configureLabel():void { + label = new TextField(); + label.autoSize = TextFieldAutoSize.LEFT; + label.background = true; + label.border = true; + + var format:TextFormat = new TextFormat(); + format.font = "Verdana"; + format.color = 0xFF0000; + format.size = 10; + format.underline = true; + + label.defaultTextFormat = format; + addChild(label); + } + } +} +
flash.text.TextField.setTextFormat()flash.text.TextField.defaultTextFormatflash.text.TextField.getTextFormat()TextFormat + Creates a TextFormat object with the specified properties.fontStringnullThe name of a font for text as a string. + sizeObjectnullAn integer that indicates the size in pixels. + colorObjectnullThe color of text using this text format. A number containing three 8-bit RGB + components; for example, 0xFF0000 is red, and 0x00FF00 is green. + boldObjectnullA Boolean value that indicates whether the text is boldface. + italicObjectnullA Boolean value that indicates whether the text is italicized. + underlineObjectnullA Boolean value that indicates whether the text is underlined. + urlStringnullThe URL to which the text in this text format hyperlinks. If url is + an empty string, the text does not have a hyperlink. + targetStringnullThe target window where the hyperlink is displayed. If the target window is an empty + string, the text is displayed in the default target window _self. If the + url parameter is set to an empty string or to the value null, you can get or + set this property, but the property will have no effect. + alignStringnullThe alignment of the paragraph, as a TextFormatAlign value. + leftMarginObjectnullIndicates the left margin of the paragraph, in pixels. + rightMarginObjectnullIndicates the right margin of the paragraph, in pixels. + indentObjectnullAn integer that indicates the indentation from the left margin to the first character + in the paragraph. + leadingObjectnullA number that indicates the amount of leading vertical space between lines. + + + Creates a TextFormat object with the specified properties. You can then change the + properties of the TextFormat object to change the formatting of text fields. + +

Any parameter may be set to null to indicate that it is not defined. All of the + parameters are optional; any omitted parameters are treated as null.

+ +
In the following example, a user can select different text formatting + options from a list that is applied to the content of another text field. If the user + clicks on the text field's content, the formatting reverts to the default (original) format. + +

The formatTextField text field lists all the TextField class property options + (with the exception of kerning) in a separate line. When a user clicks a + line in the formatTextField text field, the formatTextFieldClickHandler() + method is triggered.

+ +

The formatTextFieldClickHandler() method calls the TextField.getLineIndexAtPoint() + method to get the index of the line that was clicked, and then calls the TextField.getLineText() + method to get the content of the line. The switch statement checks the content of the line and sets + a property of the newformat TextFormat object accordingly. The setTextFormat() + method then sets the text format of the contentTextField text field to the new format. By clicking + different formatTextField lines, a user can apply a different formatting + to the contentTextField text field. (The tab setting is an array that defines + a separate tab stop for each tab in the line.) If the url or target line + is selected, the user must click the contentTextField text field to activate the link + and display the content of the target URL (Flex home page). The default value of the target + property is "_self", which means that the content is displayed in the current window if the user + selects the url line. For the target property to work, a URL must be + set already in the url property.

+ +

If a user clicks the contentTextField text field, the contentTextFieldClickHandler() + method is triggered, which sets the field's format and the newFormat TextFormat + object to the default (original) format of the text field. This clears all the formatting changes + that the user made.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.text.TextFieldAutoSize; + import flash.events.MouseEvent; + import flash.text.TextFormatAlign; + + public class TextFormat_constructorExample extends Sprite { + private var contentTextField:TextField = new TextField(); + private var formatTextField:TextField = new TextField(); + private var newFormat:TextFormat = new TextFormat(); + + public function TextFormat_constructorExample() { + contentTextField.x = 10; + contentTextField.y = 10; + contentTextField.background = true; + contentTextField.border = true; + contentTextField.multiline = true; + contentTextField.wordWrap = true; + contentTextField.selectable = false; + contentTextField.width = 250; + contentTextField.height = 120; + + contentTextField.htmlText = "<p>The TextFormat class represents character formatting " + + "information. Use the TextFormat class to create specific text formatting " + + "for text fields." + + " </p><br>" + "\tTab One" + "\tTab Two<br>"; + + formatTextField.x = 10; + formatTextField.y = 140; + formatTextField.background = true; + formatTextField.border = true; + formatTextField.autoSize = TextFieldAutoSize.LEFT; + + formatTextField.text = "align: right\n" + "blockIndent: 10 pixels\n" + "bold:\n" + "bullet:\n" + "color: red\n" + + "font: Arial\n" + "indent: 20 pixels\n" + "italic:\n" + "leading: 5 spaces\n" + + "leftMargin: 20 pixels\n" + "letterSpacing: 4 pixels\n" + "rightMargin: 20 pixels\n" + + "size: 16 point\n" + "target: new window\n" + "tabStops: 50 and 150 pixel\n" + + "underline:\n" + "url: Apache Flex page\n"; + + formatTextField.addEventListener(MouseEvent.CLICK, formatTextFieldClickHandler); + + contentTextField.addEventListener(MouseEvent.CLICK, contentTextFieldClickHandler); + + this.addChild(contentTextField); + this.addChild(formatTextField); + } + + private function formatTextFieldClickHandler(e:MouseEvent):void { + var value:String= ""; + var i:uint = 0; + var index:int = formatTextField.getLineIndexAtPoint(e.localX, e.localY); + var line:String = formatTextField.getLineText(index);; + + line = line.substr(0, (line.indexOf(":"))); + + switch(line) { + case "align": + newFormat.align = TextFormatAlign.RIGHT; + break; + case "blockIndent": + newFormat.blockIndent = 10; + break; + case "bold": + newFormat.bold = true; + break; + case "bullet": + newFormat.bullet = true; + break; + case "color": + newFormat.color = 0xFF0000; + break; + case "font": + newFormat.font = "Arial"; + break; + case "indent": + newFormat.indent = 20; + break; + case "italic": + newFormat.italic = true; + break; + case "leading": + newFormat.leading = 5; + break; + case "leftMargin": + newFormat.leftMargin = 20; + break; + case "letterSpacing": + newFormat.letterSpacing = 4; + break; + case "rightMargin": + newFormat.rightMargin = 20; + break; + case "size": + newFormat.size = 16; + break; + case "tabStops": + newFormat.tabStops = [50, 150]; + break; + case "target": + newFormat.url = "http://www.adobe.com/products/flex/"; + newFormat.target = "_blank"; + break; + case "underline": + newFormat.underline = true; + break; + case "url": + newFormat.url = "http://www.adobe.com/products/flex/"; + break; + } + + contentTextField.setTextFormat(newFormat); + } + + private function contentTextFieldClickHandler(e:MouseEvent):void { + contentTextField.setTextFormat(contentTextField.defaultTextFormat); + newFormat = contentTextField.defaultTextFormat; + } + } +} +
align + Indicates the alignment of the paragraph.StringThe align specified is not a member of flash.text.TextFormatAlign. + + ArgumentErrorArgumentErrorTextFormatAlign.LEFT + + + Indicates the alignment of the paragraph. Valid values are TextFormatAlign constants. + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + flash.text.TextFormatAlignblockIndent + Indicates the block indentation in pixels.Object + Indicates the block indentation in pixels. Block indentation is applied to + an entire block of text; that is, to all lines of the text. In contrast, normal indentation + (TextFormat.indent) affects only the first line of each paragraph. + If this property is null, the TextFormat object does not specify block indentation + (block indentation is 0). + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + bold + Specifies whether the text is boldface.Object + Specifies whether the text is boldface. The default value is null, + which means no boldface is used. + If the value is true, then + the text is boldface. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + bullet + Indicates that the text is part of a bulleted list.Object + Indicates that the text is part of a bulleted list. In a bulleted + list, each paragraph of text is indented. To the left of the first line of each paragraph, a bullet + symbol is displayed. The default value is null, which means no bulleted list + is used. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + color + Indicates the color of the text.Object + Indicates the color of the text. A number containing three 8-bit RGB components; for example, + 0xFF0000 is red, and 0x00FF00 is green. The default value is null, + which means that Flash Player uses the color black (0x000000). + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + font + The name of the font for text in this text format, as a string.String + The name of the font for text in this text format, as a string. The default value is + null, which means that Flash Player uses Times New Roman font for the text. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + indent + Indicates the indentation from the left + margin to the first character in the paragraph.Object + Indicates the indentation from the left + margin to the first character in the paragraph. The default value is null, which + indicates that no indentation is used. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + flash.text.TextFormat.blockIndentitalic + Indicates whether text in this text format is italicized.Object + Indicates whether text in this text format is italicized. The default + value is null, which means no italics are used. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + kerning + A Boolean value that indicates whether kerning is enabled (true) + or disabled (false).Object + A Boolean value that indicates whether kerning is enabled (true) + or disabled (false). Kerning adjusts the pixels between certain character pairs to improve readability, and + should be used only when necessary, such as with headings in large fonts. Kerning is + supported for embedded fonts only. + +

Certain fonts such as Verdana and monospaced fonts, + such as Courier New, do not support kerning.

+ +

The default value is null, which means that kerning is not enabled.

+ +
leading + An integer representing the amount of vertical space (called leading) + between lines.Object + An integer representing the amount of vertical space (called leading) + between lines. The default value is null, which indicates that the + amount of leading used is 0. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + leftMargin + The left margin of the paragraph, in pixels.Object + The left margin of the paragraph, in pixels. The default value is null, which + indicates that the left margin is 0 pixels. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + letterSpacing + A number representing the amount of space that is uniformly distributed between all characters.Object + A number representing the amount of space that is uniformly distributed between all characters. + The value specifies the number of pixels that are added to the advance after each character. + The default value is null, which means that 0 pixels of letter spacing is used. + You can use decimal values such as 1.75. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + rightMargin + The right margin of the paragraph, in pixels.Object + The right margin of the paragraph, in pixels. The default value is null, + which indicates that the right margin is 0 pixels. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + size + The size in pixels of text in this text format.Object + The size in pixels of text in this text format. The default value is null, which + means that a size of 12 is used. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + tabStops + Specifies custom tab stops as an array of non-negative integers.Array + Specifies custom tab stops as an array of non-negative integers. Each tab stop is + specified in pixels. If custom tab stops are not specified (null), the default tab + stop is 4 (average character width). + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + target + Indicates the target window where the hyperlink is displayed.String + Indicates the target window where the hyperlink is displayed. If the target window is an + empty string, the text is displayed in the default target window _self. You can choose + a custom name or one of the following four names: _self specifies the current frame in + the current window, _blank specifies a new window, _parent specifies the + parent of the current frame, and _top specifies the top-level frame in the current + window. If the TextFormat.url property is an empty string or null, + you can get or set this property, but the property will have no effect. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + flash.text.TextFormat.urlunderline + Indicates whether the text that uses this text format is underlined (true) + or not (false).Object + Indicates whether the text that uses this text format is underlined (true) + or not (false). This underlining is similar to that produced by the + <U> tag, but the latter is not true underlining, because it does not skip + descenders correctly. The default value is null, which indicates that underlining + is not used. + + Please see the TextFormat() constructor example + for an illustration of how to use this property. + + url + Indicates the target URL for the text in this text format.String + Indicates the target URL for the text in this text format. If the url + property is an empty string, the text does not have a hyperlink. The default value is null, + which indicates that the text does not have a hyperlink. +

Note: The text with the assigned text format must be set with the htmlText + property for the hyperlink to work.

+ +
Please see the TextFormat() constructor example + for an illustration of how to use this property. + +
flash.text.TextField.htmlText
TextDisplayMode + The TextDisplayMode class contains values that control the subpixel anti-aliasing of the advanced anti-aliasing system.Object + The TextDisplayMode class contains values that control the subpixel anti-aliasing of the advanced anti-aliasing system. + + flash.text.TextRenderer.displayModeCRT + Forces Flash Player to display grayscale anti-aliasing.crtString + Forces Flash Player to display grayscale anti-aliasing. While this setting + avoids text coloring, some users may think it appears blurry. + DEFAULT + Allows Flash Player to choose LCD or CRT mode.defaultString + Allows Flash Player to choose LCD or CRT mode. + LCD + Forces Flash Player to use LCD subpixel anti-aliasing.lcdString + Forces Flash Player to use LCD subpixel anti-aliasing. Depending on the font and + the hardware, this setting can result in much higher resolution text or text coloring. + AntiAliasType +The AntiAliasType class provides values for anti-aliasing in the flash.text.TextField class.Object +The AntiAliasType class provides values for anti-aliasing in the flash.text.TextField class. +flash.text.TextFieldADVANCED + Sets anti-aliasing to advanced anti-aliasing.advancedString + Sets anti-aliasing to advanced anti-aliasing. Advanced anti-aliasing + allows font faces to be rendered at very high quality at small sizes. It is best used + with applications that have a lot of small text. Advanced anti-aliasing is not recommended + for very large fonts (larger than 48 points). + This constant is used for the antiAliasType property in the TextField + class. + Use the syntax AntiAliasType.ADVANCED. + + flash.text.TextField.antiAliasTypeNORMAL + Sets anti-aliasing to the anti-aliasing that is used in Flash Player 7 and earlier.Bob Pappas + normalString + Sets anti-aliasing to the anti-aliasing that is used in Flash Player 7 and earlier. + This setting is recommended for applications that do not have a lot of text. + This constant is used for the antiAliasType property in the TextField + class. + Use the syntax AntiAliasType.NORMAL. + flash.text.TextField.antiAliasTypeFontType + The FontType class contains the enumerated constants "embedded" + and "device" for the fontType property of the Font class.Object + The FontType class contains the enumerated constants "embedded" + and "device" for the fontType property of the Font class. + + flash.text.Font.fontTypeDEVICE + Indicates that this is a device font.deviceString + Indicates that this is a device font. + The SWF file renders fonts with those installed on the system. + +

Using device fonts results in a smaller movie size, because font data + is not included in the file. Device fonts are often a good choice for + displaying text at small point sizes, because anti-aliased text can be blurry + at small sizes. Device fonts are also a good choice for large blocks of text, + such as scrolling text.

+ +

Text fields that use device fonts may not be displayed the same across different + systems and platforms, because they are rendered with fonts installed on the system. + For the same reason, device fonts are not anti-aliased and may appear jagged at + large point sizes.

+ +
TextField.embedFontsflash.text.engine.FontDescription.fontLookup
EMBEDDED_CFF + Indicates that this is an embedded CFF font.embeddedCFFString + Indicates that this is an embedded CFF font. + Font outlines and a subset of OpenType tables are embedded in the published SWF file. + +

Text that uses embedded CFF fonts is always displayed + in the chosen font, whether or not that font is installed + on the playback system. Also, text that uses embedded CFF fonts + is always anti-aliased (smoothed) by Flash Player. You + can select the rendering mode and hinting for an embedded CFF font using the + flash.text.engine.FontDescription.renderingMode and + flash.text.engine.FontDescription.cffHinting properties.

+ +

One drawback to embedded CFF fonts is that they increase the size of the SWF file. + However, embedded CFF fonts are typically 20% to 30% smaller than regular embedded fonts.

+ +

Fonts of type EMBEDDED_CFF can only be used by the flash.text.engine classes. + A TextField directed to use such a font will fail to render.

+ +
flash.text.engine.FontDescription.fontLookup
EMBEDDED + Indicates that this is an embedded font.embeddedString + Indicates that this is an embedded font. + Font outlines are embedded in the published SWF file. + +

Text fields that use embedded fonts are always displayed + in the chosen font, whether or not that font is installed + on the playback system. Also, text fields that use embedded fonts + are always anti-aliased (smoothed). You + can select the amount of anti-aliasing you want by using the + TextField.antiAliasType property.

+ +

One drawback to embedded fonts is that they increase the size of the SWF file.

+ +

Fonts of type EMBEDDED can only be used by TextField. + If flash.text.engine classes are directed to use such a font they will fall back to device fonts.

+ +
TextField.embedFonts
TextFormatAlign + The TextFormatAlign class provides values for text alignment in the TextFormat class.Object + The TextFormatAlign class provides values for text alignment in the TextFormat class. + + + flash.text.TextFormatCENTER + Constant; centers the text in the text field.centerString + Constant; centers the text in the text field. + Use the syntax TextFormatAlign.CENTER. + flash.text.TextFormat.alignJUSTIFY + Constant; justifies text within the text field.justifyString + Constant; justifies text within the text field. + Use the syntax TextFormatAlign.JUSTIFY. + + flash.text.TextFormat.alignLEFT + Constant; aligns text to the left within the text field.leftString + Constant; aligns text to the left within the text field. + Use the syntax TextFormatAlign.LEFT. + flash.text.TextFormat.alignRIGHT + Constant; aligns text to the right within the text field.rightString + Constant; aligns text to the right within the text field. + Use the syntax TextFormatAlign.RIGHT. + flash.text.TextFormat.alignFont + The Font class is used to manage embedded fonts in SWF files.Object + The Font class is used to manage embedded fonts in SWF files. Embedded fonts + are represented as a subclass of the Font class. The Font class is currently useful only to + find out information about embedded fonts; you cannot alter a font by + using this class. + + You cannot use the Font class to load external fonts, or to create an instance + of a Font object by itself. Use the Font class as an abstract base class. + + enumerateFonts + Specifies whether to provide a list of the currently available embedded fonts.A list of available fonts as an array of Font objects. + ArrayenumerateDeviceFontsBooleanfalseIndicates whether you want to limit the list to only the currently available embedded fonts. + If this is set to true then a list of all fonts, both device fonts and embedded fonts, is returned. + If this is set to false then only a list of embedded fonts is returned. + + Specifies whether to provide a list of the currently available embedded fonts. + This example first calls the static method Font.enumerateFonts() + to get a list of all device and embedded fonts. Then it sorts the resulting Array of Font objects + by the fontName property. + +

Next the example shows how to call the Font.enumerateFonts() method with the + enumerateDeviceFonts parameter set to false. The resulting Array only includes + embedded Font objects. (If you run this code within an application that does not contain + any embedded fonts, the embeddedFonts array will be empty.)

+ + +import flash.text.Font; + +var allFonts:Array = Font.enumerateFonts(true); +allFonts.sortOn("fontName", Array.CASEINSENSITIVE); + +var embeddedFonts:Array = Font.enumerateFonts(false); +embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE); +
hasGlyphs + Specifies whether a provided string can be displayed using the currently assigned font.A value of true if the specified string can be fully displayed using this font. + BooleanstrStringThe string to test against the current font. + + Specifies whether a provided string can be displayed using the currently assigned font. + registerFont + Registers a font class in the global font list.fontClassThe class you want to add to the global font list. + + Registers a font class in the global font list. + fontName + The name of an embedded font.String + The name of an embedded font. + + The following example shows how you can use an embedded font with the Flash Professional ActionScript 3.0 CheckBox control by setting the textFormat and embedFonts styles. + Example provided by + ActionScriptExamples.com. + +// Requires: +// - A CheckBox control UI component in Flash library. +// - An embedded font in Flash library with linkage class "MyFont" and Export for ActionScript checked. +// +import fl.controls.CheckBox; + +var embeddedFont:Font = new MyFont(); + +var textFormat:TextFormat = new TextFormat(); +textFormat.font = embeddedFont.fontName; +textFormat.size = 24; + +var checkBox:CheckBox = new CheckBox(); +checkBox.setStyle("textFormat", textFormat); +checkBox.setStyle("embedFonts", true); +checkBox.label = "The quick brown fox jumps over the lazy dog."; +checkBox.textField.autoSize = TextFieldAutoSize.LEFT; +checkBox.move(10, 10); +checkBox.validateNow(); +addChild(checkBox); +fontStyle + The style of the font.String + The style of the font. This value can be any of the values defined in the FontStyle class. + + flash.text.FontStylefontType + The type of the font.String + The type of the font. This value can be any of the constants defined in the FontType class. + + + flash.text.FontType
TextRenderer + The TextRenderer class provides functionality for the advanced anti-aliasing capability of + embedded fonts.Controls the anti-aliasing of embedded fonts. + + Object + The TextRenderer class provides functionality for the advanced anti-aliasing capability of + embedded fonts. Advanced anti-aliasing allows font faces to render at very high quality at + small sizes. Use advanced anti-aliasing with applications that have a lot of small text. Adobe does not recommend using advanced + anti-aliasing for very large fonts (larger than 48 points). + Advanced anti-aliasing is available in Flash Player 8 and later only. + +

To set advanced anti-aliasing on a text field, set the antiAliasType property of + the TextField instance.

+ +

Advanced anti-aliasing provides continuous stroke modulation (CSM), which is continuous + modulation of both stroke weight and edge sharpness. As an advanced feature, you can + use the setAdvancedAntiAliasingTable() method to define settings for specific + typefaces and font sizes.

+ +
The following example creates the TextRendererExample class + to demonstrate visual examples of advanced anti-aliasing settings with small + and large font sizes. Before testing this example, you will need to embed a + font. + If you are using Flex, embed a font in the following manner: +
  1. Place the Georgia font, named georgia.ttf in the same directory as this AS file.
  2. Add the following lines directly underneath the class definition:
  3. [Embed(source="georgia.ttf", fontFamily="Georgia")]
  4. private var embeddedFont:String;
+ If you are using Flash, embed a font in the following manner: +
  1. Place a text field on the stage and select it.
  2. In the Property Inspector, set that text field's font to Georgia
  3. In the Property Inspector, press "Embed..." and select "All"
+

Notes: +

  • You will need to compile the SWF file with "Local playback security" set to "Access local files only".
+

+ +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.*; + import flash.text.*; + + public class TextRendererExample2 extends Sprite { + + private var gutter:int = 10; + + public function TextRendererExample2() { + createTextField(8,AntiAliasType.NORMAL); + createTextField(8,AntiAliasType.ADVANCED); + createTextField(24,AntiAliasType.NORMAL); + createTextField(24,AntiAliasType.ADVANCED); + } + + private function createTextField(fontSize:Number,antiAliasType:String):TextField { + var tf:TextField = new TextField(); + tf.embedFonts = true; + tf.autoSize = TextFieldAutoSize.LEFT; + tf.antiAliasType = antiAliasType; + tf.defaultTextFormat = getTextFormat(fontSize); + tf.selectable = false; + tf.mouseEnabled = true; + tf.text = "The quick brown fox jumped over the lazy dog."; + if(numChildren > 0) { + var sibling:DisplayObject = getChildAt(numChildren - 1); + tf.y = sibling.y + sibling.height + gutter; + } + addChild(tf); + return tf; + } + + private function getTextFormat(fontSize:Number):TextFormat { + var format:TextFormat = new TextFormat(); + format.size = fontSize; + format.font = "Georgia"; + return format; + } + } +} +
flash.text.TextField.antiAliasTypesetAdvancedAntiAliasingTable + Sets a custom continuous stroke modulation (CSM) lookup table for a font.fontNameStringThe name of the font for which you are applying settings. + + fontStyleStringThe font style indicated by using one of the values from + the flash.text.FontStyle class. + + colorTypeStringThis value determines whether the stroke is dark or whether it is light. + Use one of the values from the flash.text.TextColorType class. + + advancedAntiAliasingTableArrayAn array of one or more CSMSettings objects + for the specified font. Each object contains the following properties: + +
  • fontSize
  • insideCutOff
  • outsideCutOff
+ +

The advancedAntiAliasingTable array can contain multiple entries + that specify CSM settings for different font sizes.

+ +

The fontSize is the size, in pixels, for which the settings apply.

+ +

Advanced anti-aliasing uses adaptively sampled distance fields (ADFs) to + represent the outlines that determine a glyph. Flash Player uses an outside cutoff value + (outsideCutOff), + below which densities are set to zero, and an inside cutoff value (insideCutOff), + above which densities + are set to a maximum density value (such as 255). Between these two cutoff values, + the mapping function is a linear curve ranging from zero at the outside cutoff + to the maximum density at the inside cutoff.

+ +

Adjusting the outside and inside cutoff values affects stroke weight and + edge sharpness. The spacing between these two parameters is comparable to twice the + filter radius of classic anti-aliasing methods; a narrow spacing provides a sharper edge, + while a wider spacing provides a softer, more filtered edge. When + the spacing is zero, the resulting density image is a bi-level bitmap. When the + spacing is very wide, the resulting density image has a watercolor-like edge.

+ +

Typically, users prefer sharp, high-contrast edges at small point sizes, and + softer edges for animated text and larger point sizes.

+ +

The outside cutoff typically has a negative value, and the inside cutoff typically + has a positive value, and their midpoint typically lies near zero. Adjusting these + parameters to shift the midpoint toward negative infinity increases the stroke + weight; shifting the midpoint toward positive infinity decreases the stroke weight. + Make sure that the outside cutoff value is always less than or equal to the inside cutoff value.

+ + +
+ Sets a custom continuous stroke modulation (CSM) lookup table for a font. + Flash Player attempts to detect the best CSM for your font. If you are not + satisfied with the CSM that the Flash Player provides, you can customize + your own CSM by using the setAdvancedAntiAliasingTable() method. + +
flash.text.FontStyleflash.text.TextColorTypeCSMSettings
displayMode + Controls the rendering of advanced anti-aliased text.String"default" + + Controls the rendering of advanced anti-aliased text. The visual quality of text is very subjective, and while + Flash Player tries to use the best settings for various conditions, designers may choose a different + look or feel for their text. Also, using displayMode allows a designer to override Flash + Player's subpixel choice and create visual consistency independent of the user's hardware. Use the values in the TextDisplayMode class to set this property. + + TextDisplayMode classmaxLevel + The adaptively sampled distance fields (ADFs) quality level for advanced anti-aliasing.int4 + + The adaptively sampled distance fields (ADFs) quality level for advanced anti-aliasing. The only acceptable values are + 3, 4, and 7. + +

Advanced anti-aliasing uses ADFs to + represent the outlines that determine a glyph. The higher the quality, the more + cache space is required for ADF structures. A value of 3 takes the least amount + of memory and provides the lowest quality. Larger fonts require more cache space; + at a font size of 64 pixels, the quality level increases from 3 to 4 or + from 4 to 7 unless, the level is already set to 7.

+ +
TextLineMetrics + The TextLineMetrics class contains information about the text position and measurements of a + line of text within a text field.Contains information about the text position and measurements of a line of text in a text field. + + Object + The TextLineMetrics class contains information about the text position and measurements of a + line of text within a text field. All measurements are in pixels. Objects of this class are returned by the + flash.text.TextField.getLineMetrics() method. +

For measurements related to the text field containing the line of text (for example, the "Text Field height" measurement in the diagram), see flash.text.TextField.

+ +

The following diagram indicates the points and measurements of a text field and the line of text the field contains:

+

+

+ +
The following example creates the classes TextLineMetricsExample and + LineMetricsReader to print out a message in the Flash Player via an XML object. This + is accomplished using the following steps: +
  1. Create a property called label of type TextField.
  2. The constructor calls configureAssets(), which does the following: +
    • Sets the stage's alignment to top-left and no scale.
    • Creates a new TextField object named label.
    • Enables label's background and sets the color to white.
    • Allows label's text to span multiple lines with automatic word wrapping.
    • Assigns the result of a call to getLabelText() to the text property + of label. The getLabelText() method creates a variable of type XML and assigns + it to an XML node named body, which is populated with a long sentence.
    • Adds label to the display list using addChild().
    +
  3. A method that listens for resize events performed on the stage is then added called + resizeHandler(). Every time the Flash Player window size is changed, a RESIZE + event is dispatched and the following happens: +
    • draw() is called to ensure that label appears in the center of the + stage and surrounded by a 10-pixel buffer.
    • setTimeout() then executes showMetrics() after a short delay. The + delay is added because the line metrics are not updated until after the RESIZE event has + completed and the stage has fully re-drawn.
    • showMetrics() assigns a TextLineMetrics variable named metrics to + the result of a call to getLineMetrics() and this variable is then passed to + a new instance of a LineMetricsReader instance named reader. The two + variables are then used within calls to trace() to print out the first (and only) + line of label and information provided by the LineMetricsReader instance through its + toString() method.
    +
  4. The constructor forces a single dispatch of the resize event to force + label to be drawn correctly when the SWF file is first loaded.
+ +package { + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.events.*; + import flash.text.TextField; + import flash.text.TextLineMetrics; + import flash.utils.setTimeout; + + public class TextLineMetricsExample extends Sprite { + private var gutter:int = 10; + private var label:TextField; + + public function TextLineMetricsExample() { + configureAssets(); + configureListeners(); + resizeHandler(new Event(Event.RESIZE)); + } + + private function showMetrics():void { + var metrics:TextLineMetrics = label.getLineMetrics(0); + var reader:LineMetricsReader = new LineMetricsReader(metrics); + trace("lineText: " + label.getLineText(0)); + trace("metrics: " + reader); + } + + private function configureAssets():void { + stage.align = StageAlign.TOP_LEFT; + stage.scaleMode = StageScaleMode.NO_SCALE; + + label = new TextField(); + label.background = true; + label.backgroundColor = 0xFFFFFF; + label.multiline = true; + label.wordWrap = true; + label.text = getLabelText(); + addChild(label); + } + + private function configureListeners():void { + stage.addEventListener(Event.RESIZE, resizeHandler); + } + + private function resizeHandler(event:Event):void { + draw(); + setTimeout(showMetrics, 100); + } + + private function draw():void { + label.x = gutter; + label.y = gutter; + label.width = stage.stageWidth - (gutter * 2); + label.height = stage.stageHeight - (gutter * 2); + } + + private function getLabelText():String { + var text:XML = <body>The Flex product line enables developers to build rich Internet applications that blend the responsiveness of desktop software, the cross-platform reach of the web, and the expressiveness of the Flash Platform.</body> + return text.toString(); + } + } +} + +import flash.text.TextLineMetrics; + +class LineMetricsReader { + private var metrics:TextLineMetrics; + + public function LineMetricsReader(metrics:TextLineMetrics) { + this.metrics = metrics; + } + + public function toString():String { + return "[TextLineMetrics ascent:" + metrics.ascent + + ", descent:" + metrics.descent + + ", leading:" + metrics.leading + + ", width:" + metrics.width + + ", height:" + metrics.height + + ", x:" + metrics.x + + "]"; + } +} +
flash.text.TextFieldTextLineMetrics + Creates a TextLineMetrics object.xNumberThe left position of the first character in pixels. + widthNumberThe width of the text of the selected lines (not necessarily the complete text) in pixels. + heightNumberThe height of the text of the selected lines (not necessarily the complete text) in pixels. + ascentNumberThe length from the baseline to the top of the line height in pixels. + descentNumberThe length from the baseline to the bottom depth of the line in pixels. + leadingNumberThe measurement of the vertical distance between the lines of text. + + Contains information about the text position and measurements of a line of text in a text field. + + Creates a TextLineMetrics object. The TextLineMetrics object contains information about + the text metrics of a line of text in a text field. Objects of this class are returned by the + flash.text.TextField.getLineMetrics() method. +

See the diagram in the overview for this class for the properties in context.

+ +
TextLineMetrics class overviewflash.text.TextField.getLineMetrics()
ascent + The ascent value of the text is the length from the baseline to the top of the line height in pixels.Number + The ascent value of the text is the length from the baseline to the top of the line height in pixels. See the + "Ascent" measurement in the overview diagram for this class. + + TextLineMetrics class overviewdescent + The descent value of the text is the length from the baseline to the bottom depth of the line in pixels.Number + The descent value of the text is the length from the baseline to the bottom depth of the line in pixels. + See the "Descent" measurement in the overview diagram for this class. + + TextLineMetrics class overviewheight + The height value of the text of the selected lines (not necessarily the complete text) in pixels.Number + The height value of the text of the selected lines (not necessarily the complete text) in pixels. The height of the + text line does not include the gutter height. See the "Line height" measurement in the overview diagram + for this class. + + TextLineMetrics class overviewleading + The leading value is the measurement of the vertical distance between the lines of text.Number + The leading value is the measurement of the vertical distance between the lines of text. + See the "Leading" measurement in the overview diagram for this class. + + TextLineMetrics class overviewwidth + The width value is the width of the text of the selected lines (not necessarily the complete text) in pixels.Number + The width value is the width of the text of the selected lines (not necessarily the complete text) in pixels. The width of the + text line is not the same as the width of the text field. The width of the text line is relative to the + text field width, minus the gutter width of 4 pixels (2 pixels on each side). See the "Text Line width" + measurement in the overview diagram for this class. + + TextLineMetrics class overviewx + The x value is the left position of the first character in pixels.Number + The x value is the left position of the first character in pixels. This value includes the margin, + indent (if any), and gutter widths. See the "Text Line x-position" in the overview diagram for this class. + TextLineMetrics class overview
TextInteractionMode + A class that defines the Interactive mode of a text field object.Object + A class that defines the Interactive mode of a text field object. + + + NORMAL + The text field's default interaction mode is NORMAL and it varies across platform.normalString + The text field's default interaction mode is NORMAL and it varies across platform. + On Desktop, the normal mode implies that the text field is in scrollable + selection mode. + On Mobile platforms like Android, normal mode implies that the text field can only be scrolled but + the text can not be selected. + + SELECTION + On mobile platforms like Android, the text field starts in normal mode(which implies scroll and non-selectable mode).selectionString + On mobile platforms like Android, the text field starts in normal mode(which implies scroll and non-selectable mode). + The user can switch to selection mode through the in-built context menu of the text field object. + + + StyleSheet + The StyleSheet class lets you create a StyleSheet object that contains text + formatting rules for font size, color, and other styles.Lets you create a StyleSheet object. + + flash.events:EventDispatcher + The StyleSheet class lets you create a StyleSheet object that contains text + formatting rules for font size, color, and other styles. You can then apply + styles defined by a style sheet to a TextField object that contains HTML- or + XML-formatted text. The text in the TextField object is automatically + formatted according to the tag styles defined by the StyleSheet object. + You can use text styles to define new formatting tags, redefine built-in HTML + tags, or create style classes that you can apply to certain HTML tags. + +

To apply styles to a TextField object, assign the StyleSheet + object to a TextField object's styleSheet property.

+

Note: A text field with a style sheet is not editable. In other words, a text field with the type property set to TextFieldType.INPUT applies the StyleSheet to the default text for the text field, but the content will no longer be editable by the user. Consider using the TextFormat class to assign styles to input text fields.

+ +

Flash Player supports a subset of properties in the original CSS1 specification + (www.w3.org/TR/REC-CSS1). + The following table shows the supported Cascading Style Sheet (CSS) properties and values, as well as their corresponding + ActionScript property names. (Each ActionScript property name is derived from the corresponding + CSS property name; if the name contains a hyphen, the hyphen is omitted and the subsequent character is capitalized.)

+ + CSS propertyActionScript propertyUsage and supported valuescolorcolorOnly hexadecimal color values are supported. Named colors (such as blue) + are not supported. Colors are written in the following format: #FF0000.displaydisplaySupported values are inline, block, and none.font-familyfontFamilyA comma-separated list of fonts to use, in descending order of desirability. Any font + family name can be used. If you specify a generic font name, it is converted to an + appropriate device font. The following font conversions are available: mono is + converted to _typewriter, sans-serif is converted to + _sans, and serif is converted to _serif.font-sizefontSize Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points + are equivalent.font-stylefontStyleRecognized values are normal and italic.font-weightfontWeightRecognized values are normal and bold.kerningkerningRecognized values are true and false. + Kerning is supported for embedded fonts only. Certain fonts, such as Courier New, do not support kerning. + The kerning property is only supported in SWF files created in Windows, not in SWF files created on the + Macintosh. However, these SWF files can be played in non-Windows versions of Flash Player and the kerning + still applies.leadingleadingThe amount of space that is uniformly distributed between lines. The value specifies the + number of pixels that are added after each line. A negative value condenses the space + between lines. Only the numeric part of the value is used. Units (px, pt) are not parsed; + pixels and points are equivalent.letter-spacingletterSpacingThe amount of space that is uniformly distributed between characters. + The value specifies the number of pixels that are added after each + character. A negative value condenses the space between characters. Only the numeric part of the + value is used. Units (px, pt) are not parsed; pixels and points are equivalent.margin-leftmarginLeftOnly the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points + are equivalent. margin-rightmarginRightOnly the numeric part of the value is used. Units (px, pt) are not parsed; pixels and + points are equivalent.text-aligntextAlignRecognized values are left, center, right, and + justify.text-decorationtextDecorationRecognized values are none and underline.text-indenttextIndentOnly the numeric part of the value is used. Units (px, pt) are not parsed; pixels and + points are equivalent. + +

You can use the StyleSheet class to perform low-level text rendering. + However, in Flex, you typically use the Label, Text, TextArea, and TextInput controls to process text.

+ + +
The following example creates a new style sheet and assigns bold + and red font treatments to the heading style. + + +package { + import flash.display.Sprite; + import flash.text.StyleSheet; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + + public class StyleSheetExample extends Sprite { + + public function StyleSheetExample() { + var style:StyleSheet = new StyleSheet(); + + var heading:Object = new Object(); + heading.fontWeight = "bold"; + heading.color = "#FF0000"; + + var body:Object = new Object(); + body.fontStyle = "italic"; + + style.setStyle(".heading", heading); + style.setStyle("body", body); + + var label:TextField = new TextField(); + label.styleSheet = style; + label.htmlText = "<body><span class='heading'>Hello </span>World...</body>"; + addChild(label); + } + } +} +
flash.text.TextFieldStyleSheet + Creates a new StyleSheet object. + Creates a new StyleSheet object. + + flash.text.StyleSheet.getStyle()clear + Removes all styles from the style sheet object. + Removes all styles from the style sheet object. + + getStyle + Returns a copy of the style object associated with the style named styleName.An object. + + ObjectstyleNameStringA string that specifies the name of the style to retrieve. + + + Returns a copy of the style object associated with the style named styleName. + If there is no style object associated with styleName, + null is returned. + + Please see the parseCSS() or transform() + method's example for illustrations of how to use the getStyle() method. + + flash.text.StyleSheet.setStyle()parseCSS + Parses the CSS in CSSText and loads the style sheet with it.CSSTextStringThe CSS text to parse (a string). + + Parses the CSS in cssText and loads the StyleSheet with it. + + + Parses the CSS in CSSText and loads the style sheet with it. If a style in + CSSText is already in styleSheet, the properties in + styleSheet are retained, and only the ones in CSSText + are added or changed in styleSheet. + +

To extend the native CSS parsing capability, you can override this method by creating a subclass + of the StyleSheet class.

+ +
In the following example, when a user clicks on the text file, + CSS styles, loaded from a file, are applied to the content. + +

In the constructor, a multiline text field is created and its content is + set to an HTML-formatted string. (The HTML heading and span tags are + not rendered before CSS style is applied.) A URLRequest + object is created to identify the location of the CSS file; for this example, the CSS file + is in the same directory as the SWF file. The file is loaded with a URLLoader + object. There are two event listeners added for the loader URLLoader object. + If an IO error occurs, the errorHandler() method is invoked, which displays + an error message in the text field. After all the data is received and placed in the data + property of the loader URLLoader object, the loaderCompleteHandler() + method is invoked. This method parses the CSS styles from the data loaded from the file and + fills the sheet StyleSheet object with the style definitions.

+ +

When the user clicks on the text field, the clickHandler() method is called. + The if statement in the clickHandler() method checks to make sure the file loading + was finished before applying the style sheet to the text field. In order for the style sheet to + take effect, the htmlText property must be reassigned with the content after the + style sheet is assigned to the text field. The CSS font-family and the color + property values for the heading tag also are appended to the content of the text field. (The values + of these properties will be "undefined" if style sheet values are not in effect.)

+ +

The following is an example of a content of the CSS file that can be used with this example. + Before running this example, create a text file, copy the following CSS content into it, + then save it with the file name test.css and place it in the same directory as the SWF file.

+ +
+   p {
+      font-family: Times New Roman, Times, _serif;
+      font-size: 14;
+       font-Style: italic;
+        margin-left: 10;  
+   }
+   h1 {
+      font-family: Arial, Helvetica, _sans;
+      font-size: 20;
+      font-weight: bold;
+   }
+   .bluetext {
+      color: #0000CC;
+   }
+ 
+ +package { + import flash.display.Sprite; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.text.StyleSheet; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.events.IOErrorEvent; + import flash.events.Event; + import flash.events.MouseEvent; + + public class StyleSheet_parseCSSExample extends Sprite { + private var loader:URLLoader = new URLLoader(); + private var field:TextField = new TextField(); + private var exampleText:String = "<h1>This is a headline</h1>" + + "<p>This is a line of text. <span class='bluetext'>" + + "This line of text is colored blue.</span></p>"; + private var sheet:StyleSheet = new StyleSheet(); + private var cssReady:Boolean = false; + + public function StyleSheet_parseCSSExample() { + field.x = 10; + field.y = 10; + field.background = true; + field.multiline = true; + field.autoSize = TextFieldAutoSize.LEFT; + field.htmlText = exampleText; + + field.addEventListener(MouseEvent.CLICK, clickHandler); + + addChild(field); + + var req:URLRequest = new URLRequest("test.css"); + loader.load(req); + + loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + loader.addEventListener(Event.COMPLETE, loaderCompleteHandler); + } + + public function errorHandler(e:IOErrorEvent):void { + field.htmlText = "Couldn't load the style sheet file."; + } + + public function loaderCompleteHandler(event:Event):void { + sheet.parseCSS(loader.data); + cssReady = true; + } + + public function clickHandler(e:MouseEvent):void { + + if (cssReady) { + field.styleSheet = sheet; + field.htmlText = exampleText; + + var style:Object = sheet.getStyle("h1"); + field.htmlText += "<p>Headline font-family is: " + style.fontFamily + "</p>"; + field.htmlText += "<p>Headline color is: " + style.color + "</p>"; + + } else { + field.htmlText = "Couldn't apply the CSS styles."; + } + } + } +} +
setStyle + Adds a new style with the specified name to the style sheet object.styleNameStringA string that specifies the name of the style to add to the style sheet. + + styleObjectObjectAn object that describes the style, or null. + + + Adds a new style with the specified name to the style sheet object. + If the named style does not already exist in the style sheet, it is added. + If the named style already exists in the style sheet, it is replaced. + If the styleObject parameter is null, the named style is removed. + +

Flash Player creates a copy of the style object that you pass to this method.

+ +

For a list of supported styles, see the table in the description for the StyleSheet class.

+ +
transform + Extends the CSS parsing capability.A TextFormat object containing the result of the mapping of CSS rules + to text format properties. + + flash.text:TextFormatformatObjectObjectAn object that describes the style, containing style rules as properties of the object, + or null. + + + Extends the CSS parsing capability. Advanced developers can override this method by extending the + StyleSheet class. + + This example uses the transform() method to apply a style + from a CSS file to a TextFormat object for a text field. + +

CSS styles are used usually to format HTML content. However, + by using transform() method of a StyleSheet object, specific + CSS styles can be assigned to a TextFormat object and then applied to any text field.

+ +

The URLRequest and URLLoader objects are used to + load the CSS file. An event listener is added for the Event.COMPLETE + event, which occurs after all the data is received and placed in the data property of the + loader URLLoader object. The loaderCompleteHandler() method + then parses the CSS from the data loaded from the file and fills the sheet + StyleSheet object with the styles. The getStyle() method of the style sheet + retrieves the HTML paragraph styles, which are then assigned to the cssFormat + TextFormat object by using style sheet's transform() method. Finally, the default text + format of the inputField text field is set to the new cssFormat text format.

+ + +package { + import flash.display.Sprite; + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.text.StyleSheet; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.text.TextFieldType; + import flash.events.IOErrorEvent; + import flash.events.Event; + + public class StyleSheet_transformExample extends Sprite { + private var loader:URLLoader = new URLLoader(); + private var inputField:TextField = new TextField(); + private var sheet:StyleSheet = new StyleSheet(); + + public function StyleSheet_transformExample() { + inputField.x = 10; + inputField.y = 10; + inputField.background = true; + inputField.width = 300; + inputField.height = 200; + inputField.wordWrap = true; + inputField.multiline = true; + inputField.type = TextFieldType.INPUT; + + addChild(inputField); + + var req:URLRequest = new URLRequest("test.css"); + loader.load(req); + + loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); + loader.addEventListener(Event.COMPLETE, loaderCompleteHandler); + } + + public function errorHandler(e:IOErrorEvent):void { + inputField.htmlText = "Couldn't load the style sheet file."; + } + + public function loaderCompleteHandler(event:Event):void { + var cssFormat:TextFormat = new TextFormat(); + sheet.parseCSS(loader.data); + var style:Object = sheet.getStyle("p"); + cssFormat = sheet.transform(style); + inputField.defaultTextFormat = cssFormat; + } + } +} +
flash.text.TextFormat
styleNames + An array that contains the names (as strings) of all of the styles registered + in this style sheet.ArrayReturns the names of all the styles registered in this StyleSheet. + + + An array that contains the names (as strings) of all of the styles registered + in this style sheet. + +
TextSnapshot + TextSnapshot objects let you work with static text in a movie clip.Object + TextSnapshot objects let you work with static text in a movie clip. You can use them, for example, + to lay out text with greater precision than that allowed by dynamic text, but still access the text + in a read-only way. + +

You don't use a constructor to create a TextSnapshot object; it is returned by + flash.display.DisplayObjectContainer.textSnapshot property.

+ + +
flash.display.DisplayObjectContainer.textSnapshotfindText + Searches the specified TextSnapshot object and returns the position of the first + occurrence of textToFind found at or after beginIndex.The zero-based index position of the first occurrence of the specified text, or -1. + + intbeginIndexintSpecifies the starting point to search for the specified text. + + textToFindStringSpecifies the text to search for. If you specify a string literal instead of a + variable of type String, enclose the string in quotation marks. + + caseSensitiveBooleanSpecifies whether the text must match the case of the string in + textToFind. + + + Searches the specified TextSnapshot object and returns the position of the first + occurrence of textToFind found at or after beginIndex. If + textToFind is not found, the method returns -1. + + flash.text.TextSnapshot.getText()getSelectedText + Returns a string that contains all the characters specified by the corresponding + setSelected() method.A string that contains all the characters specified by the + corresponding setSelected() command. + + StringincludeLineEndingsBooleanfalseAn optional Boolean value that specifies + whether newline characters are inserted into the returned string where + appropriate. The default value is false. + + + Returns a string that contains all the characters specified by the corresponding + setSelected() method. If no characters are specified (by the + setSelected() method), an empty string is returned. + +

If you pass true for includeLineEndings, + newline characters are inserted in the return string, and + the return string might be longer than the input range. If + includeLineEndings is false or omitted, the method returns + the selected text without adding any characters.

+ +
flash.text.TextSnapshot.getSelected()flash.text.TextSnapshot.setSelected()
getSelected + Returns a Boolean value that specifies whether a TextSnapshot object contains selected text in + the specified range.A Boolean value that indicates whether at least one character in the given range has been + selected by the corresponding setSelected() method (true); otherwise, + false. + + BooleanbeginIndexintIndicates the position of the first character to be examined. + Valid values for beginIndex are 0 through + TextSnapshot.charCount - 1. If beginIndex is a negative value, + 0 is used. + + endIndexintA value that is one greater than the index of the last character to be examined. Valid values + for endIndex are 0 through charCount. + The character indexed by the endIndex parameter is not included in the extracted + string. If this parameter is omitted, charCount is used. If this value is less than + or equal to the value of beginIndex, beginIndex + 1 is used. + + + Returns a Boolean value that specifies whether a TextSnapshot object contains selected text in + the specified range. + +

To search all characters, pass a value of 0 for start, and + charCount (or any very large number) for end. + To search a single character, pass the end parameter a value that is one greater + than the start parameter.

+ +
flash.text.TextSnapshot.charCountflash.text.TextSnapshot.getText()flash.text.TextSnapshot.getSelectedText()flash.text.TextSnapshot.setSelected()
getTextRunInfo + Returns an array of objects that contains information about a run of text.An array of objects in which each object contains information about a specific character + in the range of characters specified by the beginIndex and endIndex parameters. + Each object contains the following eleven properties: +
  • indexInRun—A zero-based integer index of the character + (relative to the entire string rather than the selected run of text).
  • selected—A Boolean value that indicates whether the character is selected + true; false otherwise.
  • font—The name of the character's font.
  • color—The combined alpha and color value of the character. + The first two hexadecimal digits represent the alpha value, and the remaining digits + represent the color value.
  • height—The height of the character, in pixels.
  • matrix_a, matrix_b, matrix_c, + matrix_d, matrix_tx, and matrix_ty— + The values of a matrix that define the geometric transformation on the character. + Normal, upright text always has a matrix of the form + [1 0 0 1 x y], where x and y + are the position of the character within the parent movie clip, regardless of the height of + the text. The matrix is in the parent movie clip coordinate system, and + does not include any transformations that may be on that movie clip itself (or its parent).
  • corner0x, corner0y, corner1x, corner1y, + corner2x, corner2y, corner3x, + and corner3y—The corners of the bounding box of + the character, based on the coordinate system of the parent movie clip. + These values are only available if the font used by the character is embedded in the + SWF file.
+ +
Array
beginIndexintThe index value of the first character in a range of characters in a TextSnapshot + object. + + endIndexintThe index value of the last character in a range of characters in a TextSnapshot + object. + +
+ Returns an array of objects that contains information about a run of text. Each object corresponds + to one character in the range of characters specified by the two method parameters. + +

Note: Using the getTextRunInfo() method for a large range of text can + return a large object. Adobe recommends limiting the text range defined by the + beginIndex and endIndex parameters.

+ +
Matrix class
getText + Returns a string that contains all the characters specified by the beginIndex + and endIndex parameters.A string containing the characters in the specified range, or an empty string if no + characters are found in the specified range. + + StringbeginIndexintIndicates the position of the first character to be included in the + returned string. Valid values for beginIndex are0 through + charCount - 1. If beginIndex is a negative value, + 0 is used. + + endIndexintA value that is one greater than the index of the last character to be examined. Valid values + for endIndex are 0 through charCount. The character + indexed by the endIndex parameter is not included in the extracted string. If this + parameter is omitted, charCount is used. If this value is less than or + equal to the value of beginIndex, beginIndex + 1 is used. + + includeLineEndingsBooleanfalseAn optional Boolean value that specifies whether newline characters + are inserted (true) or are not inserted (false) into the returned string. + The default value is false. + + + Returns a string that contains all the characters specified by the beginIndex + and endIndex parameters. If no characters are selected, an empty string is + returned. + +

To return all characters, pass a value of 0 for beginIndex and + charCount (or any very large number) for endIndex. + To return a single character, pass a value of beginIndex + 1 for endIndex.

+ +

If you pass a value of true for includeLineEndings, + newline characters are inserted in the string returned where deemed appropriate. In this case, + the return string might be longer than the input range. If includeLineEndings + is false or omitted, the selected text is returned without any characters added.

+ +
flash.text.TextSnapshot.charCountflash.text.TextSnapshot.getSelectedText()
hitTestTextNearPos + Lets you determine which character within a TextSnapshot object is on or near the specified + x, y coordinates of the movie clip containing the text in the TextSnapshot object.A number representing the index value of the character that is nearest to the specified + x, y coordinate. Returns + -1 if no character is found, or if the font doesn't contain character metric information. + + NumberxNumberA number that represents the x coordinate of the movie clip containing the + text. + + yNumberA number that represents the y coordinate of the movie clip containing the + text. + + maxDistanceNumber0An optional number that represents the maximum distance from + x, y that can be searched for + text. The distance is measured from the center point of each character. The + default value is 0. + + + Lets you determine which character within a TextSnapshot object is on or near the specified + x, y coordinates of the movie clip containing the text in the TextSnapshot object. + +

If you omit or pass a value of 0 for maxDistance, the location specified + by the x, y coordinates must lie inside the bounding box of the TextSnapshot object. +

+ +

This method works correctly only with fonts that include character metric information; however, + by default, the Flash authoring tool does not include this information for static text fields. + Therefore, + the method might return -1 instead of an index value. To ensure that an index + value is returned, you can force the Flash authoring tool to include the character metric + information for a font. To do this, add a dynamic text field that uses that font, select + Character Options for that dynamic text field, and then specify that font outlines should be + embedded for at least one character. (It doesn't matter which characters you specify, nor + whether they are the characters used in the static text fields.)

+ +
flash.display.DisplayObject.xflash.display.DisplayObject.y
setSelectColor + Specifies the color to use when highlighting characters that have been selected with the + setSelected() method.hexColoruint0xFFFF00The color used for the border placed around characters that have been selected by the + corresponding setSelected() command, expressed in hexadecimal + format (0xRRGGBB). + + + Specifies the color to use when highlighting characters that have been selected with the + setSelected() method. The color is always opaque; you can't specify a + transparency value. + +

This method works correctly only with fonts that include character metric information; however, + by default, the Flash authoring tool does not include this information for static text fields. + Therefore, the method might return -1 instead of an index value. To + ensure that an index value is returned, you can force the Flash authoring tool to include the + character metric information for a font. To do this, add a dynamic text field that uses that + font, select Character Options for that dynamic text field, and then specify that font outlines + should be embedded for at least one character. (It doesn't matter which characters you + specify, nor if they are the characters used in the static text fields.)

+
flash.text.TextSnapshot.setSelected()
setSelected + Specifies a range of characters in a TextSnapshot object to be selected or deselected.beginIndexintIndicates the position of the first character to select. + Valid values for beginIndex are 0 through charCount - 1. + If beginIndex is a negative value, 0 is used. + + endIndexintAn integer that is 1+ the index of the last character to be + examined. Valid values for end are 0 through charCount. + The character indexed by the end parameter is not included in the extracted + string. If you omit this parameter, TextSnapshot.charCount is used. If the + value of beginIndex is less than or equal to the value of endIndex, + beginIndex + 1 is used. + + selectBooleanA Boolean value that specifies whether the text should be selected (true) + or deselected (false). + + + Specifies a range of characters in a TextSnapshot object to be selected or deselected. + Characters that are selected are drawn with a colored rectangle behind them, matching the + bounding box of the character. The color of the bounding box is defined by + setSelectColor(). + +

To select or deselect all characters, pass a value of 0 for beginIndex and + charCount (or any very large number) for endIndex. To + specify a single character, pass a value of start + 1 for endIndex.

+ +

Because characters are individually marked as selected, you can call this method multiple + times to select multiple characters; that is, using this method does not deselect other + characters that have been set by this method.

+ +

The colored rectangle that indicates a selection is displayed only for fonts that include + character metric information; by default, Flash does not include this information for static + text fields. In some cases, this behavior means that text that is selected won't appear to be + selected onscreen. To ensure that all selected text appears to be + selected, you can force the Flash authoring tool to include the character metric information + for a font. To do this, add a dynamic text field that uses that font, select Character Options + for that dynamic text field, and then specify that font outlines should be embedded for at least + one character. It doesn't matter which characters you specify, nor even if they are the + characters used in the static text fields in question.

+ +
flash.text.TextSnapshot.charCountflash.text.TextSnapshot.setSelectColor()
charCount + The number of characters in a TextSnapshot object.int + The number of characters in a TextSnapshot object. + + flash.text.TextSnapshot.getText()
TextFieldAutoSize +The TextFieldAutoSize class is an enumeration of constant values used in setting the autoSize +property of the TextField class.Object +The TextFieldAutoSize class is an enumeration of constant values used in setting the autoSize +property of the TextField class. + +flash.text.TextField.autoSizeCENTER + Specifies that the text is to be treated as center-justified text.centerString + Specifies that the text is to be treated as center-justified text. + Any resizing of a single line of a text field is equally distributed + to both the right and left sides. + + LEFT + Specifies that the text is to be treated as left-justified text, + meaning that the left side of the text field remains fixed and any + resizing of a single line is on the right side.leftString + Specifies that the text is to be treated as left-justified text, + meaning that the left side of the text field remains fixed and any + resizing of a single line is on the right side. + + NONE + + Specifies that no resizing is to occur.noneString + + Specifies that no resizing is to occur. + + RIGHT + Specifies that the text is to be treated as right-justified text, + meaning that the right side of the text field remains fixed and any + resizing of a single line is on the left side.rightString + Specifies that the text is to be treated as right-justified text, + meaning that the right side of the text field remains fixed and any + resizing of a single line is on the left side. + + TextFieldType +The TextFieldType class is an enumeration of constant values used in setting the type property +of the TextField class.Object +The TextFieldType class is an enumeration of constant values used in setting the type property +of the TextField class. + + +flash.text.TextField.typeDYNAMIC + Used to specify a dynamic TextField.dynamicString + Used to specify a dynamic TextField. + + INPUT + Used to specify an input TextField.inputString + Used to specify an input TextField. + + FontStyle +The FontStyle class provides values for the TextRenderer class.Object +The FontStyle class provides values for the TextRenderer class. + +flash.text.TextRendererBOLD_ITALIC + Defines the combined bold and italic style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method.boldItalicString + Defines the combined bold and italic style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method. Use the syntax FontStyle.BOLD_ITALIC. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()BOLD + Defines the bold style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method.Bob Pappas + boldString + Defines the bold style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method. Use the syntax FontStyle.BOLD. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()ITALIC + Defines the italic style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method.italicString + Defines the italic style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method. Use the syntax FontStyle.ITALIC. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()REGULAR + Defines the plain style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method.Bob Pappas + regularString + Defines the plain style of a font for the fontStyle parameter in the setAdvancedAntiAliasingTable() method. Use the syntax FontStyle.REGULAR. + flash.text.TextRenderer.setAdvancedAntiAliasingTable()
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.ui.xml b/language-server/playerglobal_docs/flash.ui.xml new file mode 100644 index 0000000..5adda2a --- /dev/null +++ b/language-server/playerglobal_docs/flash.ui.xml @@ -0,0 +1,2642 @@ +flash.uiMouseCursorData + + The MouseCursorData class lets you define the appearance of a "native" mouse cursor.Defines a custom mouse cursor. + Object + The MouseCursorData class lets you define the appearance of a "native" mouse cursor. + +

To display the cursor, use the Mouse.registerCursor() function. To return + control of the cursor image to the operating system, call Mouse.unregisterCursor(). + Call Mouse.supportsNativeCursor to test whether native cursors are supported on the + current computer.

+ +

The maximum cursor size is 32x32 pixels.Transparency is supported on most operating systems.

+ +

A native mouse cursor is implemented directly through the operating system cursor mechanism + and is a more efficient means for displaying a custom cursor image than using a display object. + You can animate the cursor by supplying more than one image in the data property + and setting the frame rate.

+ +

The cursor is only displayed within the bounds of the stage. Outside the stage, control of the + cursor image returns to the operating system

+ +
The following example creates and displays a spinning arrow for the mouse cursor. + +

The example uses the drawing commands available through the Graphics class to create + eight, rotated images of an arrow. These images are pushed into a vector and assigned to the data + property of the MouseCursorData object. (Note that you can also use prerendered bitmap images for your cursors.)

+ +package { + + import flash.display.Sprite; + import flash.display.Shape; + import flash.display.BitmapData; + import flash.display.GraphicsPath; + import flash.ui.MouseCursorData; + import flash.ui.Mouse; + import flash.geom.Matrix; + + public class MouseCursorDataExample extends Sprite { + //Graphics path data for an arrow + private var cursorPoints:Vector.<Number> = new <Number>[0,8, 16,8, 16,0, 24,12, 16,24, 16,16, 0,16, 0,8]; + private var cursorDrawCommands:Vector.<int> = new <int>[1,2,2,2,2,2,2,2]; + + public function MouseCursorDataExample() { + var mouseCursorData:MouseCursorData = new MouseCursorData(); + mouseCursorData.data = makeCursorImages(); + mouseCursorData.frameRate = 1; + + Mouse.registerCursor( "spinningArrow", mouseCursorData ); + Mouse.cursor = "spinningArrow"; + } + + //Returns a Vector containing 8 cursor images + private function makeCursorImages():Vector.<BitmapData> + { + var cursorData:Vector.<BitmapData> = new Vector.<BitmapData>(); + + var cursorShape:Shape = new Shape(); + cursorShape.graphics.beginFill( 0xff5555, .75 ); + cursorShape.graphics.lineStyle( 1 ); + cursorShape.graphics.drawPath( cursorDrawCommands, cursorPoints ); + cursorShape.graphics.endFill(); + var transformer:Matrix = new Matrix(); + + //Rotate and draw the arrow shape to a BitmapData object for each of 8 frames + for( var i:int = 0; i < 8; i++ ) + { + var cursorFrame:BitmapData = new BitmapData( 32, 32, true, 0 ); + cursorFrame.draw( cursorShape, transformer ); + cursorData.push( cursorFrame ); + + transformer.translate(-15,-15); + transformer.rotate( 0.785398163 ); + transformer.translate(15,15); + } + return cursorData; + } + } + +} +
flash.ui.Mouse.cursorAIR Cookbook: Native Mouse cursor for Flash Player 10.2+MouseCursorData + Creates a MouseCursorData object.Constructor. + + Creates a MouseCursorData object. + +

To display the cursor, call the Mouse.registerCursor() function.

+ +
flash.ui.Mouse.registerCursor()
data + A Vector of BitmapData objects containing the cursor image or images.The mouse cursor image or images. + + + A Vector of BitmapData objects containing the cursor image or images. + +

Supply more than one image and set the framerate property to + animate the cursor.

+ +

The maximum cursor size is 32x32 pixels.

+ +
frameRate + The frame rate for animating the cursor.NumberThe mouse frame rate. + + + The frame rate for animating the cursor. + +

Suppy more than one image in the data property and set the + frame rate to a value greater than 0 to animate the cursor. The cursor frame rate + may differ from the current SWF frame rate.

+ +
hotSpot + The hot spot of the cursor in pixels.flash.geom:PointThe cursor hot spot. + + + The hot spot of the cursor in pixels. + +

The hotspot is the point on the cursor under which mouse clicks are registered. + By default, the hot spot is the upper-left corner (0,0).

+ +
ContextMenuBuiltInItems +The ContextMenuBuiltInItems class describes the items that are built in to a context menu.Object +The ContextMenuBuiltInItems class describes the items that are built in to a context menu. +You can hide these items by using the ContextMenu.hideBuiltInItems() method. + The following example uses the class ContextMenuBuiltInItemsExample + to remove the normal context menu items from the stage and add a new menu item. This is + accomplished with the following steps: +
  1. A property myContextMenu is declared and then assigned to a new ContextMenu + object.
  2. The method removeDefaultItems() is called, which removes all built-in context + menu items except Print.
  3. The method addCustomMenuItems() is called, which places a menu item called + Hello World into the customItems array using the + push() method of Array.
  4. The Hello World menu item is then added to the Stage's context + menu item list.
  5. A TextField object with the text "Right Click" is added to the center of the Stage + by using addChild() via createLabel().
+ +package { + import flash.ui.ContextMenu; + import flash.ui.ContextMenuItem; + import flash.ui.ContextMenuBuiltInItems; + import flash.display.Sprite; + import flash.text.TextField; + + public class ContextMenuBuiltInItemsExample extends Sprite { + private var myContextMenu:ContextMenu; + + public function ContextMenuBuiltInItemsExample() { + myContextMenu = new ContextMenu(); + removeDefaultItems(); + addCustomMenuItems(); + this.contextMenu = myContextMenu; + addChild(createLabel()); + } + + private function removeDefaultItems():void { + myContextMenu.hideBuiltInItems(); + + var defaultItems:ContextMenuBuiltInItems = myContextMenu.builtInItems; + defaultItems.print = true; + } + + private function addCustomMenuItems():void { + var item:ContextMenuItem = new ContextMenuItem("Hello World"); + myContextMenu.customItems.push(item); + } + + private function createLabel():TextField { + var txtField:TextField = new TextField(); + txtField.text = "Right Click"; + txtField.x = this.stage.stageWidth/2 - txtField.width/2; + txtField.y = this.stage.stageHeight/2 - txtField.height/2; + return txtField; + } + } +} +
ContextMenu.hideBuiltInItems()ContextMenuBuiltInItems +Creates a new ContextMenuBuiltInItems object so that you can set the properties for Flash Player to display or hide each menu item. +Creates a new ContextMenuBuiltInItems object so that you can set the properties for Flash Player to display or hide each menu item. +forwardAndBack +Lets the user move forward or backward one frame in a SWF file at run time (does not +appear for a single-frame SWF file).Boolean +Lets the user move forward or backward one frame in a SWF file at run time (does not +appear for a single-frame SWF file). +loop +Lets the user set a SWF file to start over automatically when it reaches the final +frame (does not appear for a single-frame SWF file).Boolean +Lets the user set a SWF file to start over automatically when it reaches the final +frame (does not appear for a single-frame SWF file). +play +Lets the user start a paused SWF file (does not appear for a single-frame SWF file).Boolean +Lets the user start a paused SWF file (does not appear for a single-frame SWF file). +print +Lets the user send the displayed frame image to a printer.Boolean +Lets the user send the displayed frame image to a printer. +quality +Lets the user set the resolution of the SWF file at run time.Boolean +Lets the user set the resolution of the SWF file at run time. +rewind +Lets the user set a SWF file to play from the first frame when selected, at any time (does not +appear for a single-frame SWF file).Boolean +Lets the user set a SWF file to play from the first frame when selected, at any time (does not +appear for a single-frame SWF file). +save +Lets the user with Shockmachine installed save a SWF file.Boolean +Lets the user with Shockmachine installed save a SWF file. +zoom +Lets the user zoom in and out on a SWF file at run time.Boolean +Lets the user zoom in and out on a SWF file at run time. +
MouseCursor +The MouseCursor class is an enumeration of constant values used in setting the cursor property +of the Mouse class.Object +The MouseCursor class is an enumeration of constant values used in setting the cursor property +of the Mouse class. + + +flash.ui.Mouse.cursorARROW + Used to specify that the arrow cursor should be used.arrowString + Used to specify that the arrow cursor should be used. + + AUTO + Used to specify that the cursor should be selected automatically based on the object under the mouse.autoString + Used to specify that the cursor should be selected automatically based on the object under the mouse. + + BUTTON + Used to specify that the button pressing hand cursor should be used.buttonString + Used to specify that the button pressing hand cursor should be used. + + HAND + Used to specify that the dragging hand cursor should be used.handString + Used to specify that the dragging hand cursor should be used. + + IBEAM + Used to specify that the I-beam cursor should be used.ibeamString + Used to specify that the I-beam cursor should be used. + + MultitouchInputMode + The MultitouchInputMode class provides values for the inputMode property in the flash.ui.Multitouch class.Object + The MultitouchInputMode class provides values for the inputMode property in the flash.ui.Multitouch class. + These values set the type of touch events the Flash runtime dispatches when the user interacts with a touch-enabled device. + + The following example displays a message when the + square drawn on mySprite is tapped on a touch-enabled screen: + +Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +var myTextField:TextField = new TextField(); + +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); + +function taphandler(e:TouchEvent): void { + myTextField.text = "I've been tapped"; + myTextField.y = 50; + addChild(myTextField); +} +flash.ui.Multitouch.inputModeGESTURE + Specifies that TransformGestureEvent, PressAndTapGestureEvent, and GestureEvent events are dispatched for the related user interaction supported by the current environment, + and other touch events (such as a simple tap) are interpreted as mouse events.gestureString + Specifies that TransformGestureEvent, PressAndTapGestureEvent, and GestureEvent events are dispatched for the related user interaction supported by the current environment, + and other touch events (such as a simple tap) are interpreted as mouse events. + + flash.ui.Multitouch.inputModeflash.events.TransformGestureEventflash.events.GestureEventflash.events.PressAndTapGestureEventflash.events.TouchEventNONE + Specifies that all user contact with a touch-enabled device is interpreted as a type of mouse event.noneString + Specifies that all user contact with a touch-enabled device is interpreted as a type of mouse event. + + flash.ui.Multitouch.inputModeflash.events.MouseEventTOUCH_POINT + Specifies that events are dispatched only for basic touch events, such as a single finger tap.touchPointString + Specifies that events are dispatched only for basic touch events, such as a single finger tap. When you use this setting, + events listed in the TouchEvent class are dispatched; events listed in the TransformGestureEvent, PressAndTapGestureEvent, and GestureEvent classes are not dispatched. + + flash.ui.Multitouch.inputModeflash.events.TransformGestureEventflash.events.GestureEventflash.events.PressAndTapGestureEventflash.events.TouchEventContextMenu + The ContextMenu class provides control over the items displayed in context menus.flash.display:NativeMenu + The ContextMenu class provides control over the items displayed in context menus. + +

Mobile Browser Support: This class is not supported in mobile browsers.

+ +

AIR profile support: This feature is not supported + on mobile devices or AIR for TV devices. See + + AIR Profile Support for more information regarding API support across multiple profiles.

+ +

In Flash Player, users open the context menu by right-clicking (Windows or Linux) or Control-clicking + (Macintosh) Flash Player. You can use the methods and properties of the ContextMenu class to + add custom menu items, control the display of the built-in context menu items (for example, Zoom In, + and Print), or create copies of menus. In AIR, there are no built-in items and no standard context menu.

+ +

In Flash Professional, you can attach a ContextMenu object to a specific button, movie clip, or text + field object, or to an entire movie level. You use the contextMenu property of the InteractiveObject + class to do this.

+ +

In Flex or Flash Builder, only top-level components in the application can have context menus. + For example, if a DataGrid control is a child of a TabNavigator or VBox container, the DataGrid control + cannot have its own context menu.

+ +

To add new items to a ContextMenu object, you create a ContextMenuItem object, and then add that + object to the ContextMenu.customItems array. For more information about creating context + menu items, see the ContextMenuItem class entry.

+ +

Flash Player has three types of context menus: the standard menu (which appears when you right-click + in Flash Player), the edit menu (which appears when you right-click a selectable or editable text + field), and an error menu (which appears when a SWF file has failed to load into Flash Player). Only the + standard and edit menus can be modified with the ContextMenu class. Only the edit menu appears in AIR.

+ +

Custom menu items always appear at the top of the Flash Player context menu, above any visible + built-in menu items; a separator bar distinguishes built-in and custom menu items. You cannot remove the + Settings menu item from the context menu. + The Settings menu item is required in Flash so that users can access the settings that affect privacy and + storage on their computers. You also cannot remove the About menu item, which is + required so that users can find out what version of Flash Player they are using. (In AIR, the built-in + Settings and About menu items are not used.)

+ +

You can add no more than 15 custom items to a context menu in Flash Player. In AIR, there is no explicit + limit imposed on the number of items in a context menu.

+ +

You must use the ContextMenu() constructor to create a ContextMenu object before + calling its methods.

+ +
The following example uses the class ContextMenuExample + to remove the default context menu items from the Stage and add a new menu item, which, if + clicked, changes the color of a square on the Stage. This is accomplished with the following + steps: +
  1. A property myContextMenu is declared and then assigned to a new ContextMenu + object and a property redRectangle of type Sprite is declared.
  2. The method removeDefaultItems() is called, which removes all built-in context + menu items except Print.
  3. The method addCustomMenuItems() is called, which places a menu item called + Red to Black menu selection into the defaultItems array by using the + push() method of Array. A menuItemSelect event listener is added to the + ContextMenuItem object and the associated method is called menuItemSelectHandler(). + This method prints out some statements using trace() whenever the + context menu is accessed and Red to Black is selected. Also the red square + is removed and replaced with a black one.
  4. An event listener of type menuSelect is added, along with + the associated method menuSelectHandler, which simply prints out three statements using + trace() every time an item in the context menu is opened.
  5. Then addChildren() draws a red square and adds it + to the display list, where it is immediately displayed.
  6. Finally, myContextMenu is assigned to the context menu of the redRectangle sprite + so that the custom context menu is displayed only when the mouse pointer is over the square.
+ +package { + import flash.ui.ContextMenu; + import flash.ui.ContextMenuItem; + import flash.ui.ContextMenuBuiltInItems; + import flash.events.ContextMenuEvent; + import flash.display.Sprite; + import flash.display.Shape; + import flash.text.TextField; + + public class ContextMenuExample extends Sprite { + private var myContextMenu:ContextMenu; + private var menuLabel:String = "Reverse Colors"; + private var textLabel:String = "Right Click"; + private var redRectangle:Sprite; + private var label:TextField; + private var size:uint = 100; + private var black:uint = 0x000000; + private var red:uint = 0xFF0000; + + public function ContextMenuExample() { + myContextMenu = new ContextMenu(); + removeDefaultItems(); + addCustomMenuItems(); + myContextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, menuSelectHandler); + + addChildren(); + redRectangle.contextMenu = myContextMenu; + } + + private function addChildren():void { + redRectangle = new Sprite(); + redRectangle.graphics.beginFill(red); + redRectangle.graphics.drawRect(0, 0, size, size); + addChild(redRectangle); + redRectangle.x = size; + redRectangle.y = size; + label = createLabel(); + redRectangle.addChild(label); + } + + private function removeDefaultItems():void { + myContextMenu.hideBuiltInItems(); + var defaultItems:ContextMenuBuiltInItems = myContextMenu.builtInItems; + defaultItems.print = true; + } + + private function addCustomMenuItems():void { + var item:ContextMenuItem = new ContextMenuItem(menuLabel); + myContextMenu.customItems.push(item); + item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelectHandler); + } + + private function menuSelectHandler(event:ContextMenuEvent):void { + trace("menuSelectHandler: " + event); + } + + private function menuItemSelectHandler(event:ContextMenuEvent):void { + trace("menuItemSelectHandler: " + event); + var textColor:uint = (label.textColor == black) ? red : black; + var bgColor:uint = (label.textColor == black) ? black : red; + redRectangle.graphics.clear(); + redRectangle.graphics.beginFill(bgColor); + redRectangle.graphics.drawRect(0, 0, size, size); + label.textColor = textColor; + } + + private function createLabel():TextField { + var txtField:TextField = new TextField(); + txtField.text = textLabel; + return txtField; + } + } +} +
ContextMenuItem classflash.display.InteractiveObject.contextMenumenuSelect + Dispatched when a user first generates a + context menu but before the contents of the context menu are displayed.flash.events.ContextMenuEvent.MENU_SELECTflash.events.ContextMenuEvent + Dispatched when a user first generates a + context menu but before the contents of the context menu are displayed. This allows your + program to modify the set of context menu items before + displaying the menu. The user generates + the context menu by right-clicking the pointing device. + ContextMenu + Creates a ContextMenu object. + Creates a ContextMenu object. + + ContextMenu.customItemsContextMenu.hideBuiltInItems()addItemAt + Adds a menu item at the bottom of the menu.If item is null. + ArgumentErrorArgumentErrorIf item is a member of another menu. + + ArgumentErrorArgumentErrorflash.display:NativeMenuItemitemflash.display:NativeMenuItemThe item to add at the bottom of the menu. + indexint + Adds a menu item at the bottom of the menu. + +

When creating a context menu, you can add either NativeMenuItem or + ContextMenuItem objects. However, it is advisable to use only one type of object in a context + menu so that all items in the menu have the same properties.

+ +
clone + + + Creates a copy of the menu and all items.flash.display:NativeMenu + + + Creates a copy of the menu and all items. + + containsItem + Reports whether this menu contains the specified menu item.true if item is in this menu. + + Booleanitemflash.display:NativeMenuItemThe item to look up. + + + Reports whether this menu contains the specified menu item. + + display + Pops up this menu at the specified location.stageflash.display:StageThe Stage object on which to display this menu. + + stageXNumberThe number of horizontal pixels, relative to the origin + of stage, at which to display this menu. + + stageYNumberThe number of vertical pixels, relative to the origin + of stage, at which to display this menu. + + + Pops up this menu at the specified location. + +

Note: In Flash Player, this method is not supported.

+ +
getItemAt + Gets the menu item at the specified index.If index is outside the bounds of the menu's + items array. + + RangeErrorRangeErrorThe item at the specified position in the menu. + + flash.display:NativeMenuItemindexintThe (zero-based) position of the item to return. + + + Gets the menu item at the specified index. + + getItemIndex + Gets the position of the specified item.The (zero-based) position of the specified item in this menu + or -1, if the item is not in this menu. + + intitemflash.display:NativeMenuItemThe NativeMenuItem object to look up. + + + Gets the position of the specified item. + + hideBuiltInItems + Hides all built-in menu items (except Settings) in the specified ContextMenu object. + Hides all built-in menu items (except Settings) in the specified ContextMenu object. If the debugger version of Flash + Player is running, the Debugging menu item appears, although it is dimmed for SWF files that + do not have remote debugging enabled. + +

This method hides only menu items that appear in the standard context menu; it does not affect + items that appear in the edit and error menus.

+ +

This method works by setting all the Boolean members of my_cm.builtInItems to false. You can selectively make a built-in item visible by setting its + corresponding member in my_cm.builtInItems to true. +

+ +

Note: In AIR, context menus do not have built-in items. Calling this method will have no effect.

+ +
ContextMenuBuiltInItems classContextMenu.builtInItems
removeAllItems + + Removes all items from the menu. + + Removes all items from the menu. + + + + removeItemAt + + Removes and returns the menu item at the specified index.The NativeMenuItem object removed. + + flash.display:NativeMenuItemindexintThe (zero-based) position of the item to remove. + + + + Removes and returns the menu item at the specified index. + + builtInItems + An instance of the ContextMenuBuiltInItems class with the following properties: + forwardAndBack, loop, + play, print, quality, + rewind, save, and zoom.flash.ui:ContextMenuBuiltInItems + An instance of the ContextMenuBuiltInItems class with the following properties: + forwardAndBack, loop, + play, print, quality, + rewind, save, and zoom. + Setting these properties to false removes the corresponding menu items from the + specified ContextMenu object. These properties are enumerable and are set to true by + default. + +

Note: In AIR, context menus do not have built-in items.

+ +
ContextMenuBuiltInItems classContextMenu.hideBuiltInItems()
clipboardItems + An instance of the ContextMenuClipboardItems class with the following properties: + cut, copy, paste, delete, selectAll.flash.ui:ContextMenuClipboardItems + An instance of the ContextMenuClipboardItems class with the following properties: + cut, copy, paste, delete, selectAll. + Setting one of these properties to false disables the corresponding item in the + clipboard menu. + + The following example demonstrates the use of the clipboardItems property + of the ContextMenu object. Create a ContextMenu, and set its + clipboardMenu property to true. Add an event handler for the + MENU_SELECT (generally, right-click) event, and assign the menu to a display object. + In this case, the copy and paste menus are enabled. + +package { + import flash.ui.ContextMenu; + import flash.events.ContextMenuEvent; + import flash.display.Sprite; + + public class ContextMenuClipboardItemsExample extends Sprite { + public function ContextMenuClipboardItemsExample() { + var myContextMenu:ContextMenu = new ContextMenu(); + myContextMenu.clipboardMenu = true; + myContextMenu.addEventListener(ContextMenuEvent.MENU_SELECT, menuSelectHandler); + var rc:Sprite = new Sprite(); + rc.graphics.beginFill(0xDDDDDD); + rc.graphics.drawRect(0,0,100,30); + addChild(rc); + rc.contextMenu = myContextMenu; + } + function menuSelectHandler(event:ContextMenuEvent):void { + event.contextMenuOwner.contextMenu.clipboardItems.copy = true; + event.contextMenuOwner.contextMenu.clipboardItems.paste = true; + } + } +} +ContextMenuClipboardItems classclipboardMenu + Specifies whether or not the clipboard menu should be used.Boolean + Specifies whether or not the clipboard menu should be used. If this value is true, + the clipboardItems property determines which items are enabled or disabled on the clipboard menu. + +

If the link property is non-null, this clipBoardMenu property is ignored.

+ +
customItems + An array of ContextMenuItem objects.Array + An array of ContextMenuItem objects. Each object in the array represents a context menu item that you + have defined. Use this property to add, remove, or modify these custom menu items. + +

To add new menu items, you create a ContextMenuItem object and then add it to the + customItems array (for example, by using Array.push()). For more information about creating + menu items, see the ContextMenuItem class entry.

+ +
flash.display.InteractiveObject.contextMenu
isSupported + The isSupported property is set to true if the + ContextMenu class is supported on the current platform, otherwise it is + set to false.Boolean + The isSupported property is set to true if the + ContextMenu class is supported on the current platform, otherwise it is + set to false. + + items + The array of custom items in this menu.Array + The array of custom items in this menu. + +

Using this property is equivalent to using the customItems property. + The array is sorted in display order.

+ +
link + The URLRequest of the link.flash.net:URLRequest + The URLRequest of the link. If this property is null, a normal context menu is displayed. + If this property is not null, the link context menu is displayed, and operates on the url specified. + +

If a link is specified, the clipboardMenu property is ignored.

+ +

The default value is null.

+ +
numItems + The number of items in this menu.int + The number of items in this menu. + +
KeyLocation +The KeyLocation class contains constants that indicate the location of a key pressed on +the keyboard or keyboard-like input device.Object +The KeyLocation class contains constants that indicate the location of a key pressed on +the keyboard or keyboard-like input device. +

The KeyLocation constants are used in the KeyboardEvent.keyLocation property.

+ +
flash.events.KeyboardEvent.keyLocationD_PAD + Indicates the key activation originated on a directional pad of input device.4uint + Indicates the key activation originated on a directional pad of input device. + Example: The trackball on a mobile device or the left arrow on a remote control. + LEFT + Indicates the key activated is in the left key location (there is more than one possible location for this + key).1uint + Indicates the key activated is in the left key location (there is more than one possible location for this + key). + Example: The left Shift key on a PC 101 Key US keyboard. + NUM_PAD + Indicates the key activation originated on the numeric keypad or with a virtual key corresponding + to the numeric keypad.3uint + Indicates the key activation originated on the numeric keypad or with a virtual key corresponding + to the numeric keypad. Example: The 1 key on a PC 101 Key US keyboard located on the numeric pad. + RIGHT + Indicates the key activated is in the right key location (there is more than one possible location for this + key).2uint + Indicates the key activated is in the right key location (there is more than one possible location for this + key). + Example: The right Shift key on a PC 101 Key US keyboard. + STANDARD + Indicates the key activation is not distinguished as the left or right version of the key, + and did not originate on the numeric keypad (or did not originate with a virtual + key corresponding to the numeric keypad).0uint + Indicates the key activation is not distinguished as the left or right version of the key, + and did not originate on the numeric keypad (or did not originate with a virtual + key corresponding to the numeric keypad). Example: The Q key on a PC 101 Key US keyboard. +
ContextMenuClipboardItems + The ContextMenuClipboardItems class lets you enable or disable the commands in the clipboard context menu.Object + The ContextMenuClipboardItems class lets you enable or disable the commands in the clipboard context menu. + +

Enable or disable the context menu clipboard commands using the clipboardItems property of + the ContextMenu object. The clipboardItems property is an instance of this ContextMenuClipboardItems + class. The clipboard context menu is shown in a context menu when the clipboardMenu property + of the context menu is true, unless the context menu is for a TextField object. TextField objects + control the display of the context menu and the state of its clipboard items automatically.

+ +
ContextMenu.clipboardMenuContextMenuClipboardItems + Creates a new ContextMenuClipboardItems object. + Creates a new ContextMenuClipboardItems object. + clear + Enables or disables the 'Delete' or 'Clear' item on the clipboard menu.Boolean + Enables or disables the 'Delete' or 'Clear' item on the clipboard menu. + This should be enabled only if an object that can be cleared is selected. + copy + Enables or disables the 'Copy' item on the clipboard menu.Boolean + Enables or disables the 'Copy' item on the clipboard menu. + This should be enabled only if an object that can be copied is selected. + cut + Enables or disables the 'Cut' item on the clipboard menu.Boolean + Enables or disables the 'Cut' item on the clipboard menu. + This should be enabled only if an object that can be cut is selected. + paste + Enables or disables the 'Paste' item on the clipboard menu.Boolean + Enables or disables the 'Paste' item on the clipboard menu. + This should be enabled only if pastable data is on the clipboard. + selectAll + Enables or disables the 'Select All' item on the clipboard menu.Boolean + Enables or disables the 'Select All' item on the clipboard menu. + This should only be enabled in a context where a selection can be + expanded to include all similar items, such as in a list or a text editing control. +
KeyboardType + The KeyboardType class is an enumeration class that provides values for different categories of physical computer or device keyboards.Object + The KeyboardType class is an enumeration class that provides values for different categories of physical computer or device keyboards. + +

Use the values defined by the KeyboardType class with the Keybooard.physicalKeyboardType + property.

+ +
The following example is a simple test that indicates the current state of the "Num Lock" and "Caps Lock" keys + as well as the type of keybaord and touch screen type in the running environment. When testing this example, click the + text field to see the property values: + +import flash.events.~~; +import flash.display.~~; +import flash.ui.Keyboard; +import flash.system.Capabilities; +import flash.text.TextField; + + +var keyboardInfoTxt:TextField = new TextField(); +keyboardInfoTxt.x = 30; +keyboardInfoTxt.y = 50; +keyboardInfoTxt.width = 300; +keyboardInfoTxt.height = 100; +keyboardInfoTxt.border = true; + +addChild(keyboardInfoTxt); + +addEventListener (MouseEvent.CLICK, getScreenKeyboardType); + +function getScreenKeyboardType(e:MouseEvent):void{ + keyboardInfoTxt.text= "Caps Lock is : " + String(flash.ui.Keyboard.capsLock)+ "\n" + + "Num Lock is : " + String(flash.ui.Keyboard.numLock) +"\n" + + "Has Virtual Keyboard : " + String(flash.ui.Keyboard.hasVirtualKeyboard) + "\n" + + "Physical Keyboard Type : " + flash.ui.Keyboard.physicalKeyboardType + "\n" + + "flash.system.Capabilities.touchscreenType is : " + flash.system.Capabilities.touchscreenType; +} +
Keyboard.physicalKeyboardTypeALPHANUMERIC + A standard keyboard with a full set of numbers and letters.alphanumericString + A standard keyboard with a full set of numbers and letters. + +

Most desktop computers and some mobile devices provide an alphanumeric keyboard.

+ +
KEYPAD + A phone-style 12-button keypad.keypadString + A phone-style 12-button keypad. + +

Many mobile devices provide a keypad, although some provide an alphanumeric keyboard.

+ +
NONE + No physical keyboard is supported.noneString + No physical keyboard is supported. + +

Typically, a virtual keyboard is provided in the absence of a physical keyboard.

+ +
flash.ui.Keyboard.hasVirtualKeyboard
Mouse + The methods of the Mouse class are used to hide and show the mouse pointer, + or to set the pointer to a specific style.Top-level class used to set, hide. and show the mouse pointer. + Object + The methods of the Mouse class are used to hide and show the mouse pointer, + or to set the pointer to a specific style. + The Mouse class is a top-level class whose properties and methods + you can access without using a constructor. The pointer is visible by default, + but you can hide it and implement a custom pointer. + + The following example uses the MouseExample, SimpleButton, + ButtonDisplayState, and CustomCursor classes to place a simple button on the Stage. The button + has a custom pointer and the button changes when clicked. This is accomplished with the following steps: +
  1. Declare the following instance properties: cursor of type CustomCursor, child of type + CustomButton, and gutter of type uint.
  2. Assign child to a new CustomButton instance, set its x and + y coordinates to 10 pixels each, and then add the instance to the display list. + The CustomButton class overrides the downState, upState, + overState, and hitTestState properties in SimpleButton. Each of these + properties instantiates a ButtonDisplayState object, which draws a different square, depending + on the state of the child instance.
  3. The child instance is then used to add a MOUSE_OVER event listener and + mouseOverHandler() listener method, along with a MOUSE_OUT event listener and associated + mouseOutHandler() method.
  4. The event listeners work as follows: +
    • mouseOverHandler: Hides the "normal" pointer and adds a MOUSE_MOVE + listener, which processes the mouse moves using mouseMoveHandler(), described + below.
    • mouseOutHandler: When the mouse moves outside the custom button, the + "normal" pointer is shown, the MOUSE_MOVE event listener is removed, and the custom cursor's + visibility is set to false.
    • mouseMoveHandler: Moves the custom cursor around wherever the pointer is + moved and sets the custom cursor's visibility to true.
  5. Back in the MouseExample constructor, the cursor property is assigned to a new + CustomCursor object and then added to the display list using addChild(). + The CustomCursor class draws a small nearly black square in place of the "normal" pointer + whenever the mouse is over child.
  6. A fourth event listener of type MOUSE_LEAVE is added, with the associated + mouseLeaveHandler() method. In this method (called if the mouse leaves the Stage), + mouseOutHandler() is passed a new mouseMove listener object, which essentially + removes the pointer so it is not left on the Stage.
+ +package { + import flash.display.Sprite; + import flash.display.DisplayObject; + import flash.ui.Mouse; + import flash.events.*; + + public class MouseExample extends Sprite { + private var cursor:CustomCursor; + private var child:CustomButton; + private var gutter:uint = 10; + + public function MouseExample() { + child = new CustomButton(); + child.x = gutter; + child.y = gutter; + addChild(child); + + child.addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler); + child.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler); + + cursor = new CustomCursor(); + addChild(cursor); + + stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); + } + + private function mouseOverHandler(event:MouseEvent):void { + trace("mouseOverHandler"); + Mouse.hide(); + child.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + } + + private function mouseOutHandler(event:MouseEvent):void { + trace("mouseOutHandler"); + Mouse.show(); + child.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); + cursor.visible = false; + } + + private function mouseMoveHandler(event:MouseEvent):void { + trace("mouseMoveHandler"); + cursor.x = event.localX; + cursor.y = event.localY; + event.updateAfterEvent(); + cursor.visible = true; + } + + private function mouseLeaveHandler(event:Event):void { + trace("mouseLeaveHandler"); + mouseOutHandler(new MouseEvent(MouseEvent.MOUSE_MOVE)); + } + } +} + +import flash.display.Shape; +import flash.display.SimpleButton; + +class CustomButton extends SimpleButton { + var upColor:uint = 0xFFCC00; + var overColor:uint = 0xCCFF00; + var downColor:uint = 0x00CCFF; + var size:uint = 80; + + public function CustomButton() { + downState = new ButtonDisplayState(downColor, size+10); + overState = new ButtonDisplayState(overColor, size); + upState = new ButtonDisplayState(upColor, size); + hitTestState = new ButtonDisplayState(upColor, size); + } +} + +class ButtonDisplayState extends Shape { + var bgColor:uint; + var size:uint; + + public function ButtonDisplayState(bgColor:uint, size:uint) { + this.bgColor = bgColor; + this.size = size; + draw(); + } + + private function draw():void { + graphics.clear(); + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, size, size); + graphics.endFill(); + } +} + +class CustomCursor extends Shape { + var bgColor:uint = 0x333333; + var size:uint = 10; + + public function CustomCursor() { + visible = false; + draw(); + } + + private function draw():void { + graphics.clear(); + graphics.beginFill(bgColor); + graphics.drawRect(0, 0, size, size); + graphics.endFill(); + } +} +
flash.events.MouseEventhide + Hides the pointer. + Hides the pointer. The pointer is visible by default. + +

Note: You need to call Mouse.hide() only once, regardless of + the number of previous calls to Mouse.show().

+ +
flash.display.DisplayObject.mouseXflash.display.DisplayObject.mouseY
registerCursor + Registers a native cursor under the given name, with the given data.nameStringThe name to use as a reference to the native cursor instance. + cursorflash.ui:MouseCursorDataThe properties for the native cursor, such as icon bitmap, specified as a MouseCursorData instance. + + Registers a native cursor under the given name, with the given data. + + Registers a native cursor under the given name, with the given data. + flash.ui.MouseCursorDatashow + Displays the pointer. + Displays the pointer. The pointer is visible by default. + +

Note: You need to call Mouse.show() only once, regardless of + the number of previous calls to Mouse.hide().

+ +
flash.display.DisplayObject.mouseXflash.display.DisplayObject.mouseY
unregisterCursor + Unregisters the native cursor with the given name.nameStringThe name referring to the native cursor instance. + Unregisters the native cursor with the given name. + + + Unregisters the native cursor with the given name. + cursor + Sets or returns the type of cursor, or, for a native cursor, the cursor name.StringIf set to any value which is not a member of flash.ui.MouseCursor, or is not a string specified using + the Mouse.registerCursor() method. + ArgumentErrorArgumentErrorThe type of cursor, or, for a native cursor, the cursor name. + + Sets or returns the type of cursor, or, for a native cursor, the cursor name. + +

The default value is flash.ui.MouseCursor.AUTO.

+ +

To set values for this property, use the following string values:

+ + String valueDescriptionflash.ui.MouseCursor.AUTOMouse cursor will change automatically based on the object under the mouse.flash.ui.MouseCursor.ARROWMouse cursor will be an arrow.flash.ui.MouseCursor.BUTTONMouse cursor will be a button clicking hand.flash.ui.MouseCursor.HANDMouse cursor will be a dragging hand.flash.ui.MouseCursor.IBEAMMouse cursor will be an I-beam. +

Note: For Flash Player 10.2 or AIR 2.6 and later versions, this property sets or gets the cursor name + when you are using a native cursor. A native cursor name defined using Mouse.registerCursor() overwrites currently + predefined cursor types (such as flash.ui.MouseCursor.IBEAM).

+ +
flash.ui.MouseCursorregisterCursor()flash.ui.MouseCursorData
supportsCursor + Indicates whether the computer or device displays a persistent cursor.Boolean + Indicates whether the computer or device displays a persistent cursor. + +

The supportsCursor property is true on most desktop computers + and false on most mobile devices.

+ +

Note: Mouse events can be dispatched whether or not this property is true. + However, mouse events may behave differently depending on the physical characteristics of the pointing device.

+ +
The following example is a simple test that indicates current support for a persistent cursor, or not. When testing this example, click the + text field to see the property value: + +import flash.events.~~; +import flash.display.~~; +import flash.ui.Mouse; +import flash.text.TextField; + +var supportsCursorTxt:TextField = new TextField(); +supportsCursorTxt.width = 200; +supportsCursorTxt.border = true; +addChild(supportsCursorTxt); + +addEventListener (MouseEvent.CLICK, getScreenKeyboardType); + +function getScreenKeyboardType(e:MouseEvent):void{ + supportsCursorTxt.text= "Supports Cursor is : " + String(flash.ui.Mouse.supportsCursor); + +} + The following example tests and responds to different user input environments. + This example assumes it is part of the code for a game that uses a cursor. First, the example tests + to see if the environment supports a cursor. If not, it then tests to see if the environment supports + interaction with a stylus. If so, then code can be inserted to customize the game for stylus use. + If the environment supports finger interaction, code can be inserted to customize the program for the specific + needs of finger touches. If no pointing device is supported at all, then the developer needs to create + alternative cursors or some means of interaction, such as key presses. + +if(Mouse.supportsCursor) { + //Game acts as before +} else { + if(Capabilities.touchscreenType == TouchscreenType.STYLUS ){ + //The Game has to change so that the character is chasing the location of the stylus as + //it's dragged around. Some of the animations will have to change + }else if(Capabilities.touchscreenType = TouchscreenType.FINGER){ + //Same as above, except that the hit-area is larger for a finger. + }else{ + //There's no pointing device at all. The developer designs some sort of custom cursor to + //be controlled with key presses or similar input + } +} +
flash.system.Capabilities.touchscreenType
supportsNativeCursor + Indicates whether the current configuration supports native cursors.BooleanIndicates whether the current configuration supports native cursors. + + + Indicates whether the current configuration supports native cursors. + +
Keyboard + The Keyboard class is used to build an interface that can be controlled by a user with a standard keyboard.Object + The Keyboard class is used to build an interface that can be controlled by a user with a standard keyboard. + You can use the methods and properties of the Keyboard class without using a constructor. + The properties of the Keyboard class are constants representing the keys that are + most commonly used to control games. + + isAccessible + Specifies whether the last key pressed is accessible by other SWF files.The value true if the last key pressed can be accessed. + If access is not permitted, this method returns false. + Boolean + Specifies whether the last key pressed is accessible by other SWF files. + By default, security restrictions prevent code from a SWF file in one domain + from accessing a keystroke generated from a SWF file in another domain. + + ALTERNATE + Constant associated with the key code value for the Alternate (Option) key (18).18uint + Constant associated with the key code value for the Alternate (Option) key (18). + + AUDIO + Select the audio mode + + 0x01000017uint + Select the audio mode + + A + Constant associated with the key code value for the A key (65).65uint + Constant associated with the key code value for the A key (65). + + BACKQUOTE + Constant associated with the key code value for the ` key (192).192uint + Constant associated with the key code value for the ` key (192). + + BACKSLASH + Constant associated with the key code value for the \ key (220).220uint + Constant associated with the key code value for the \ key (220). + + BACKSPACE + Constant associated with the key code value for the Backspace key (8).8uint + Constant associated with the key code value for the Backspace key (8). + + BACK + Return to previous page in application + + 0x01000016uint + Return to previous page in application + + BLUE + Blue function key button + + 0x01000003uint + Blue function key button + + B + Constant associated with the key code value for the B key (66).66uint + Constant associated with the key code value for the B key (66). + + CAPS_LOCK + Constant associated with the key code value for the Caps Lock key (20).20uint + Constant associated with the key code value for the Caps Lock key (20). + + CHANNEL_DOWN + Channel down + + 0x01000005uint + Channel down + + CHANNEL_UP + Channel up + + 0x01000004uint + Channel up + + COMMAND + Constant associated with the Mac command key (15).15uint + Constant associated with the Mac command key (15). This constant is currently only used for setting menu key equivalents. + + COMMA + Constant associated with the key code value for the , key (188).188uint + Constant associated with the key code value for the , key (188). + + CONTROL + Constant associated with the key code value for the Control key (17).17uint + Constant associated with the key code value for the Control key (17). + + CharCodeStrings + An array containing all the defined key name constants.unknownArray + An array containing all the defined key name constants. + + C + Constant associated with the key code value for the C key (67).67uint + Constant associated with the key code value for the C key (67). + + DELETE + Constant associated with the key code value for the Delete key (46).46uint + Constant associated with the key code value for the Delete key (46). + + DOWN + Constant associated with the key code value for the Down Arrow key (40).40uint + Constant associated with the key code value for the Down Arrow key (40). + + DVR + Engage DVR application mode + + 0x01000019uint + Engage DVR application mode + + D + Constant associated with the key code value for the D key (68).68uint + Constant associated with the key code value for the D key (68). + + END + Constant associated with the key code value for the End key (35).35uint + Constant associated with the key code value for the End key (35). + + ENTER + Constant associated with the key code value for the Enter key (13).13uint + Constant associated with the key code value for the Enter key (13). + + EQUAL + Constant associated with the key code value for the = key (187).187uint + Constant associated with the key code value for the = key (187). + + ESCAPE + Constant associated with the key code value for the Escape key (27).27uint + Constant associated with the key code value for the Escape key (27). + + EXIT + Exits current application mode + + 0x01000015uint + Exits current application mode + + E + Constant associated with the key code value for the E key (69).69uint + Constant associated with the key code value for the E key (69). + + F10 + Constant associated with the key code value for the F10 key (121).121uint + Constant associated with the key code value for the F10 key (121). + + F11 + Constant associated with the key code value for the F11 key (122).122uint + Constant associated with the key code value for the F11 key (122). + + F12 + Constant associated with the key code value for the F12 key (123).123uint + Constant associated with the key code value for the F12 key (123). + + F13 + Constant associated with the key code value for the F13 key (124).124uint + Constant associated with the key code value for the F13 key (124). + + F14 + Constant associated with the key code value for the F14 key (125).125uint + Constant associated with the key code value for the F14 key (125). + + F15 + Constant associated with the key code value for the F15 key (126).126uint + Constant associated with the key code value for the F15 key (126). + + F1 + Constant associated with the key code value for the F1 key (112).112uint + Constant associated with the key code value for the F1 key (112). + + F2 + Constant associated with the key code value for the F2 key (113).113uint + Constant associated with the key code value for the F2 key (113). + + F3 + Constant associated with the key code value for the F3 key (114).114uint + Constant associated with the key code value for the F3 key (114). + + F4 + Constant associated with the key code value for the F4 key (115).115uint + Constant associated with the key code value for the F4 key (115). + + F5 + Constant associated with the key code value for the F5 key (116).116uint + Constant associated with the key code value for the F5 key (116). + + F6 + Constant associated with the key code value for the F6 key (117).117uint + Constant associated with the key code value for the F6 key (117). + + F7 + Constant associated with the key code value for the F7 key (118).118uint + Constant associated with the key code value for the F7 key (118). + + F8 + Constant associated with the key code value for the F8 key (119).119uint + Constant associated with the key code value for the F8 key (119). + + F9 + Constant associated with the key code value for the F9 key (120).120uint + Constant associated with the key code value for the F9 key (120). + + FAST_FORWARD + Engage fast-forward transport mode + + 0x0100000Auint + Engage fast-forward transport mode + + F + Constant associated with the key code value for the F key (70).70uint + Constant associated with the key code value for the F key (70). + + GREEN + Green function key button + + 0x01000001uint + Green function key button + + GUIDE + Engage program guide + + 0x01000014uint + Engage program guide + + G + Constant associated with the key code value for the G key (71).71uint + Constant associated with the key code value for the G key (71). + + HELP + Engage help application or context-sensitive help + + 0x0100001Duint + Engage help application or context-sensitive help + + HOME + Constant associated with the key code value for the Home key (36).36uint + Constant associated with the key code value for the Home key (36). + + H + Constant associated with the key code value for the H key (72).72uint + Constant associated with the key code value for the H key (72). + + INFO + Info button + + 0x01000013uint + Info button + + INPUT + Cycle input + + 0x0100001Buint + Cycle input + + INSERT + Constant associated with the key code value for the Insert key (45).45uint + Constant associated with the key code value for the Insert key (45). + + I + Constant associated with the key code value for the I key (73).73uint + Constant associated with the key code value for the I key (73). + + J + Constant associated with the key code value for the J key (74).74uint + Constant associated with the key code value for the J key (74). + + KEYNAME_BEGIN + The Begin key + BeginString + The Begin key + KEYNAME_BREAK + The Break key + BreakString + The Break key + KEYNAME_CLEARDISPLAY + The Clear Display key + ClrDspString + The Clear Display key + KEYNAME_CLEARLINE + The Clear Line key + ClrLnString + The Clear Line key + KEYNAME_DELETECHAR + The Delete Character key + DelChrString + The Delete Character key + KEYNAME_DELETELINE + The Delete Line key + DelLnString + The Delete Line key + KEYNAME_DELETE + The Delete key + DeleteString + The Delete key + KEYNAME_DOWNARROW + The down arrow + + DownString + The down arrow + + KEYNAME_END + The End key + EndString + The End key + KEYNAME_EXECUTE + The Execute key + ExecString + The Execute key + KEYNAME_F10 + The F10 key + F10String + The F10 key + KEYNAME_F11 + The F11 key + F11String + The F11 key + KEYNAME_F12 + The F12 key + F12String + The F12 key + KEYNAME_F13 + The F13 key + F13String + The F13 key + KEYNAME_F14 + The F14 key + F14String + The F14 key + KEYNAME_F15 + The F15 key + F15String + The F15 key + KEYNAME_F16 + The F16 key + F16String + The F16 key + KEYNAME_F17 + The F17 key + F17String + The F17 key + KEYNAME_F18 + The F18 key + F18String + The F18 key + KEYNAME_F19 + The F19 key + F19String + The F19 key + KEYNAME_F1 + The F1 key + F1String + The F1 key + KEYNAME_F20 + The F20 key + F20String + The F20 key + KEYNAME_F21 + The F21 key + F21String + The F21 key + KEYNAME_F22 + The F22 key + F22String + The F22 key + KEYNAME_F23 + The F23 key + F23String + The F23 key + KEYNAME_F24 + The F24 key + F24String + The F24 key + KEYNAME_F25 + The F25 key + F25String + The F25 key + KEYNAME_F26 + The F26 key + F26String + The F26 key + KEYNAME_F27 + The F27 key + F27String + The F27 key + KEYNAME_F28 + The F28 key + F28String + The F28 key + KEYNAME_F29 + The F29 key + F29String + The F29 key + KEYNAME_F2 + The F2 key + F2String + The F2 key + KEYNAME_F30 + The F30 key + F30StringThe F30 key + + The F30 key + KEYNAME_F31 + The F31 key + F31String + The F31 key + KEYNAME_F32 + The F32 key + F32String + The F32 key + KEYNAME_F33 + The F33 key + F33String + The F33 key + KEYNAME_F34 + The F34 key + F34String + The F34 key + KEYNAME_F35 + The F35 key + F35String + The F35 key + KEYNAME_F3 + The F3 key + F3String + The F3 key + KEYNAME_F4 + The F4 key + F4String + The F4 key + KEYNAME_F5 + The F5 key + F5String + The F5 key + KEYNAME_F6 + The F6 key + F6String + The F6 key + KEYNAME_F7 + The F7 key + F7String + The F7 key + KEYNAME_F8 + The F8 key + F8String + The F8 key + KEYNAME_F9 + The F9 key + F9String + The F9 key + KEYNAME_FIND + The Find key + FindString + The Find key + KEYNAME_HELP + The Help key + HelpString + The Help key + KEYNAME_HOME + The Home key + HomeString + The Home key + KEYNAME_INSERTCHAR + The Insert Character key + InsChrString + The Insert Character key + KEYNAME_INSERTLINE + The Insert Line key + InsLnString + The Insert Line key + KEYNAME_INSERT + The Insert key + InsertString + The Insert key + KEYNAME_LEFTARROW + The left arrow + + LeftString + The left arrow + + KEYNAME_MENU + The Menu key + MenuString + The Menu key + KEYNAME_MODESWITCH + The Mode Switch key + ModeSwString + The Mode Switch key + KEYNAME_NEXT + The Next key + NextString + The Next key + KEYNAME_PAGEDOWN + The Page Down key + PgDnString + The Page Down key + KEYNAME_PAGEUP + The Page Up key + PgUpString + The Page Up key + KEYNAME_PAUSE + The Pause key + PauseString + The Pause key + KEYNAME_PREV + The Previous key + PrevString + The Previous key + KEYNAME_PRINTSCREEN + The Print Screen + PrntScrnString + The Print Screen + KEYNAME_PRINT + The Print key + PrintString + The Print key + KEYNAME_REDO + The Redo key + RedoString + The Redo key + KEYNAME_RESET + The Reset key + ResetString + The Reset key + KEYNAME_RIGHTARROW + The right arrow + + RightString + The right arrow + + KEYNAME_SCROLLLOCK + The Scroll Lock key + ScrlLckString + The Scroll Lock key + KEYNAME_SELECT + The Select key + SelectString + The Select key + KEYNAME_STOP + The Stop key + StopString + The Stop key + KEYNAME_SYSREQ + The System Request key + SysReqString + The System Request key + KEYNAME_SYSTEM + The System key + SysString + The System key + KEYNAME_UNDO + The Undo key + UndoString + The Undo key + KEYNAME_UPARROW + The up arrow + UpString + The up arrow + KEYNAME_USER + The User key + UserString + The User key + K + Constant associated with the key code value for the K key (75).75uint + Constant associated with the key code value for the K key (75). + + LAST + Watch last channel or show watched + + 0x01000011uint + Watch last channel or show watched + + LEFTBRACKET + Constant associated with the key code value for the [ key (219).219uint + Constant associated with the key code value for the [ key (219). + + LEFT + Constant associated with the key code value for the Left Arrow key (37).37uint + Constant associated with the key code value for the Left Arrow key (37). + + LIVE + Return to live [position in broadcast] + + 0x01000010uint + Return to live [position in broadcast] + + L + Constant associated with the key code value for the L key (76).76uint + Constant associated with the key code value for the L key (76). + + MASTER_SHELL + Engage "Master Shell" e.g.0x0100001Euint + Engage "Master Shell" e.g. TiVo or other vendor button + + MENU + Engage menu + + 0x01000012uint + Engage menu + + MINUS + Constant associated with the key code value for the - key (189).189uint + Constant associated with the key code value for the - key (189). + + M + Constant associated with the key code value for the M key (77).77uint + Constant associated with the key code value for the M key (77). + + NEXT + Skip to next track or chapter + + 0x0100000Euint + Skip to next track or chapter + + NUMBER_0 + Constant associated with the key code value for the 0 key (48).48uint + Constant associated with the key code value for the 0 key (48). + + NUMBER_1 + Constant associated with the key code value for the 1 key (49).49uint + Constant associated with the key code value for the 1 key (49). + + NUMBER_2 + Constant associated with the key code value for the 2 key (50).50uint + Constant associated with the key code value for the 2 key (50). + + NUMBER_3 + Constant associated with the key code value for the 3 key (51).51uint + Constant associated with the key code value for the 3 key (51). + + NUMBER_4 + Constant associated with the key code value for the 4 key (52).52uint + Constant associated with the key code value for the 4 key (52). + + NUMBER_5 + Constant associated with the key code value for the 5 key (53).53uint + Constant associated with the key code value for the 5 key (53). + + NUMBER_6 + Constant associated with the key code value for the 6 key (54).54uint + Constant associated with the key code value for the 6 key (54). + + NUMBER_7 + Constant associated with the key code value for the 7 key (55).55uint + Constant associated with the key code value for the 7 key (55). + + NUMBER_8 + Constant associated with the key code value for the 8 key (56).56uint + Constant associated with the key code value for the 8 key (56). + + NUMBER_9 + Constant associated with the key code value for the 9 key (57).57uint + Constant associated with the key code value for the 9 key (57). + + NUMPAD_0 + Constant associated with the key code value for the number 0 key on the number pad (96).96uint + Constant associated with the key code value for the number 0 key on the number pad (96). + + NUMPAD_1 + Constant associated with the key code value for the number 1 key on the number pad (97).97uint + Constant associated with the key code value for the number 1 key on the number pad (97). + + NUMPAD_2 + Constant associated with the key code value for the number 2 key on the number pad (98).98uint + Constant associated with the key code value for the number 2 key on the number pad (98). + + NUMPAD_3 + Constant associated with the key code value for the number 3 key on the number pad (99).99uint + Constant associated with the key code value for the number 3 key on the number pad (99). + + NUMPAD_4 + Constant associated with the key code value for the number 4 key on the number pad (100).100uint + Constant associated with the key code value for the number 4 key on the number pad (100). + + NUMPAD_5 + Constant associated with the key code value for the number 5 key on the number pad (101).101uint + Constant associated with the key code value for the number 5 key on the number pad (101). + + NUMPAD_6 + Constant associated with the key code value for the number 6 key on the number pad (102).102uint + Constant associated with the key code value for the number 6 key on the number pad (102). + + NUMPAD_7 + Constant associated with the key code value for the number 7 key on the number pad (103).103uint + Constant associated with the key code value for the number 7 key on the number pad (103). + + NUMPAD_8 + Constant associated with the key code value for the number 8 key on the number pad (104).104uint + Constant associated with the key code value for the number 8 key on the number pad (104). + + NUMPAD_9 + Constant associated with the key code value for the number 9 key on the number pad (105).105uint + Constant associated with the key code value for the number 9 key on the number pad (105). + + NUMPAD_ADD + Constant associated with the key code value for the addition key on the number pad (107).107uint + Constant associated with the key code value for the addition key on the number pad (107). + + NUMPAD_DECIMAL + Constant associated with the key code value for the decimal key on the number pad (110).110uint + Constant associated with the key code value for the decimal key on the number pad (110). + + NUMPAD_DIVIDE + Constant associated with the key code value for the division key on the number pad (111).111uint + Constant associated with the key code value for the division key on the number pad (111). + + NUMPAD_ENTER + Constant associated with the key code value for the Enter key on the number pad (108).108uint + Constant associated with the key code value for the Enter key on the number pad (108). + + NUMPAD_MULTIPLY + Constant associated with the key code value for the multiplication key on the number pad (106).106uint + Constant associated with the key code value for the multiplication key on the number pad (106). + + NUMPAD_SUBTRACT + Constant associated with the key code value for the subtraction key on the number pad (109).109uint + Constant associated with the key code value for the subtraction key on the number pad (109). + + NUMPAD + Constant associated with the pseudo-key code for the the number pad (21).21uint + Constant associated with the pseudo-key code for the the number pad (21). Use to + set numpad modifier on key equivalents + + N + Constant associated with the key code value for the N key (78).78uint + Constant associated with the key code value for the N key (78). + + O + Constant associated with the key code value for the O key (79).79uint + Constant associated with the key code value for the O key (79). + + PAGE_DOWN + Constant associated with the key code value for the Page Down key (34).34uint + Constant associated with the key code value for the Page Down key (34). + + PAGE_UP + Constant associated with the key code value for the Page Up key (33).33uint + Constant associated with the key code value for the Page Up key (33). + + PAUSE + Engage pause transport mode + + 0x01000008uint + Engage pause transport mode + + PERIOD + Constant associated with the key code value for the .190uint + Constant associated with the key code value for the . key (190). + + PLAY + Engage play transport mode + + 0x01000007uint + Engage play transport mode + + PREVIOUS + Skip to previous track or chapter + + 0x0100000Fuint + Skip to previous track or chapter + + P + Constant associated with the key code value for the P key (80).80uint + Constant associated with the key code value for the P key (80). + + QUOTE + Constant associated with the key code value for the ' key (222).222uint + Constant associated with the key code value for the ' key (222). + + Q + Constant associated with the key code value for the Q key (81).81uint + Constant associated with the key code value for the Q key (81). + + RECORD + Record item or engage record transport mode + + 0x01000006uint + Record item or engage record transport mode + + RED + Red function key button + + 0x01000000uint + Red function key button + + REWIND + Engage rewind transport mode + + 0x0100000Buint + Engage rewind transport mode + + RIGHTBRACKET + Constant associated with the key code value for the ] key (221).221uint + Constant associated with the key code value for the ] key (221). + + RIGHT + Constant associated with the key code value for the Right Arrow key (39).39uint + Constant associated with the key code value for the Right Arrow key (39). + + R + Constant associated with the key code value for the R key (82).82uint + Constant associated with the key code value for the R key (82). + + SEARCH + Search button + + 0x0100001Fuint + Search button + + SEMICOLON + Constant associated with the key code value for the ; key (186).186uint + Constant associated with the key code value for the ; key (186). + + SETUP + Engage setup application or menu + + 0x0100001Cuint + Engage setup application or menu + + SHIFT + Constant associated with the key code value for the Shift key (16).16uint + Constant associated with the key code value for the Shift key (16). + + SKIP_BACKWARD + Quick skip backward (usually 7-10 seconds) + + 0x0100000Duint + Quick skip backward (usually 7-10 seconds) + + SKIP_FORWARD + Quick skip ahead (usually 30 seconds) + + 0x0100000Cuint + Quick skip ahead (usually 30 seconds) + + SLASH + Constant associated with the key code value for the / key (191).191uint + Constant associated with the key code value for the / key (191). + + SPACE + Constant associated with the key code value for the Spacebar (32).32uint + Constant associated with the key code value for the Spacebar (32). + + STOP + Engage stop transport mode + + 0x01000009uint + Engage stop transport mode + + STRING_BEGIN + The OS X Unicode Begin constant + String + The OS X Unicode Begin constant + STRING_BREAK + The OS X Unicode Break constant + String + The OS X Unicode Break constant + STRING_CLEARDISPLAY + The OS X Unicode Clear Display constant + String + The OS X Unicode Clear Display constant + STRING_CLEARLINE + The OS X Unicode Clear Line constant + String + The OS X Unicode Clear Line constant + STRING_DELETECHAR + The OS X Unicode Delete Character constant + String + The OS X Unicode Delete Character constant + STRING_DELETELINE + The OS X Unicode Delete Line constant + String + The OS X Unicode Delete Line constant + STRING_DELETE + The OS X Unicode Delete constant + String + The OS X Unicode Delete constant + STRING_DOWNARROW + The OS X Unicode down arrow constant + String + The OS X Unicode down arrow constant + STRING_END + The OS X Unicode End constant + String + The OS X Unicode End constant + STRING_EXECUTE + The OS X Unicode Execute constant + String + The OS X Unicode Execute constant + STRING_F10 + The OS X Unicode F10 constant + String + The OS X Unicode F10 constant + STRING_F11 + The OS X Unicode F11 constant + String + The OS X Unicode F11 constant + STRING_F12 + The OS X Unicode F12 constant + String + The OS X Unicode F12 constant + STRING_F13 + The OS X Unicode F13 constant + String + The OS X Unicode F13 constant + STRING_F14 + The OS X Unicode F14 constant + String + The OS X Unicode F14 constant + STRING_F15 + The OS X Unicode F15 constant + String + The OS X Unicode F15 constant + STRING_F16 + The OS X Unicode F16 constant + String + The OS X Unicode F16 constant + STRING_F17 + The OS X Unicode F17 constant + String + The OS X Unicode F17 constant + STRING_F18 + The OS X Unicode F18 constant + String + The OS X Unicode F18 constant + STRING_F19 + The OS X Unicode F19 constant + String + The OS X Unicode F19 constant + STRING_F1 + The OS X Unicode F1 constant + String + The OS X Unicode F1 constant + STRING_F20 + The OS X Unicode F20 constant + String + The OS X Unicode F20 constant + STRING_F21 + The OS X Unicode F21 constant + String + The OS X Unicode F21 constant + STRING_F22 + The OS X Unicode F22 constant + String + The OS X Unicode F22 constant + STRING_F23 + The OS X Unicode F23 constant + String + The OS X Unicode F23 constant + STRING_F24 + The OS X Unicode F24 constant + String + The OS X Unicode F24 constant + STRING_F25 + The OS X Unicode F25 constant + String + The OS X Unicode F25 constant + STRING_F26 + The OS X Unicode F26 constant + String + The OS X Unicode F26 constant + STRING_F27 + The OS X Unicode F27 constant + String + The OS X Unicode F27 constant + STRING_F28 + The OS X Unicode F28 constant + String + The OS X Unicode F28 constant + STRING_F29 + The OS X Unicode F29 constant + String + The OS X Unicode F29 constant + STRING_F2 + The OS X Unicode F2 constant + String + The OS X Unicode F2 constant + STRING_F30 + The OS X Unicode F30 constant + String + The OS X Unicode F30 constant + STRING_F31 + The OS X Unicode F31 constant + String + The OS X Unicode F31 constant + STRING_F32 + The OS X Unicode F32 constant + String + The OS X Unicode F32 constant + STRING_F33 + The OS X Unicode F33 constant + String + The OS X Unicode F33 constant + STRING_F34 + The OS X Unicode F34 constant + String + The OS X Unicode F34 constant + STRING_F35 + The OS X Unicode F35 constant + String + The OS X Unicode F35 constant + STRING_F3 + The OS X Unicode F3 constant + String + The OS X Unicode F3 constant + STRING_F4 + The OS X Unicode F4 constant + String + The OS X Unicode F4 constant + STRING_F5 + The OS X Unicode F5 constant + String + The OS X Unicode F5 constant + STRING_F6 + The OS X Unicode F6 constant + String + The OS X Unicode F6 constant + STRING_F7 + The OS X Unicode F7 constant + String + The OS X Unicode F7 constant + STRING_F8 + The OS X Unicode F8 constant + String + The OS X Unicode F8 constant + STRING_F9 + The OS X Unicode F9 constant + String + The OS X Unicode F9 constant + STRING_FIND + The OS X Unicode Find constant + String + The OS X Unicode Find constant + STRING_HELP + The OS X Unicode Help constant + String + The OS X Unicode Help constant + STRING_HOME + The OS X Unicode Home constant + String + The OS X Unicode Home constant + STRING_INSERTCHAR + The OS X Unicode Insert Character constant + String + The OS X Unicode Insert Character constant + STRING_INSERTLINE + The OS X Unicode Insert Line constant + String + The OS X Unicode Insert Line constant + STRING_INSERT + The OS X Unicode Insert constant + String + The OS X Unicode Insert constant + STRING_LEFTARROW + The OS X Unicode left arrow constant + String + The OS X Unicode left arrow constant + STRING_MENU + The OS X Unicode Menu constant + String + The OS X Unicode Menu constant + STRING_MODESWITCH + The OS X Unicode Mode Switch constant + String + The OS X Unicode Mode Switch constant + STRING_NEXT + The OS X Unicode Next constant + String + The OS X Unicode Next constant + STRING_PAGEDOWN + The OS X Unicode Page Down constant + String + The OS X Unicode Page Down constant + STRING_PAGEUP + The OS X Unicode Page Up constant + String + The OS X Unicode Page Up constant + STRING_PAUSE + The OS X Unicode Pause constant + String + The OS X Unicode Pause constant + STRING_PREV + The OS X Unicode Previous constant + String + The OS X Unicode Previous constant + STRING_PRINTSCREEN + The OS X Unicode Print Screen constant + String + The OS X Unicode Print Screen constant + STRING_PRINT + The OS X Unicode Print constant + String + The OS X Unicode Print constant + STRING_REDO + The OS X Unicode Redo constant + String + The OS X Unicode Redo constant + STRING_RESET + The OS X Unicode Reset constant + String + The OS X Unicode Reset constant + STRING_RIGHTARROW + The OS X Unicode right arrow constant + String + The OS X Unicode right arrow constant + STRING_SCROLLLOCK + The OS X Unicode Scroll Lock constant + String + The OS X Unicode Scroll Lock constant + STRING_SELECT + The OS X Unicode Select constant + String + The OS X Unicode Select constant + STRING_STOP + The OS X Unicode Stop constant + String + The OS X Unicode Stop constant + STRING_SYSREQ + The OS X Unicode System Request constant + String + The OS X Unicode System Request constant + STRING_SYSTEM + The OS X Unicode System constant + String + The OS X Unicode System constant + STRING_UNDO + The OS X Unicode Undo constant + String + The OS X Unicode Undo constant + STRING_UPARROW + The OS X Unicode up arrow constant + String + The OS X Unicode up arrow constant + STRING_USER + The OS X Unicode User constant + String + The OS X Unicode User constant + SUBTITLE + Toggle subtitles + + 0x01000018uint + Toggle subtitles + + S + Constant associated with the key code value for the S key (83).83uint + Constant associated with the key code value for the S key (83). + + TAB + Constant associated with the key code value for the Tab key (9).9uint + Constant associated with the key code value for the Tab key (9). + + T + Constant associated with the key code value for the T key (84).84uint + Constant associated with the key code value for the T key (84). + + UP + Constant associated with the key code value for the Up Arrow key (38).38uint + Constant associated with the key code value for the Up Arrow key (38). + + U + Constant associated with the key code value for the U key (85).85uint + Constant associated with the key code value for the U key (85). + + VOD + Engage video-on-demand + + 0x0100001Auint + Engage video-on-demand + + V + Constant associated with the key code value for the V key (86).86uint + Constant associated with the key code value for the V key (86). + + W + Constant associated with the key code value for the W key (87).87uint + Constant associated with the key code value for the W key (87). + + X + Constant associated with the key code value for the X key (88).88uint + Constant associated with the key code value for the X key (88). + + YELLOW + Yellow function key button + + 0x01000002uint + Yellow function key button + + Y + Constant associated with the key code value for the Y key (89).89uint + Constant associated with the key code value for the Y key (89). + + Z + Constant associated with the key code value for the Z key (90).90uint + Constant associated with the key code value for the Z key (90). + + capsLock + Specifies whether the Caps Lock key is activated (true) or not (false).Boolean + Specifies whether the Caps Lock key is activated (true) or not (false). + hasVirtualKeyboard + Indicates whether the computer or device provides a virtual keyboard.Boolean + Indicates whether the computer or device provides a virtual keyboard. + If the current environment provides a virtual keyboard, this value is true. + + The following example is a simple test that indicates the current state of the "Num Lock" and "Caps Lock" keys + as well as the type of keybaord and touch screen type in the running environment. When testing this example, click the + text field to see the property values: + +import flash.events.~~; +import flash.display.~~; +import flash.ui.Keyboard; +import flash.system.Capabilities; +import flash.text.TextField; + + +var keyboardInfoTxt:TextField = new TextField(); +keyboardInfoTxt.x = 30; +keyboardInfoTxt.y = 50; +keyboardInfoTxt.width = 300; +keyboardInfoTxt.height = 100; +keyboardInfoTxt.border = true; + +addChild(keyboardInfoTxt); + +addEventListener (MouseEvent.CLICK, getScreenKeyboardType); + +function getScreenKeyboardType(e:MouseEvent):void{ + keyboardInfoTxt.text= "Caps Lock is : " + String(flash.ui.Keyboard.capsLock)+ "\n" + + "Num Lock is : " + String(flash.ui.Keyboard.numLock) +"\n" + + "Has Virtual Keyboard : " + String(flash.ui.Keyboard.hasVirtualKeyboard) + "\n" + + "Physical Keyboard Type : " + flash.ui.Keyboard.physicalKeyboardType + "\n" + + "flash.system.Capabilities.touchscreenType is : " + flash.system.Capabilities.touchscreenType; +} +numLock + Specifies whether the Num Lock key is activated (true) or not (false).Boolean + Specifies whether the Num Lock key is activated (true) or not (false). + physicalKeyboardType + Indicates the type of physical keyboard provided by the computer or device, if any.String + Indicates the type of physical keyboard provided by the computer or device, if any. + +

Use the constants defined in the KeyboardType class to test the values reported by this property.

+ +

Note: If a computer or device has both an alphanumeric keyboard and a 12-button keypad, this + property only reports the presence of the alphanumeric keyboard.

+ +
KeyboardType class
Multitouch + The Multitouch class manages and provides information about the current environment's support for handling + contact from user input devices, including contact that has two or more touch points (such as a user's fingers on a touch screen).manages and indicates support for touch interaction + + Object + The Multitouch class manages and provides information about the current environment's support for handling + contact from user input devices, including contact that has two or more touch points (such as a user's fingers on a touch screen). + When a user interacts with a device such as a mobile phone or tablet with a touch screen, the user typically + touches the screen with his or her fingers or a pointing device. While there is a broad range of pointing devices, + such as a mouse or a stylus, many of these devices only have a single point of contact with an application. For pointing + devices with a single point of contact, + user interaction events can be handled as a mouse event, or using a basic set of touch events (called "touch point" events). + However, for pointing devices that have several + points of contact and perform complex movement, such as the human hand, Flash runtimes support an additional set of event handling API called gesture events. The API + for handling user interaction with these gesture events includes the following classes: +

  • flash.events.TouchEvent
  • flash.events.GestureEvent
  • flash.events.GesturePhase
  • flash.events.TransformGestureEvent
  • flash.events.PressAndTapGestureEvent

+

Use the listed classes to write code that handles touch events. Use the Multitouch class to determine the + current environment's support for touch interaction, and to manage the support of touch interaction if + the current environment supports touch input.

+

You cannot create a Multitouch object directly from ActionScript code. If you call new Multitouch(), an exception is thrown.

+

Note: The Multitouch feature is not supported for SWF files embedded in HTML running on Mac OS.

+ +
The following example first checks to see if gesture events are supported + (if the machine doesn't support gesture events, the vector array Multitouch.supportedGestures + returns null and assigning null to the vector of strings causes a run-time error). + If gesture events are supported, the example displays the events from + the TransformGestureEvent class supported in the current environment: + +package { + import flash.ui.Multitouch; + import flash.ui.MultitouchInputMode; + import flash.display.Sprite; + import flash.text.TextField; + + public class MultitouchExample extends Sprite { + + Multitouch.inputMode = MultitouchInputMode.GESTURE; + + public function MultitouchExample() { + + if(Multitouch.supportsGestureEvents){ + var supportedGesturesVar:Vector.<String> = Multitouch.supportedGestures; + var deviceSupports:TextField = new TextField(); + deviceSupports.width = 200; + deviceSupports.height = 200; + deviceSupports.wordWrap = true; + + for (var i:int=0; i<supportedGesturesVar.length; ++i) { + deviceSupports.appendText(supportedGesturesVar[i] + ", "); + addChild(deviceSupports); + } + } + } + } +} +
flash.events.TouchEventflash.events.GestureEventflash.events.TransformGestureEventflash.events.GesturePhaseflash.events.PressAndTapGestureEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()Michael Chaize: Tetris, Touch API and AndroidChristian Cantrell: Multitouch and gesture support on the Flash PlatformLee Brimelow: Flash Player 10.1 multi-touch FAQPiotr Walczyszyn: Multitouch development in FlexinputMode + Identifies the multi-touch mode for touch and gesture event handling.Stringgesture + + + Identifies the multi-touch mode for touch and gesture event handling. Use this property to manage + whether or not events are dispatched as touch events with multiple points of contact and specific events + for different gestures (such as rotation and pan), or only a single point of contact (such as tap), or + none at all (contact is handled as a mouse event). To set this property, use values from the flash.ui.MultitouchInputMode class. + The following example displays a message when the + square drawn on mySprite is tapped on a touch-enabled screen: + +Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT; + +var mySprite:Sprite = new Sprite(); +var myTextField:TextField = new TextField(); + +mySprite.graphics.beginFill(0x336699); +mySprite.graphics.drawRect(0,0,40,40); +addChild(mySprite); + +mySprite.addEventListener(TouchEvent.TOUCH_TAP, taphandler); + +function taphandler(e:TouchEvent): void { + myTextField.text = "I've been tapped"; + myTextField.y = 50; + addChild(myTextField); +} +flash.ui.MultitouchInputModemaxTouchPoints + The maximum number of concurrent touch points supported by the current environment.intmaximum number of concurrent touch points for mult-touch interaction + + + The maximum number of concurrent touch points supported by the current environment. + flash.events.TouchEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()flash.events.GestureEventflash.events.TransformGestureEventsupportedGestures + A Vector array (a typed array of string values) of multi-touch contact types supported in the current environment.indicates current support for mult-touch interaction + + + A Vector array (a typed array of string values) of multi-touch contact types supported in the current environment. The array of strings + can be used as event types to register event listeners. Possible values are constants from the GestureEvent, PressAndTapGestureEvent, and + TransformGestureEvent classes (such as GESTURE_PAN). +

If the Flash runtime is in an environment that does not support any multi-touch gestures, the value is null.

+

Note: For Mac OS 10.5.3 and later, Multitouch.supportedGestures returns + non-null values (possibly indicating incorrectly that gesture events are supported) even if the current hardware does not support gesture input.

+

Use this property to test for multi-touch gesture support. Then, use event handlers for the available multi-touch + gestures. For those gestures that are not supported in the current evironment, you'll need to create alternative + event handling.

+
The following example adds the appropriate event listeners for each individual supported gesture in the current + environment. The Multitouch.supportedGestures vector array contents change to include all + the gestures available to the current software and hardware environment for the Flash runtime. If the Multitouch.supportedGestures + vector array does not contain one of the TransformGestureEvent gestures, then no event listener is added for that gesture. + This example comes from Holly Schinsky. + +Multitouch.inputMode = MultitouchInputMode.GESTURE; + + for each (var item:String in Multitouch.supportedGestures) { + trace("gesture " + item); + if (item == TransformGestureEvent.GESTURE_PAN) + img.addEventListener(TransformGestureEvent.GESTURE_PAN, onPan); + else if (item == TransformGestureEvent.GESTURE_ROTATE) + img.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate); + else if (item == TransformGestureEvent.GESTURE_SWIPE) + img.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe); + else if (item == TransformGestureEvent.GESTURE_ZOOM) + img.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom); + } +
flash.events.TouchEventflash.events.MouseEventflash.events.EventDispatcher.addEventListener()flash.events.GestureEventflash.events.PressAndTapGestureEventflash.events.TransformGestureEvent
supportsGestureEvents + Indicates whether the current environment supports gesture input, such as rotating two fingers + around a touch screen.Boolean + Indicates whether the current environment supports gesture input, such as rotating two fingers + around a touch screen. Gesture events are listed in the TransformGestureEvent, PressAndTapGestureEvent, and GestureEvent classes. +

Note: For Mac OS 10.5.3 and later, this value is always true. Multitouch.supportsGestureEvent returns + true even if the hardware does not support gesture events.

+
flash.events.TransformGestureEventflash.events.GestureEventflash.events.PressAndTapGestureEvent
supportsTouchEvents + Indicates whether the current environment supports basic touch input, such as a single finger tap.Boolean + Indicates whether the current environment supports basic touch input, such as a single finger tap. + Touch events are listed in the TouchEvent class. + The following example displays whether or not + the current environment supports touch events: + +var myTextField:TextField = new TextField(); +myTextField.width = 200; + +addEventListener(Event.ENTER_FRAME, enterhandler); + +function enterhandler(e:Event): void { +var support:Boolean = Multitouch.supportsTouchEvents; + switch (support) { + case true : + myTextField.text = "Touch events supported"; + break; + case false : + myTextField.text = "Touch events not supported"; + break; + default : + myTextField.text = "unknown"; + } + + addChild(myTextField); +} +flash.events.TouchEvent
ContextMenuItem + The ContextMenuItem class represents an item in the context + menu.flash.display:NativeMenuItem + The ContextMenuItem class represents an item in the context + menu. Each ContextMenuItem object has a caption (text) that is displayed in the context menu. To add + a new item to a context menu, you add it to the customItems array of a + ContextMenu object. + +

With the properties of the ContextMenuItem class you can enable or disable specific menu items, and you can make + items visible or invisible.

You write an event handler for the menuItemSelect event + to add functionality to the menu item when the user selects it. + +

Custom menu items appear at the top of the context menu, above any built-in items. A separator bar + divides custom menu items from built-in items. In AIR, there are no built-in items and the + following restrictions do not apply to content in the AIR application sandbox.

+

Restrictions:

+
  • You can add no more than 15 custom items to a context menu.
  • Each caption must contain at least one visible character.
  • Control characters, newlines, and other white space characters are ignored.
  • No caption can be more than 100 characters long.
  • Captions that are identical to any built-in menu item, or to another custom item, are ignored, + whether the matching item is visible or not. Menu captions are compared to built-in captions or + existing custom captions without regard to case, punctuation, or white space.
  • The following captions are not allowed, but the words may be used in conjunction with other words + to form a custom caption (for example, although "Paste" is not allowed, "Paste tastes great" is allowed): +
    + Save
    + Zoom In
    + Zoom Out
    + 100%
    + Show All
    + Quality
    + Play
    + Loop
    + Rewind
    + Forward
    + Back
    + Movie not loaded
    + About
    + Print
    + Show Redraw Regions
    + Debugger
    + Undo
    + Cut
    + Copy
    + Paste
    + Delete
    + Select All
    + Open
    + Open in new window
    + Copy link
    + 
  • None of the following words can appear in a custom caption on their own or in conjunction with other words: +
    + Adobe
    + Macromedia
    + Flash Player
    + Settings
    + 
+ +

Note: When the player is running on a non-English system, the caption strings are compared to both the English list and the localized equivalents.

+ +
The following example uses the class ContextMenuBuiltInItemsExample + to remove the default context menu items from the Stage and add a new menu item. This is + accomplished with the following steps: +
  1. A property myContextMenu is declared and then assigned to a new ContextMenu + object.
  2. The method removeDefaultItems() is called, which removes all built-in context + menu items except Print.
  3. The method addCustomMenuItems() is called, which places a menu item called + Hello World into the customItems array by using the + push() method of Array.
  4. The Hello World context menu item is added to the Stage's context + menu item list.
  5. A TextField object with the text "Right Click Here" is added to the stage.
+ +package { + import flash.ui.ContextMenu; + import flash.ui.ContextMenuItem; + import flash.ui.ContextMenuBuiltInItems; + import flash.display.Sprite; + import flash.text.TextField; + + public class ContextMenuItemExample extends Sprite { + private var myContextMenu:ContextMenu; + + public function ContextMenuItemExample() { + myContextMenu = new ContextMenu(); + removeDefaultItems(); + addCustomMenuItems(); + this.contextMenu = myContextMenu; + addChild(createLabel()); + } + + private function removeDefaultItems():void { + myContextMenu.hideBuiltInItems(); + + var defaultItems:ContextMenuBuiltInItems = myContextMenu.builtInItems; + defaultItems.print = true; + } + + private function addCustomMenuItems():void { + var item:ContextMenuItem = new ContextMenuItem("Hello World"); + myContextMenu.customItems.push(item); + } + + private function createLabel():TextField { + var txtField:TextField = new TextField(); + txtField.text = "Right Click Here"; + return txtField; + } + } +} +
ContextMenu classContextMenuBuiltInItems classmenuItemSelect + Dispatched when a user selects an item from a context menu.flash.events.ContextMenuEvent.MENU_ITEM_SELECTflash.events.ContextMenuEvent + Dispatched when a user selects an item from a context menu. + The user generates the context menu by clicking the secondary button of the user's pointing device. + ContextMenuItem + + Creates a new ContextMenuItem object that can be added to the ContextMenu.customItems + array.captionStringSpecifies the text associated with the menu item. + See the ContextMenuItem class overview for caption value restrictions. + separatorBeforeBooleanfalseSpecifies whether a separator bar appears above the + menu item in the context menu. The default value is false. + enabledBooleantrueSpecifies whether the menu item is enabled or disabled in the + context menu. The default value is true (enabled). This parameter is optional. + visibleBooleantrueSpecifies whether the menu item is visible or invisible. The + default value is true (visible). + + + + Creates a new ContextMenuItem object that can be added to the ContextMenu.customItems + array. + + clone + + Creates a copy of the NativeMenuItem object.flash.display:NativeMenuItem + + Creates a copy of the NativeMenuItem object. + + systemClearMenuItemflash.ui:ContextMenuItemsystemCopyLinkMenuItemflash.ui:ContextMenuItemsystemCopyMenuItemflash.ui:ContextMenuItemsystemCutMenuItemflash.ui:ContextMenuItemsystemOpenLinkMenuItemflash.ui:ContextMenuItemsystemPasteMenuItemflash.ui:ContextMenuItemsystemSelectAllMenuItemflash.ui:ContextMenuItemcaption + Specifies the menu item caption (text) displayed in the context menu.String + Specifies the menu item caption (text) displayed in the context menu. + See the ContextMenuItem class overview for caption value restrictions. + + separatorBefore + Indicates whether a separator bar should appear above the specified menu item.Booleanfalse + + Indicates whether a separator bar should appear above the specified menu item. + +

Note: A separator bar always appears between any custom menu items and the + built-in menu items.

+ +
visible + Indicates whether the specified menu item is visible when the Flash Player + context menu is displayed.Booleantrue + + Indicates whether the specified menu item is visible when the Flash Player + context menu is displayed. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.utils.xml b/language-server/playerglobal_docs/flash.utils.xml new file mode 100644 index 0000000..f257f34 --- /dev/null +++ b/language-server/playerglobal_docs/flash.utils.xml @@ -0,0 +1,2045 @@ +flash.utilsProxy + + The Proxy class lets you + override the default behavior of ActionScript operations + (such as retrieving and modifying properties) on an object.Object + The Proxy class lets you + override the default behavior of ActionScript operations + (such as retrieving and modifying properties) on an object. + +

The Proxy class has no constructor, and you should not attempt to instantiate Proxy. + Instead, subclass the Proxy class to override methods such as + getProperty and provide custom behavior. If you try to use a method of + the Proxy class without overriding the method, an exception is thrown.

+

And, keep in mind, your own code overriding the methods of the Proxy class can throw + exceptions unintentionally. Throwing exceptions when using these methods causes problems because + the calling code (using operators like in, is, delete and others) + does not expect exceptions. Unless you're already sure your overriding method does not throw exceptions, + Adobe recommends using try..catch statements around your implementation of the Proxy class + to avoid fatal errors when operators call your methods. For example:

+ + dynamic class MyProxy extends Proxy { + flash_proxy override function callProperty(name:~~, ...rest):~~ { + try { + // custom code here + } + catch (e:Error) { + // respond to error here + } + } + + +

The Proxy class is a replacement for the + Object.__resolve and Object.addProperty + features of ActionScript 2.0, which are no longer + available in ActionScript 3.0. The Object.addProperty() feature allowed you to + dynamically create get and set methods in ActionScript 2.0. Although ActionScript 3.0 + provides get and set methods at compile time, you cannot dynamically assign one + to an object unless you use the Proxy class.

+ +

To avoid collisions with the public namespace, + the methods of the Proxy class are in the + flash_proxy namespace.

+ +

Where methods of the Proxy class take a name + argument, name can be either a String or + a QName object (if namespaces are being used).

+ +
+package { + import flash.display.Sprite; + + public class ProxyExample extends Sprite { + public function ProxyExample() { + var arr:ProxyArray = new ProxyArray(); + arr.push(1); + arr.push(-2); + arr.push(3); + arr.push(4); + arr.push("five"); + + trace(arr.length); // 5 + trace(arr[0]); // 1 + trace(arr[1]); // -2 + trace(arr[2]); // 3 + trace(arr[3]); // 4 + + trace(arr.sum()); // 6 + + arr.clear(); + trace(arr); // (empty string) + + arr[0] = "zero"; + trace(arr); // zero + } + } +} + +import flash.utils.Proxy; +import flash.utils.flash_proxy; + +dynamic class ProxyArray extends Proxy { + private var _item:Array; + + public function ProxyArray() { + _item = new Array(); + } + + override flash_proxy function callProperty(methodName:*, ... args):* { + var res:*; + switch (methodName.toString()) { + case 'clear': + _item = new Array(); + break; + case 'sum': + var sum:Number = 0; + for each (var i:* in _item) { + // ignore non-numeric values + if (!isNaN(i)) { + sum += i; + } + } + res = sum; + break; + default: + res = _item[methodName].apply(_item, args); + break; + } + return res; + } + + override flash_proxy function getProperty(name:*):* { + return _item[name]; + } + + override flash_proxy function setProperty(name:*, value:*):void { + _item[name] = value; + } +} +
callProperty + Overrides the behavior of an object property that can be called as a function.The return value of the called method. + nameThe name of the method being invoked. + restAn array specifying the arguments to the + called method. + + Overrides the behavior of an object property that can be called as a function. When a method of + the object is invoked, this method is called. While some objects can be called as functions, + some object properties can also be called as functions. + + Function.call()ECMA-262 Language Specification, 3rd Edition, section 15deleteProperty + Overrides the request to delete a property.If the property was deleted, true; otherwise false. + BooleannameThe name of the property to delete. + + Overrides the request to delete a property. When a property is deleted + with the delete operator, this + method is called to perform the deletion. + + delete operatorECMA-262 Language Specification, 3rd Edition, 8.6.2.5getDescendants + Overrides the use of the descendant operator.The results of the descendant operator. + nameThe name of the property to descend + into the object and search for. + + Overrides the use of the descendant operator. + When the descendant operator is used, this method + is invoked. + + descendant operatorE4X SpecificationgetProperty + Overrides any request for a property's value.The specified property or undefined if the property is not found. + nameThe name of the property to retrieve. + + Overrides any request for a property's value. If the property can't be found, the method + returns undefined. For more information on this behavior, see + the ECMA-262 Language Specification, 3rd Edition, section 8.6.2.1. + + + get statementECMA-262 Language Specification, 3rd Edition, section 8.6.2.1hasProperty + Overrides a request to check whether an object has a particular property by name.If the property exists, true; otherwise false. + BooleannameThe name of the property to check for. + + Overrides a request to check whether an object has a particular property by name. + + + Object.hasOwnProperty()ECMA-262 Language Specification, 3rd Edition, section 8.6.2.4isAttribute + Checks whether a supplied QName is also marked as an attribute.Returns true if the argument for name is a QName that is also + marked as an attribute. + BooleannameThe name of the property to check. + + Checks whether a supplied QName is also marked as an attribute. + + QName classnextNameIndex + Allows enumeration of the proxied object's properties by index number.The property's index value. + intindexintThe zero-based index value where the enumeration begins. + + Allows enumeration of the proxied object's properties by index number. However, you cannot + enumerate the properties of the Proxy class themselves. + This function supports implementing for...in and + for each..in loops on the object to retrieve property index values. +

For example:

+ + protected var _item:Array; // array of object's properties + override flash_proxy function nextNameIndex (index:int):int { + // initial call + if (index == 0) { + _item = new Array(); + for (var x:~~ in _target) { + _item.push(x); + } + } + + if (index < _item.length) { + return index + 1; + } else { + return 0; + } + } + override flash_proxy function nextName(index:int):String { + return _item[index - 1]; + } + + +
Proxy.nextName()Proxy.nextValue()
nextName + Allows enumeration of the proxied object's properties by index number to + retrieve property names.The property's name. + StringindexintThe zero-based index value of the object's property. + + Allows enumeration of the proxied object's properties by index number to + retrieve property names. However, you cannot + enumerate the properties of the Proxy class themselves. + This function supports implementing for...in and + for each..in loops on the object to retrieve the desired names. +

For example (with code from Proxy.nextNameIndex()):

+ + protected var _item:Array; // array of object's properties + override flash_proxy function nextNameIndex (index:int):int { + // initial call + if (index == 0) { + _item = new Array(); + for (var x:~~ in _target) { + _item.push(x); + } + } + + if (index < _item.length) { + return index + 1; + } else { + return 0; + } + } + override flash_proxy function nextName(index:int):String { + return _item[index - 1]; + } + + +
Proxy.nextNameIndex()Proxy.nextValue()
nextValue + Allows enumeration of the proxied object's properties by index number to + retrieve property values.The property's value. + indexintThe zero-based index value of the object's property. + + Allows enumeration of the proxied object's properties by index number to + retrieve property values. However, you cannot + enumerate the properties of the Proxy class themselves. + This function supports implementing for...in and + for each..in loops on the object to retrieve the desired values. + +

For example (with code from Proxy.nextNameIndex()):

+ + protected var _item:Array; // array of object's properties + override flash_proxy function nextNameIndex (index:int):int { + // initial call + if (index == 0) { + _item = new Array(); + for (var x:~~ in _target) { + _item.push(x); + } + } + + if (index < _item.length) { + return index + 1; + } else { + return 0; + } + } + override flash_proxy function nextName(index:int):String { + return _item[index - 1]; + } + +
Proxy.nextNameIndex()Proxy.nextName()
setProperty + Overrides a call to change a property's value.nameThe name of the property to modify. + valueThe value to set the property to. + + Overrides a call to change a property's value. If the property can't be found, this method + creates a property with the specified name and value. + + set statementECMA-262 Language Specification, 3rd Edition, section 8.6.2.2
ByteArray + The ByteArray class provides methods and properties to optimize reading, writing, + and working with binary data.flash.utils:IDataInputflash.utils:IDataOutputObject + The ByteArray class provides methods and properties to optimize reading, writing, + and working with binary data. + +

Note: The ByteArray class is for advanced developers who need to access + data on the byte level.

+ +

In-memory data is a packed array (the most compact representation for the data type) + of bytes, but an instance of the ByteArray + class can be manipulated with the standard [] (array access) operators. + It also can be read and written to as an in-memory file, using + methods similar to those in the URLStream and Socket classes.

+ +

In addition, zlib compression and decompression are supported, as + well as Action Message Format (AMF) object serialization.

+ +

Possible uses of the ByteArray class include the following: + +

  • Creating a custom protocol to connect to a server.
  • Writing your own URLEncoder/URLDecoder.
  • Writing your own AMF/Remoting packet.
  • Optimizing the size of your data by using data types.
  • Working with binary data loaded from a file in + Adobe® AIR®.
+

+ +
The following example uses the class ByteArrayExample to write a Boolean + and the double-precision floating-point representation of pi to a byte array. This is accomplished + using the following steps: +
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and then check the length and + read it back.
  3. Write the double-precision floating-point equivalent of the mathematical value of pi.
  4. Read back each of the nine bytes written into the byte array.
+ +

Note: when trace() is called on a byte, it prints the decimal equivalent + of the bytes stored in the byte array.

+ +

Notice how a code segment is added at the end to check for end of file errors to ensure that + the byte stream is not read past its end.

+ +package { + import flash.display.Sprite; + import flash.utils.ByteArray; + import flash.errors.EOFError; + + public class ByteArrayExample extends Sprite { + public function ByteArrayExample() { + var byteArr:ByteArray = new ByteArray(); + + byteArr.writeBoolean(false); + trace(byteArr.length); // 1 + trace(byteArr[0]); // 0 + + byteArr.writeDouble(Math.PI); + trace(byteArr.length); // 9 + trace(byteArr[0]); // 0 + trace(byteArr[1]); // 64 + trace(byteArr[2]); // 9 + trace(byteArr[3]); // 33 + trace(byteArr[4]); // 251 + trace(byteArr[5]); // 84 + trace(byteArr[6]); // 68 + trace(byteArr[7]); // 45 + trace(byteArr[8]); // 24 + + byteArr.position = 0; + + try { + trace(byteArr.readBoolean() == false); // true + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); // 3.141592653589793 + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + } + } +} +
[] (array access)Socket classURLStream classByteArray + Creates a ByteArray instance representing a packed array of bytes, so that you can use the methods and properties in this class to optimize your data storage and stream. + Creates a ByteArray instance representing a packed array of bytes, so that you can use the methods and properties in this class to optimize your data storage and stream. + clear + Clears the contents of the byte array and resets the length + and position properties to 0. + Clears the contents of the byte array and resets the length + and position properties to 0. Calling this method explicitly + frees up the memory used by the ByteArray instance. + + compress + Compresses the byte array.algorithmStringunknownThe compression algorithm to use when compressing. Valid values are defined as + constants in the CompressionAlgorithm class. The default is to use zlib format. + This parameter is only recognized for content running in Adobe AIR. + Flash Player supports only the default algorithm, zlib, and throws an exception if you attempt to pass + a value for this parameter. Calling compress(CompressionAlgorithm.DEFLATE) + has the same effect as calling the deflate() method. + + + Compresses the byte array. The entire byte array is compressed. For content + running in Adobe AIR, you can specify a compression algorithm by passing a + value (defined in the CompressionAlgorithm class) as the algorithm + parameter. Flash Player supports only the default + algorithm, zlib. + +

After the call, the length property of the ByteArray is set to the new length. + The position property is set to the end of the byte array.

+ +

The zlib compressed data format is described at + http://www.ietf.org/rfc/rfc1950.txt.

+ +

The deflate compression algorithm is described at + http://www.ietf.org/rfc/rfc1951.txt.

+ +

The deflate compression algorithm is used in several compression + formats, such as zlib, gzip, some zip implementations, and others. When data is + compressed using one of those compression formats, in addition to storing + the compressed version of the original data, the compression format data + (for example, the .zip file) includes metadata information. Some examples of + the types of metadata included in various file formats are file name, + file modification date/time, original file size, optional comments, checksum + data, and more.

+ +

For example, when a ByteArray is compressed using the zlib algorithm, + the resulting ByteArray is structured in a specific format. Certain bytes contain + metadata about the compressed data, while other bytes contain the actual compressed + version of the original ByteArray data. As defined by the zlib compressed data + format specification, those bytes (that is, the portion containing + the compressed version of the original data) are compressed using the deflate + algorithm. Consequently those bytes are identical to the result of calling + compress(air.CompressionAlgorithm.DEFLATE) + on the original ByteArray. However, the result from + compress(air.CompressionAlgorithm.ZLIB) includes + the extra metadata, while the compress(CompressionAlgorithm.DEFLATE) + result includes only the compressed version of the original ByteArray data and nothing else.

+ +

In order to use the deflate format to compress a ByteArray instance's + data in a specific format such as gzip or zip, you cannot simply call + compress(CompressionAlgorithm.DEFLATE). + You must create a ByteArray structured + according to the compression format's specification, including the appropriate + metadata as well as the compressed data obtained using the deflate format. + Likewise, in order to decode data compressed in a format such + as gzip or zip, you can't simply call uncompress(CompressionAlgorithm.DEFLATE) + on that data. First, you must separate the metadata from the compressed data, and you can + then use the deflate format to decompress the compressed data.

+ +
uncompress()flash.utils.CompressionAlgorithm
deflate + Compresses the byte array using the deflate compression algorithm. + Compresses the byte array using the deflate compression algorithm. + The entire byte array is compressed. + +

After the call, the length property of the ByteArray is set to the new length. + The position property is set to the end of the byte array.

+ +

The deflate compression algorithm is described at + http://www.ietf.org/rfc/rfc1951.txt.

+ +

In order to use the deflate format to compress a ByteArray instance's + data in a specific format such as gzip or zip, you cannot simply call + deflate(). You must create a ByteArray structured + according to the compression format's specification, including the appropriate + metadata as well as the compressed data obtained using the deflate format. + Likewise, in order to decode data compressed in a format such + as gzip or zip, you can't simply call inflate() + on that data. First, you must separate the metadata from the compressed data, and you can + then use the deflate format to decompress the compressed data.

+ +
inflate()
inflate + Decompresses the byte array using the deflate compression algorithm.The data is not valid compressed data; it was not compressed with the + same compression algorithm used to compress. + + IOErrorflash.errors:IOError + Decompresses the byte array using the deflate compression algorithm. + The byte array must have been compressed using the same algorithm. + +

After the call, the length property of the ByteArray is set to the new length. + The position property is set to 0.

+ +

The deflate compression algorithm is described at + http://www.ietf.org/rfc/rfc1951.txt.

+ +

In order to decode data compressed in a format that uses the deflate compression algorithm, + such as data in gzip or zip format, it will not work to simply call inflate() on + a ByteArray containing the compression formation data. First, you must separate the metadata that is + included as part of the compressed data format from the actual compressed data. For more + information, see the compress() method description.

+ +
deflate()
readBoolean + Reads a Boolean value from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorReturns true if the byte is nonzero, false otherwise. + + Boolean + Reads a Boolean value from the byte stream. A single byte is read, + and true is returned if the byte is nonzero, + false otherwise. + + readByte + Reads a signed byte from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorAn integer between -128 and 127. + int + Reads a signed byte from the byte stream. +

The returned value is in the range -128 to 127.

+
readBytes + Reads the number of data bytes, specified by the length parameter, from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe value of the supplied offset and length, combined, is greater than the maximum for a uint. + RangeErrorRangeErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. + offsetuint0The offset (position) in bytes at which the read data should be written. + lengthuint0The number of bytes to read. The default value of 0 causes all available data to be read. + + + Reads the number of data bytes, specified by the length parameter, from the byte stream. + The bytes are read into the ByteArray object specified by the bytes parameter, + and the bytes are written into the destination ByteArray starting at the position specified by offset. + + readDouble + Reads an IEEE 754 double-precision (64-bit) floating-point number from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA double-precision (64-bit) floating-point number. + + Number + Reads an IEEE 754 double-precision (64-bit) floating-point number from the byte stream. + + readFloat + Reads an IEEE 754 single-precision (32-bit) floating-point number from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA single-precision (32-bit) floating-point number. + + Number + Reads an IEEE 754 single-precision (32-bit) floating-point number from the byte stream. + + readInt + Reads a signed 32-bit integer from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA 32-bit signed integer between -2147483648 and 2147483647. + int + Reads a signed 32-bit integer from the byte stream. + +

The returned value is in the range -2147483648 to 2147483647.

+ +
readMultiByte + Reads a multibyte string of specified length from the byte stream using the + specified character set.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorUTF-8 encoded string. + StringlengthuintThe number of bytes from the byte stream to read. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift-jis", "cn-gb", + "iso-8859-1", and others. + For a complete list, see Supported Character Sets. +

Note: If the value for the charSet parameter + is not recognized by the current system, the application uses the system's default + code page as the character set. For example, a value for the charSet parameter, + as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of + 1 might work on your development system, but not on another system. + On the other system, the application will use the system's default code page.

+ +
+ Reads a multibyte string of specified length from the byte stream using the + specified character set. + + +
readObject + Reads an object from the byte array, encoded in AMF + serialized format.There is not sufficient data available + to read. + + EOFErrorflash.errors:EOFErrorThe deserialized object. + + Reads an object from the byte array, encoded in AMF + serialized format. + + flash.net.registerClassAlias()readShort + Reads a signed 16-bit integer from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA 16-bit signed integer between -32768 and 32767. + int + Reads a signed 16-bit integer from the byte stream. + +

The returned value is in the range -32768 to 32767.

+ +
readUTFBytes + Reads a sequence of UTF-8 bytes specified by the length + parameter from the byte stream and returns a string.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA string composed of the UTF-8 bytes of the specified length. + StringlengthuintAn unsigned short indicating the length of the UTF-8 bytes. + + Reads a sequence of UTF-8 bytes specified by the length + parameter from the byte stream and returns a string. + + readUTF + Reads a UTF-8 string from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorUTF-8 encoded string. + String + Reads a UTF-8 string from the byte stream. The string + is assumed to be prefixed with an unsigned short indicating + the length in bytes. + + + flash.utils.IDataInput.readUTF()readUnsignedByte + Reads an unsigned byte from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA 32-bit unsigned integer between 0 and 255. + uint + Reads an unsigned byte from the byte stream. + +

The returned value is in the range 0 to 255.

+ +
readUnsignedInt + Reads an unsigned 32-bit integer from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA 32-bit unsigned integer between 0 and 4294967295. + uint + Reads an unsigned 32-bit integer from the byte stream. + +

The returned value is in the range 0 to 4294967295.

+ +
readUnsignedShort + Reads an unsigned 16-bit integer from the byte stream.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA 16-bit unsigned integer between 0 and 65535. + uint + Reads an unsigned 16-bit integer from the byte stream. + +

The returned value is in the range 0 to 65535.

+
toString + Converts the byte array to a string.The string representation of the byte array. + + String + Converts the byte array to a string. + If the data in the array begins with a Unicode byte order mark, the application will honor that mark + when converting to a string. If System.useCodePage is set to true, the + application will treat the data in the array as being in the current system code page when converting. + + uncompress + Decompresses the byte array.The data is not valid compressed data; it was not compressed with the + same compression algorithm used to compress. + + IOErrorflash.errors:IOErroralgorithmStringunknownThe compression algorithm to use when decompressing. This must be the + same compression algorithm used to compress the data. Valid values are defined as + constants in the CompressionAlgorithm class. The default is to use zlib format. This parameter + is only recognized for content running in Adobe AIR. Flash Player + supports only the default algorithm, zlib, and throws an exception if you attempt to pass + a value for this parameter. + + + Decompresses the byte array. For content running in Adobe AIR, you can specify + a compression algorithm by passing a value (defined in the CompressionAlgorithm class) + as the algorithm parameter. The byte array must have been compressed + using the same algorithm. Flash Player supports only the + default algorithm, zlib. + +

After the call, the length property of the ByteArray is set to the new length. + The position property is set to 0.

+ +

The zlib compressed data format is described at + http://www.ietf.org/rfc/rfc1950.txt.

+ +

The deflate compression algorithm is described at + http://www.ietf.org/rfc/rfc1951.txt.

+ +

In order to decode data compressed in a format that uses the deflate compression algorithm, + such as data in gzip or zip format, it will not work to call + uncompress(CompressionAlgorithm.DEFLATE) on + a ByteArray containing the compression formation data. First, you must separate the metadata that is + included as part of the compressed data format from the actual compressed data. For more + information, see the compress() method description.

+ +
compress()flash.utils.CompressionAlgorithm
writeBoolean + Writes a Boolean value.valueBooleanA Boolean value determining which byte is written. If the parameter is true, + the method writes a 1; if false, the method writes a 0. + + + Writes a Boolean value. A single byte is written according to the value parameter, + either 1 if true or 0 if false. + + writeByte + Writes a byte to the byte stream.valueintA 32-bit integer. The low 8 bits are written to the byte stream. + + Writes a byte to the byte stream. +

The low 8 bits of the + parameter are used. The high 24 bits are ignored.

+ +
writeBytes + Writes a sequence of length bytes from the + specified byte array, bytes, + starting offset(zero-based index) bytes + into the byte stream.bytesflash.utils:ByteArrayThe ByteArray object. + offsetuint0A zero-based index indicating the position into the array to begin writing. + lengthuint0An unsigned integer indicating how far into the buffer to write. + + Writes a sequence of length bytes from the + specified byte array, bytes, + starting offset(zero-based index) bytes + into the byte stream. + +

If the length parameter is omitted, the default + length of 0 is used; the method writes the entire buffer starting at + offset. + If the offset parameter is also omitted, the entire buffer is + written.

If offset or length + is out of range, they are clamped to the beginning and end + of the bytes array.

+ +
writeDouble + Writes an IEEE 754 double-precision (64-bit) floating-point number to the byte stream.valueNumberA double-precision (64-bit) floating-point number. + + Writes an IEEE 754 double-precision (64-bit) floating-point number to the byte stream. + + writeFloat + Writes an IEEE 754 single-precision (32-bit) floating-point number to the byte stream.valueNumberA single-precision (32-bit) floating-point number. + + Writes an IEEE 754 single-precision (32-bit) floating-point number to the byte stream. + + writeInt + Writes a 32-bit signed integer to the byte stream.valueintAn integer to write to the byte stream. + + Writes a 32-bit signed integer to the byte stream. + + writeMultiByte + Writes a multibyte string to the byte stream using the specified character set.valueStringThe string value to be written. + charSetStringThe string denoting the character set to use. Possible character set strings + include "shift-jis", "cn-gb", "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + + Writes a multibyte string to the byte stream using the specified character set. + + writeObject + Writes an object into the byte array in AMF + serialized format.objectThe object to serialize. + + + Writes an object into the byte array in AMF + serialized format. + + flash.net.registerClassAlias()writeShort + Writes a 16-bit integer to the byte stream.valueint32-bit integer, whose low 16 bits are written to the byte stream. + + Writes a 16-bit integer to the byte stream. The low 16 bits of the parameter are used. + The high 16 bits are ignored. + + writeUTFBytes + Writes a UTF-8 string to the byte stream.valueStringThe string value to be written. + + Writes a UTF-8 string to the byte stream. Similar to the writeUTF() method, + but writeUTFBytes() does not prefix the string with a 16-bit length word. + + writeUTF + Writes a UTF-8 string to the byte stream.If the length is larger than + 65535. + + RangeErrorRangeErrorvalueStringThe string value to be written. + + Writes a UTF-8 string to the byte stream. The length of the UTF-8 string in bytes + is written first, as a 16-bit integer, followed by the bytes representing the + characters of the string. + + writeUnsignedInt + Writes a 32-bit unsigned integer to the byte stream.valueuintAn unsigned integer to write to the byte stream. + + Writes a 32-bit unsigned integer to the byte stream. + + bytesAvailable + The number of bytes of data available for reading + from the current position in the byte array to the + end of the array.uint + The number of bytes of data available for reading + from the current position in the byte array to the + end of the array. + +

Use the bytesAvailable property in conjunction + with the read methods each time you access a ByteArray object + to ensure that you are reading valid data.

+ +
defaultObjectEncoding + Denotes the default object encoding for the ByteArray class to use for a new ByteArray instance.uint + Denotes the default object encoding for the ByteArray class to use for a new ByteArray instance. + When you create a new ByteArray instance, the encoding on that instance starts + with the value of defaultObjectEncoding. + The defaultObjectEncoding property is initialized to ObjectEncoding.AMF3. + + +

When an object is written to or read from binary data, the objectEncoding value + is used to determine whether the ActionScript 3.0, ActionScript2.0, or ActionScript 1.0 format should be used. The value is a + constant from the ObjectEncoding class.

+ +
ObjectEncoding classflash.utils.ByteArray.objectEncoding
endian + Changes or reads the byte order for the data; either Endian.BIG_ENDIAN or + Endian.LITTLE_ENDIAN.String + Changes or reads the byte order for the data; either Endian.BIG_ENDIAN or + Endian.LITTLE_ENDIAN. + + Endian classlength + The length of the ByteArray object, in bytes.uint + The length of the ByteArray object, in bytes. + +

If the length is set to a value that is larger than the current length, + the right side of the byte array is filled with zeros.

+ +

If the length is set to a value that is smaller than the + current length, the byte array is truncated.

+ +
objectEncoding + Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be + used when writing to, or reading from, a ByteArray instance.uint + Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be + used when writing to, or reading from, a ByteArray instance. The value is a + constant from the ObjectEncoding class. + + ObjectEncoding classflash.utils.ByteArray.defaultObjectEncodingposition + Moves, or returns the current position, in bytes, of the file + pointer into the ByteArray object.uint + Moves, or returns the current position, in bytes, of the file + pointer into the ByteArray object. This is the + point at which the next call to a read + method starts reading or a write + method starts writing. + +
IDataOutput +The IDataOutput interface provides a set of methods for writing binary data. +The IDataOutput interface provides a set of methods for writing binary data. +This interface is the I/O counterpart to the IDataInput interface, which +reads binary data. The IDataOutput interface is implemented by the FileStream, Socket +and ByteArray classes. +

All IDataInput and IDataOutput operations are "bigEndian" by default (the most significant +byte in the sequence is stored at the lowest or first storage address), +and are nonblocking.

+

Sign extension matters only when you read data, not when you write it. Therefore, you do not need separate +write methods to work with IDataInput.readUnsignedByte() and +IDataInput.readUnsignedShort(). In other words:

+
  • Use IDataOutput.writeByte() with IDataInput.readUnsignedByte() and + IDataInput.readByte().
  • Use IDataOutput.writeShort() with IDataInput.readUnsignedShort() and + IDataInput.readShort().
+ + + +
The following example uses the class DataOutputExample to write a boolean + and the double-precision floating-point representation of pi to a byte array. This is accomplished + using the following steps: +
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and the double-precision + floating-point equivalent of the mathematical value of pi.
  3. Read back the boolean and double-precision floating-point number.
+ +

Notice how a code segment is added at the end to check for end of file errors to ensure that + the byte stream is not read past its end.

+ +package { + import flash.display.Sprite; + import flash.utils.ByteArray; + import flash.errors.EOFError; + + public class DataOutputExample extends Sprite { + public function DataOutputExample() { + var byteArr:ByteArray = new ByteArray(); + + byteArr.writeBoolean(false); + byteArr.writeDouble(Math.PI); + + byteArr.position = 0; + + try { + trace(byteArr.readBoolean()); // false + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); // 3.141592653589793 + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + } + } +} +
IDataInput interfaceendianFileStream classSocket classURLStream classByteArray classwriteBoolean + Writes a Boolean value.valueBooleanA Boolean value determining which byte is written. If the parameter is true, + 1 is written; if false, 0 is written. + + + Writes a Boolean value. A single byte is written according to the value parameter, + either 1 if true or 0 if false. + + writeByte + Writes a byte.valueintA byte value as an integer. + + + Writes a byte. + The low 8 bits of the + parameter are used; the high 24 bits are ignored. + writeBytes + Writes a sequence of bytes from the + specified byte array, bytes, + starting at the byte specified by offset + (using a zero-based index) + with a length specified by length, + into the file stream, byte stream, or byte array.bytesflash.utils:ByteArrayThe byte array to write. + offsetuint0A zero-based index specifying the position into the array to begin writing. + lengthuint0An unsigned integer specifying how far into the buffer to write. + + + Writes a sequence of bytes from the + specified byte array, bytes, + starting at the byte specified by offset + (using a zero-based index) + with a length specified by length, + into the file stream, byte stream, or byte array. + +

If the length parameter is omitted, the default + length of 0 is used and the entire buffer starting at + offset is written. + If the offset parameter is also omitted, the entire buffer is + written.

+ +

If the offset or length parameter + is out of range, they are clamped to the beginning and end + of the bytes array.

+
writeDouble + Writes an IEEE 754 double-precision (64-bit) floating point number.valueNumberA double-precision (64-bit) floating point number. + + + Writes an IEEE 754 double-precision (64-bit) floating point number. + writeFloat + Writes an IEEE 754 single-precision (32-bit) floating point number.valueNumberA single-precision (32-bit) floating point number. + + + Writes an IEEE 754 single-precision (32-bit) floating point number. + writeInt + Writes a 32-bit signed integer.valueintA byte value as a signed integer. + + + Writes a 32-bit signed integer. + writeMultiByte + Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set.valueStringThe string value to be written. + charSetStringThe string denoting the character set to use. Possible character set strings + include "shift-jis", "cn-gb", "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + + Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set. + + writeObject + Writes an object to the file stream, byte stream, or byte array, in AMF serialized + format.objectThe object to be serialized. + + + Writes an object to the file stream, byte stream, or byte array, in AMF serialized + format. + objectEncodingflash.net.registerClassAlias()writeShort + Writes a 16-bit integer.valueintA byte value as an integer. + + + Writes a 16-bit integer. The low 16 bits of the parameter are used; + the high 16 bits are ignored. + writeUTFBytes + Writes a UTF-8 string.valueStringThe string value to be written. + + + Writes a UTF-8 string. Similar to writeUTF(), + but does not prefix the string with a 16-bit length word. + writeUTF + Writes a UTF-8 string to the file stream, byte stream, or byte array.If the length is larger than + 65535. + + RangeErrorRangeErrorvalueStringThe string value to be written. + + + Writes a UTF-8 string to the file stream, byte stream, or byte array. The length of the UTF-8 string in bytes + is written first, as a 16-bit integer, followed by the bytes representing the + characters of the string. + writeUnsignedInt + Writes a 32-bit unsigned integer.valueuintA byte value as an unsigned integer. + + + Writes a 32-bit unsigned integer. + endian + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN + constant from the Endian class.String + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN + constant from the Endian class. + + Endian classobjectEncoding + Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the + writeObject() method.uint + Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the + writeObject() method. The value is a constant from the ObjectEncoding class. + + IDataInput.readObject()writeObject()ObjectEncoding class
Endian + The Endian class contains values that denote the byte order used to represent multibyte + numbers.Object + The Endian class contains values that denote the byte order used to represent multibyte + numbers. The byte order is either bigEndian (most significant byte first) or littleEndian (least + significant byte first). + +

Content in Flash Player or Adobe® + AIR™ can interface with a server by using the binary protocol of that + server, directly. Some servers use the bigEndian byte order and some servers use the + littleEndian byte order. Most servers on the Internet use the bigEndian byte order + because "network byte order" is bigEndian. The littleEndian byte order is + popular because the Intel x86 architecture uses it. Use the endian byte order that + matches the protocol of the server that is sending or receiving data.

+ + +
flash.utils.ByteArray.endianflash.filesystem.FileStream.endianflash.utils.IDataInput.endianflash.utils.IDataOutput.endianflash.net.Socket.endianflash.net.URLStream.endianBIG_ENDIAN + Indicates the most significant byte of the multibyte number appears first in the sequence of bytes.bigEndianString + Indicates the most significant byte of the multibyte number appears first in the sequence of bytes. +

The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). + The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent + decimal number, 305419896, the most significant digit is 3, and the least significant digit + is 6).

+

A stream using the bigEndian byte order (the most significant byte first) + writes:

+
+	 12 34 56 78
+	 
+ +
LITTLE_ENDIAN + Indicates the least significant byte of the multibyte number appears first in the sequence of bytes.littleEndianString + Indicates the least significant byte of the multibyte number appears first in the sequence of bytes. +

The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). + The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent + decimal number, 305419896, the most significant digit is 3, and the least significant digit + is 6).

+

A stream using the littleEndian byte order (the least significant byte + first) writes:

+
+	 78 56 34 12
+	 
+ +
IExternalizable + The IExternalizable interface provides control over serialization of a class as it is encoded + into a data stream. + The IExternalizable interface provides control over serialization of a class as it is encoded + into a data stream. The writeExternal() and + readExternal() methods of the IExternalizable interface are implemented by a class to allow customization + of the contents and format of the data stream (but not the classname or type) for an object and its supertypes. + Each individual class must serialize and reconstruct the state of its instances. These methods must be symmetrical with + the supertype to save its state. These methods supercede the native Action Message Format (AMF) serialization behavior. +

If a class does not implement, nor inherits from a class which implements, the IExternalizable interface, then an instance + of the class will be serialized using the default mechanism of public members only. As a result, private, internal, and + protected members of a class will not be available.

+

To serialize private members, a class must use the IExternalizable interface. + For example, the following class will not serialize any of its members because they are private:

+ + class Example { + + private var one:int; + private var two:int; + } + +

However, if you implement the IExternalizable interface, you can write to, and read from, the data stream the private + members of the class as follows:

+ + class Example implement IExternalizable { + + private var one:int; + private var two:int; + + public function writeExternal(output:IDataOutput) { + + output.writeInt(one); + output.writeInt(two); + } + + public function readExternal(input:IDataInput) { + + one = input.readInt(); + two = input.readInt(); + } + } + +

Note: If a class implements IExternalizable the default serialization no longer applies to instances + of that class. If that class inherits public members from a super class, you must carefully manage those members as well.

+

When a subclass of a class implementing IExternalizable has private members of its own, the subclass must override the + methods of IExternalizable, as follows:

+ + public class Base implements IExternalizable { + + private var one:Boolean; + + public function writeExternal(output:IDataOutput):void { + + output.writeBoolean(one); + } + + public function readExternal(input:IDataInput):void { + + one = input.readBoolean(); + } + } + + public class Example extends Base { + + private var one:String; + + + public override function writeExternal(output:IDataOutput):void { + + super.writeExternal(output); + output.writeUTF(one); + } + + public override function readExternal(input:IDataInput):void { + + super.readExternal(input); + one = input.readUTF(); + } + } + +

The IExternalizable interface can also be used to compress data before writing it to a data stream. + For example:

+ + class Example implements IExternalizable { + + public var one:Boolean; + public var two:Boolean; + public var three:Boolean; + public var four:Boolean; + public var five:Boolean; + public var six:Boolean; + public var seven:Boolean; + public var eight:Boolean; + + public function writeExternal(output:IDataOutput) { + + var flag:int = 0; + + if (one) flag |= 1; + if (two) flag |= 2; + if (three) flag |= 4; + if (four) flag |= 8; + if (five) flag |= 16; + if (six) flag |= 32; + if (seven) flag |= 64; + if (eight) flag |= 128; + + output.writeByte(flag); + } + + public function readExternal(input:IDataInput) { + + var flag:int = input.readByte(); + + one = (flag & 1) != 0; + two = (flag & 2) != 0; + three = (flag & 4) != 0; + four = (flag & 8) != 0; + five = (flag & 16) != 0; + six = (flag & 32) != 0; + seven = (flag & 64) != 0; + eight = (flag & 128) != 0; + } + } + +
flash.net.ObjectEncodingreadExternal + A class implements this method to decode itself from a data stream by calling the methods of the IDataInput + interface.inputflash.utils:IDataInputThe name of the class that implements the IDataInput interface. + + A class implements this method to decode itself from a data stream by calling the methods of the IDataInput + interface. This method must read the values in the same sequence and with the same types as + were written by the writeExternal() method. + writeExternal + A class implements this method to encode itself for a data stream by calling the methods of the IDataOutput + interface.outputflash.utils:IDataOutputThe name of the class that implements the IDataOutput interface. + + A class implements this method to encode itself for a data stream by calling the methods of the IDataOutput + interface. +
describeType + Produces an XML object that describes the ActionScript object named as the parameter of + the method.An XML object containing details about the object that was passed in as a parameter. + It provides the following information about the object: + +
  • The class of the object
  • The attributes of the class
  • The inheritance tree from the class to its base classes
  • The interfaces implemented by the class
  • The declared instance properties of the class
  • The declared static properties of the class
  • The instance methods of the class
  • The static methods of the class
  • For each method of the class, the name, number of parameters, return type, + and parameter types
+

Note: describeType() only shows public properties and methods, and will not show + properties and methods that are private, package internal or in custom namespaces.

+ +
XML
valueThe object for which a type description is desired. Any ActionScript value + may be passed to this method including all available ActionScript types, object + instances, primitive types such as uint, and class objects. + +
+ Produces an XML object that describes the ActionScript object named as the parameter of + the method. This method implements the programming concept of reflection for the + ActionScript language. +

If the value parameter is an instance of a type, the returned XML object includes all the instance properties of that type, + but does not include any static properties. You can check for this condition when you parse the XML object by examining the value of the <type> tag's isStatic attribute, which is false when the value parameter is an instance of a type.

+

To obtain the static properties of a type, pass the type itself for the value parameter. The returned XML object includes not only the type's static properties, but also all of its instance properties. + The instance properties are nested inside a tag named <factory> to distinguish them from the static properties. + In this case, the isStatic attribute of the <type> tag is true.

+

Note: If you need only to traverse an object's inheritance hierarchy and do not need the other information provided by describeType(), + use the getQualifiedClassName() and getQualifiedSuperclassName() functions instead.

+

The following table describes some of the tags and attributes of the XML object generated by describeType() + (all class and interface names returned are in fully qualified format):

+ TagAttributeDescription<type> The root tag of the XML object. nameThe name of the ActionScript object's data type. baseThe immediate superclass of the ActionScript object's defining class. If the ActionScript object is a class object, the value is Class. isDynamictrue if the ActionScript object's defining class is dynamic; false otherwise. If the ActionScript object is a class object, the value is true because the Class class is dynamic. isFinaltrue if the ActionScript object's defining class is final; false otherwise. isStatictrue if the ActionScript object is a class object or constructor function; false otherwise. This attribute is named isStatic because if it is true, any tags that are not nested inside the factory tag are static.<extendsClass> There is a separate extendsClass tag for each superclass of the ActionScript object's defining class. typeThe name of a superclass that the ActionScript object's defining class extends.<implementsInterface> There is a separate implementsInterface tag for each interface implemented by the ActionScript object's defining class or any of its superclasses. typeThe name of an interface that the ActionScript object's defining class implements.<accessor> An accessor is a property defined by getter and setter functions. nameThe name of the accessor. accessThe access rights of the property. Possible values include readonly, writeonly, and readwrite. typeThe data type of the property. declaredByThe class that contains the associated getter or setter functions.<constant> A constant is a property defined with the const statement. nameThe name of the constant. typeThe data type of the constant.<method> A method is a function declared as part of a class definition. nameThe name of the method. declaredByThe class that contains the method definition. returnTypeThe data type of the method's return value.<parameter> There is a separate parameter tag for each parameter that a method defines. This tag is always nested inside a <method> tag. indexA number corresponding to the order in which the parameter appears in the method's parameter list. The first parameter has a value of 1. typeThe data type of the parameter. optionaltrue if the parameter is optional; false otherwise.<variable> A variable is a property defined with the var statement. nameThe name of the variable. typeThe data type of the variable.<factory> If the ActionScript object is a class object or constructor function, all instance properties and methods are nested inside this tag. If the isStatic attribute of the <type> tag is true, all properties and methods that are not nested within the <factory> tag are static. This tag appears only if the ActionScript object is a class object or constructor function. + + +
package { + import flash.display.Sprite; + import flash.utils.describeType; + + public class DescribeTypeExample extends Sprite { + public function DescribeTypeExample() { + var child:Sprite = new Sprite(); + var description:XML = describeType(child); + trace(description..accessor.@name.toXMLString()); + } + } +} +
getQualifiedClassName()getQualifiedSuperclassName()
escapeMultiByte + Returns an escaped copy of the input string encoded as either UTF-8 or system code page, depending on the value of System.useCodePage.An escaped copy of the input string. If System.useCodePage is true, the escaped string is encoded in the system code page. + If System.useCodePage is false, the escaped string is encoded in UTF-8. + For example, the input string "Crüe" will be escaped as "Cr%C3%BCe" on all systems if System.useCodePage is false. + If system.useCodePage is true, and the system uses a Latin code page, "Crüe" will be escaped as "Cr%FCe". + If the system uses a non Latin code page that does not contain the letter 'ü' the result will probably be "Cr?e". + Unescaping "Cr%C3%BCe" with System.useCodePage set to true will produce different undesired results on different systems, such as "Crüe" on a Latin system. + Similarly, unescaping "Cr%FCe" with System.useCodePage set to false could produce "Cre" or "Cr?e" or other variations depending on the code page of the system. + + + StringvalueStringThe string to be escaped. + + + Returns an escaped copy of the input string encoded as either UTF-8 or system code page, depending on the value of System.useCodePage. + Use of System.useCodePage allows legacy content encoded in local code pages to be accessed by the runtime, but only on systems using that legacy code page. + For example, Japanese data encoded as Shift-JIS will only be escaped and unescaped properly on an OS using a Japanese default code page. + + getDefinitionByName + Returns a reference to the class object of the class specified by the name parameter.No public definition exists with the + specified name. + + ReferenceErrorReferenceErrorReturns a reference to the class object of the class specified by the name parameter. + + ObjectnameStringThe name of a class. + + Returns a reference to the class object of the class specified by the name parameter. + The following example uses the class GetDefinitionByNameExample to + create an orange square on the stage. This is accomplished using the following steps: +
  1. Variables for the background color of orange and size of 80 pixels are declared, + which will later be used in drawing the square.
  2. Within the constructor, a variable ClassReference of type Class is + assigned to Sprite.
  3. An instance of ClassReference called instance is instantiated.
  4. Since instance is, by reference, a Sprite object, a square can be + drawn and added to the display list using the methods available to Sprite.
+ +package { + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.utils.getDefinitionByName; + + public class GetDefinitionByNameExample extends Sprite { + private var bgColor:uint = 0xFFCC00; + private var size:uint = 80; + + public function GetDefinitionByNameExample() { + var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class; + var instance:Object = new ClassReference(); + instance.graphics.beginFill(bgColor); + instance.graphics.drawRect(0, 0, size, size); + instance.graphics.endFill(); + addChild(DisplayObject(instance)); + } + } +} +
getQualifiedClassName + Returns the fully qualified class name of an object.A string containing the fully qualified class name. + StringvalueThe object for which a fully qualified class name is desired. Any ActionScript value + may be passed to this method including all available ActionScript types, object + instances, primitive types such as uint, and class objects. + + + Returns the fully qualified class name of an object. + + describeType()getQualifiedSuperclassName()getQualifiedSuperclassName + Returns the fully qualified class name of the base class of the object specified by the value + parameter.A fully qualified base class name, or null if none exists. + StringvalueAny value. + + Returns the fully qualified class name of the base class of the object specified by the value + parameter. This function provides a quicker way of retrieving the base class name than describeType(), but also + doesn't provide all the information describeType() does. +

After you retrieve the name of a class with this function, you can convert the class name to a class reference with the getDefinitionByName() function.

+

Note: This function restricts itself to instance hierarchies, whereas the describeType() function + uses class object hierarchies if the value parameter is a data type. Calling describeType() on a data type returns the + superclass based on the class object hierarchy, in which all class objects inherit from Class. The getQualifiedSuperclassName() + function, however, ignores the class object hierarchy and returns the superclass based on the more familiar instance hierarchy. + For example, calling getQualifiedSuperclassName(String) + returns Object although technically the String class object inherits from Class. In other words, the results are + the same whether you use an instance of a type or the type itself.

+
describeType()getDefinitionByName()getQualifiedClassName()
getTimer + Used to compute relative time.The number of milliseconds since the runtime was initialized (while processing ActionScript 2.0), or since the virtual machine started (while + processing ActionScript 3.0). If the runtime starts playing one + SWF file, and another SWF file is loaded later, the return value is relative to when the first SWF file was + loaded. + + int + Used to compute relative time. For a Flash runtime processing ActionScript 3.0, this method returns the number of milliseconds that have elapsed + since the Flash runtime virtual machine for ActionScript 3.0 (AVM2) started. For a Flash runtime processing ActionScript 2.0, this method returns + the number of milliseconds since the Flash runtime began initialization. Flash runtimes use two + virtual machines to process ActionScript. AVM1 is the ActionScript virtual machine used to run ActionScript 1.0 and 2.0. + AVM2 is the ActionScript virtual machine used to run ActionScript 3.0. The getTimer() method behavior for AVM1 is different than the + behavior for AVM2. +

For a calendar date (timestamp), see the Date object.

+ +
The following example uses the class GetTimerExample to get and print the + number of milliseconds since the runtime initialized. + +package { + import flash.utils.getTimer; + import flash.display.Sprite; + + public class GetTimerExample extends Sprite { + public function GetTimerExample() { + var duration:uint = getTimer(); + trace("duration: " + duration); + } + } +} +
flash.display.AVM1MovieDate class
unescapeMultiByte + Returns an unescaped copy of the input string, which is decoded from either system code page page or UTF-8 depending on the value of System.useCodePage.An unescaped copy of the input string. If System.useCodePage is true, the escaped string is decoded from the system code page. + If System.useCodePage is false, the escaped string is decoded from UTF-8. + For example, if the input string is "Crüe" and System.useCodePage is false, the result will be "Crüe" on all systems. + If System.useCodePage is true and the input string is "Cr%FCe", and the system uses a Latin code page, the result will also be "Crüe". + Unescaping "Cr%C3%BCe" with System.useCodePage set to true will produce different undesired results on different systems, such as "Crüe" on a Latin system. + Similarly, unescaping "Cr%FCe" with System.useCodePage set to false could produce "Cre" or "Cr?e" or other variations depending on the code page of the system. + + + StringvalueStringThe escaped string to be unescaped. + + + Returns an unescaped copy of the input string, which is decoded from either system code page page or UTF-8 depending on the value of System.useCodePage. + Use of System.useCodePage allows legacy content encoded in local code pages to be accessed by the runtime, but only on systems using that legacy code page. + For example, Japanese data encoded as Shift-JIS will only be escaped and unescaped properly on an OS using a Japanese default code page. + + clearInterval + Cancels a specified setInterval() call.iduintThe ID of the setInterval() call, which you set to a variable, + as in the following: + + + Cancels a specified setInterval() call. + + The following example uses the setInterval() method to create a timed + interval, calling the myRepeatingFunction() method after regular intervals of one + second. +

Each call of the myRepeatingFunction method increments the counter + property, and when it equals the stopCount property, the clearInterval() + method is called with the property intervalId which is a reference id to + the interval that was created earlier.

+ +package { + import flash.display.Sprite; + import flash.utils.*; + + public class ClearIntervalExample extends Sprite { + private var intervalDuration:Number = 1000; // duration between intervals, in milliseconds + private var intervalId:uint; + private var counter:uint = 0; + private var stopCount:uint = 3; + + public function ClearIntervalExample() { + intervalId = setInterval(myRepeatingFunction, intervalDuration, "Hello", "World"); + } + + public function myRepeatingFunction():void { + trace(arguments[0] + " " + arguments[1]); + + counter++; + if(counter == stopCount) { + trace("Clearing Interval"); + clearInterval(intervalId); + } + } + } +} +
setInterval()
clearTimeout + Cancels a specified setTimeout() call.iduintThe ID of the setTimeout() call, which you set to a variable, + as in the following: + + + Cancels a specified setTimeout() call. + + The following example uses the setTimeout() method to call another + method following a specified delay period. +

A loop is created to count to one million. If the system can process this request faster + than a second can expire, clearTimeout() will remove the setTimeout() + request, and myDelayedFunction() will not be called.

+ +package { + import flash.display.Sprite; + import flash.utils.*; + + public class ClearTimeoutExample extends Sprite { + private var delay:Number = 1000; // delay before calling myDelayedFunction + private var intervalId:uint; + private var count:uint = 1000000; + + public function ClearTimeoutExample() { + intervalId = setTimeout(myDelayedFunction, delay); + startCounting(); + } + + public function startCounting():void { + var i:uint = 0; + do { + if(i == count-1) { + clearTimeout(intervalId); + trace("Your computer can count to " + count + " in less than " + delay/1000 + " seconds."); + } + i++; + } while(i < count) + } + + public function myDelayedFunction():void { + trace("Time expired."); + } + } +} +
setTimeout()
setInterval + Runs a function at a specified interval (in milliseconds).Unique numeric identifier for the timed process. Use this identifier to cancel + the process, by calling the clearInterval() method. + + uintclosureFunctionThe name of the function to execute. Do not include quotation marks or + parentheses, and do not specify parameters of the function to call. For example, use + functionName, not functionName() or functionName(param). + + delayNumberThe interval, in milliseconds. + + argumentsAn optional list of arguments that are passed to the closure function. + + + Runs a function at a specified interval (in milliseconds). + +

Instead of using the setInterval() method, consider + creating a Timer object, with the specified interval, using 0 as the repeatCount + parameter (which sets the timer to repeat indefinitely).

+ +

If you intend to use the clearInterval() method to cancel the + setInterval() call, be sure to assign the setInterval() call to a + variable (which the clearInterval() function will later reference). + If you do not call the clearInterval() function to cancel the + setInterval() call, the object containing the set timeout closure + function will not be garbage collected.

+ +
The following example uses the setInterval() method to create a timed + interval, calling the myRepeatingFunction() method after regular intervals of one + second. + +package { + import flash.display.Sprite; + import flash.utils.*; + + public class SetIntervalExample extends Sprite { + private var intervalDuration:Number = 1000; // duration between intervals, in milliseconds + + public function SetIntervalExample() { + var intervalId:uint = setInterval(myRepeatingFunction, intervalDuration, "Hello", "World"); + } + + public function myRepeatingFunction():void { + trace(arguments[0] + " " + arguments[1]); + } + } +} +
clearInterval()
setTimeout + Runs a specified function after a specified delay (in milliseconds).Unique numeric identifier for the timed process. Use this identifier to cancel + the process, by calling the clearTimeout() method. + + uintclosureFunctionThe name of the function to execute. Do not include quotation marks or + parentheses, and do not specify parameters of the function to call. For example, use + functionName, not functionName() or functionName(param). + + delayNumberThe delay, in milliseconds, until the function is executed. + + argumentsAn optional list of arguments that are passed to the closure function. + + + Runs a specified function after a specified delay (in milliseconds). + +

Instead of using this method, consider + creating a Timer object, with the specified interval, using 1 as the repeatCount + parameter (which sets the timer to run only once).

+ +

If you intend to use the clearTimeout() method to cancel the + setTimeout() call, be sure to assign the setTimeout() call to a + variable (which the clearTimeout() function will later reference). + If you do not call the clearTimeout() function to cancel the + setTimeout() call, the object containing the set timeout closure + function will not be garbage collected.

+ +
The following example uses the setTimeout() method to call another + method following a specified delay period. + +package { + import flash.display.Sprite; + import flash.utils.*; + + public class SetTimeoutExample extends Sprite { + private var delay:Number = 1000; // delay before calling myDelayedFunction + + public function SetTimeoutExample() { + var intervalId:uint = setTimeout(myDelayedFunction, delay, "Hello", "World"); + } + + public function myDelayedFunction():void { + trace(arguments[0] + " " + arguments[1]); + } + } +} +
clearTimeout()
Timer + The Timer class is the interface to timers, which let you + run code on a specified time sequence.flash.events:EventDispatcher + The Timer class is the interface to timers, which let you + run code on a specified time sequence. Use the start() method to start a timer. + Add an event listener for the timer event to set up code to be run on the timer interval. + +

You can create Timer objects to run once or repeat at specified intervals to execute code on a schedule. + + Depending on the SWF file's framerate or the runtime environment (available + memory and other factors), the runtime may dispatch events at slightly + offset intervals. For example, if a SWF file is set to play at 10 frames per second (fps), which is 100 millisecond + intervals, but your timer is set to fire an event at 80 milliseconds, the event will be dispatched close to the + 100 millisecond interval. + + Memory-intensive scripts may also offset the events.

+ +
The following example uses the class TimerExample to show how a + listener method timerHandler() can be set to listen for a new TimerEvent + to be dispatched. The timer is started when start() is called, and after that point, + the timer events are dispatched. + +package { + import flash.utils.Timer; + import flash.events.TimerEvent; + import flash.display.Sprite; + + public class TimerExample extends Sprite { + + public function TimerExample() { + var myTimer:Timer = new Timer(1000, 2); + myTimer.addEventListener("timer", timerHandler); + myTimer.start(); + } + + public function timerHandler(event:TimerEvent):void { + trace("timerHandler: " + event); + } + } +} +
timerComplete + Dispatched whenever it has completed the number of requests set by Timer.repeatCount.flash.events.TimerEvent.TIMER_COMPLETEflash.events.TimerEvent + Dispatched whenever it has completed the number of requests set by Timer.repeatCount. + timer + Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property.flash.events.TimerEvent.TIMERflash.events.TimerEvent + Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property. + Timer + Constructs a new Timer object with the specified delay + and repeatCount states.if the delay specified is negative or not a finite number + + ErrorErrordelayNumberThe delay between timer events, in milliseconds. A delay lower than 20 milliseconds is not recommended. Timer frequency + is limited to 60 frames per second, meaning a delay lower than 16.6 milliseconds causes runtime problems. + + repeatCountint0Specifies the number of repetitions. + If zero, the timer repeats infinitely. + If nonzero, the timer runs the specified number of times and then stops. + + + Constructs a new Timer object with the specified delay + and repeatCount states. + +

The timer does not start automatically; you must call the start() method + to start it.

+ +
In the following example, the user is given 90 seconds to enter + a response in an input text field. Also, every 30 seconds, a status + message lets the user know how many seconds are left. + +

A Timer object is created that starts in 30 seconds (delay is set to 30000 + milliseconds) and repeats three times, for a total of 90 seconds. (The timer + stops after the third time.)

+ +

Two event listeners are added for the myTimer timer. The first is + triggered by the TimerEvent.TIMER event, which occurs every time + the timer is started. The timerHandler() method changes + the text for the statusTextField text field to reflect the seconds + remaining.

+

Note: The Timer class keeps track of the number of times it has to start + (repeats) by increasing the number in the currentCount property.)

+ +

After the timer is called for the last time, the TimerEvent.TIMER_COMPLETE + event is dispatched and the completeHandler() method is called. + The completeHandler() method changes the type of the inputTextField text field + from INPUT to DYNAMIC, which means the user can no + longer enter or change text.

+ + +package { + import flash.display.Sprite; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFieldAutoSize; + import flash.utils.Timer; + import flash.events.TimerEvent; + import flash.events.Event; + + public class Timer_constructorExample extends Sprite { + private var statusTextField:TextField = new TextField(); + private var inputTextField:TextField = new TextField(); + private var delay:uint = 30000; + private var repeat:uint = 3; + private var myTimer:Timer = new Timer(delay, repeat); + + public function Timer_constructorExample() { + inputTextField.x = 10; + inputTextField.y = 10; + inputTextField.border = true; + inputTextField.background = true; + inputTextField.height = 200; + inputTextField.width = 200; + inputTextField.multiline = true; + inputTextField.wordWrap = true; + inputTextField.type = TextFieldType.INPUT; + + statusTextField.x = 10; + statusTextField.y = 220; + statusTextField.background = true; + statusTextField.autoSize = TextFieldAutoSize.LEFT; + + myTimer.start(); + statusTextField.text = "You have " + ((delay * repeat) / 1000) + + " seconds to enter your response."; + + myTimer.addEventListener(TimerEvent.TIMER, timerHandler); + myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler); + + addChild(inputTextField); + addChild(statusTextField); + } + + private function timerHandler(e:TimerEvent):void{ + repeat--; + statusTextField.text = ((delay * repeat) / 1000) + " seconds left."; + } + + private function completeHandler(e:TimerEvent):void { + statusTextField.text = "Times Up."; + inputTextField.type = TextFieldType.DYNAMIC; + } + } +} +
reset + Stops the timer, if it is running, and sets the currentCount property back to 0, + like the reset button of a stopwatch. + Stops the timer, if it is running, and sets the currentCount property back to 0, + like the reset button of a stopwatch. Then, when start() is called, + the timer instance runs for the specified number of repetitions, + as set by the repeatCount value. + + Timer.stop()start + Starts the timer, if it is not already running. + Starts the timer, if it is not already running. + + stop + Stops the timer. + Stops the timer. When start() is called after stop(), the timer + instance runs for the remaining number of repetitions, as set by the repeatCount property. + + Timer.reset()currentCount + The total number of times the timer has fired since it started + at zero.int + The total number of times the timer has fired since it started + at zero. If the timer has been reset, only the fires since + the reset are counted. + + delay + The delay, in milliseconds, between timer + events.NumberThrows an exception if the delay specified is negative or not a finite number. + + ErrorError + The delay, in milliseconds, between timer + events. If you set the delay interval while + the timer is running, the timer will restart + at the same repeatCount iteration. +

Note: A delay lower than 20 milliseconds is not recommended. Timer frequency + is limited to 60 frames per second, meaning a delay lower than 16.6 milliseconds causes runtime problems.

+
repeatCount + The total number of times the timer is set to run.int + The total number of times the timer is set to run. + If the repeat count is set to 0, the timer continues forever + or until the stop() method is invoked or the program stops. + If the repeat count is nonzero, the timer runs the specified number of times. + If repeatCount is set to a total that is the same or less then currentCount + the timer stops and will not fire again. + + running + The timer's current state; true if the timer is running, otherwise false.Boolean + The timer's current state; true if the timer is running, otherwise false. + +
CompressionAlgorithm + The CompressionAlgorithm class defines string constants for the names of compress and uncompress options.Object + The CompressionAlgorithm class defines string constants for the names of compress and uncompress options. These constants + are used as values of the algorithm parameter of the ByteArray.compress() + and ByteArray.uncompress() methods. + + flash.utils.ByteArray.compress()flash.utils.ByteArray.uncompress()DEFLATE + Defines the string to use for the deflate compression algorithm.deflateString + Defines the string to use for the deflate compression algorithm. + + ZLIB + Defines the string to use for the zlib compression algorithm.zlibString + Defines the string to use for the zlib compression algorithm. + + IDataInput +The IDataInput interface provides a set of methods for reading binary data. +The IDataInput interface provides a set of methods for reading binary data. +This interface is the I/O counterpart to the IDataOutput interface, which +writes binary data. +

All IDataInput and IDataOutput operations are "bigEndian" by default (the most significant +byte in the sequence is stored at the lowest or first storage address), +and are nonblocking. +If insufficient data is available, an EOFError exception +is thrown. Use the IDataInput.bytesAvailable property to determine +how much data is available to read.

+ +

Sign extension matters only when you read data, not when you write it. Therefore you do not need separate +write methods to work with IDataInput.readUnsignedByte() and +IDataInput.readUnsignedShort(). In other words:

+
  • Use IDataOutput.writeByte() with IDataInput.readUnsignedByte() and +IDataInput.readByte().
  • Use IDataOutput.writeShort() with IDataInput.readUnsignedShort() and +IDataInput.readShort().
+ + + +
The following example uses the class DataInputExample to write a boolean + and the double-precision floating-point representation of pi to a byte array. This is accomplished + using the following steps: +
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and the double-precision + floating-point equivalent of the mathematical value of pi.
  3. Read back the boolean and double-precision floating-point number.
+ +

Notice how a code segment is added at the end to check for end of file errors to ensure that + the byte stream is not read past its end.

+ +package { + import flash.display.Sprite; + import flash.utils.ByteArray; + import flash.errors.EOFError; + + public class DataInputExample extends Sprite { + public function DataInputExample() { + var byteArr:ByteArray = new ByteArray(); + + byteArr.writeBoolean(false); + byteArr.writeDouble(Math.PI); + + byteArr.position = 0; + + try { + trace(byteArr.readBoolean()); // false + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); // 3.141592653589793 + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + + try { + trace(byteArr.readDouble()); + } + catch(e:EOFError) { + trace(e); // EOFError: Error #2030: End of file was encountered. + } + } + } +} +
IDataOutput interfaceendianFileStream classSocket classURLStream classByteArray classEOFError classreadBoolean + Reads a Boolean value from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA Boolean value, true if the byte is nonzero, + false otherwise. + Boolean + Reads a Boolean value from the file stream, byte stream, or byte array. A single byte is read + and true is returned if the byte is nonzero, + false otherwise. + readByte + Reads a signed byte from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range -128 to 127. + int + Reads a signed byte from the file stream, byte stream, or byte array. + readBytes + Reads the number of data bytes, specified by the length parameter, + from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorbytesflash.utils:ByteArrayThe ByteArray object to read + data into. + offsetuint0The offset into the bytes parameter at which data + read should begin. + lengthuint0The number of bytes to read. The default value + of 0 causes all available data to be read. + + Reads the number of data bytes, specified by the length parameter, + from the file stream, byte stream, or byte array. The bytes are read into the + ByteArray objected specified by the bytes parameter, starting at + the position specified by offset. + readDouble + Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorAn IEEE 754 double-precision floating point number. + Number + Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array. + readFloat + Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorAn IEEE 754 single-precision floating point number. + Number + Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array. + readInt + Reads a signed 32-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range -2147483648 to 2147483647. + int + Reads a signed 32-bit integer from the file stream, byte stream, or byte array. + readMultiByte + Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the + specified character set.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorUTF-8 encoded string. + StringlengthuintThe number of bytes from the byte stream to read. + charSetStringThe string denoting the character set to use to interpret the bytes. + Possible character set strings include "shift-jis", "cn-gb", + "iso-8859-1", and others. + For a complete list, see Supported Character Sets. + +

Note: If the value for the charSet parameter is not recognized by the current + system, then Adobe® Flash® Player or + Adobe® AIR® uses the system's default + code page as the character set. For example, a value for the charSet parameter, as in + myTest.readMultiByte(22, "iso-8859-01"), that uses 01 instead of + 1 might work on your development system, but not on another system. On the other + system, Flash Player or the AIR runtime will use the system's + default code page.

+ +
+ Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the + specified character set. + + +
readObject + Reads an object from the file stream, byte stream, or byte array, encoded in AMF + serialized format.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe deserialized object + + + Reads an object from the file stream, byte stream, or byte array, encoded in AMF + serialized format. + objectEncodingflash.net.registerClassAlias()readShort + Reads a signed 16-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range -32768 to 32767. + int + Reads a signed 16-bit integer from the file stream, byte stream, or byte array. + readUTFBytes + Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters of the specified length. + StringlengthuintThe number of bytes to read. + + Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string. + readUTF + Reads a UTF-8 string from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters. + + String + Reads a UTF-8 string from the file stream, byte stream, or byte array. The string + is assumed to be prefixed with an unsigned short indicating + the length in bytes. + +

This method is similar to the readUTF() + method in the Java® IDataInput interface.

+
readUnsignedByte + Reads an unsigned byte from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 255. + uint + Reads an unsigned byte from the file stream, byte stream, or byte array. + readUnsignedInt + Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 4294967295. + uint + Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array. + readUnsignedShort + Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available + to read. + EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 65535. + uint + Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array. + bytesAvailable + Returns the number of bytes of data available for reading + in the input buffer.uint + Returns the number of bytes of data available for reading + in the input buffer. + User code must call bytesAvailable to ensure + that sufficient data is available before trying to read + it with one of the read methods. + endian + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant + from the Endian class.String + The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant + from the Endian class. + + Endian classobjectEncoding + Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the + readObject() method.uint + Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the + readObject() method. The value is a constant from the ObjectEncoding class. + + readObject()IDataOutput.writeObject()ObjectEncoding class
Dictionary + The Dictionary class lets you create a dynamic collection of properties, which uses strict equality + (===) for key comparison.Object + The Dictionary class lets you create a dynamic collection of properties, which uses strict equality + (===) for key comparison. When an object is used as a key, the object's + identity is used to look up the object, and not the value returned from calling toString() on it. +

The following statements show the relationship between a Dictionary object and a key object:

+
+ var dict = new Dictionary();
+ var obj = new Object();
+ var key:Object = new Object();
+ key.toString = function() { return "key" }
+ 
+ dict[key] = "Letters";
+ obj["key"] = "Letters";
+ 
+ dict[key] == "Letters"; // true
+ obj["key"] == "Letters"; // true
+ obj[key] == "Letters"; // true because key == "key" is true b/c key.toString == "key"
+ dict["key"] == "Letters"; // false because "key" === key is false
+ delete dict[key]; //removes the key
+ 
+ +
=== (strict equality)Dictionary + Creates a new Dictionary object.weakKeysBooleanfalseInstructs the Dictionary object to use "weak" references on object keys. + If the only reference to an object is in the specified Dictionary object, the key is eligible for + garbage collection and is removed from the table when the object is collected. + + + Creates a new Dictionary object. To remove a key from a Dictionary object, use the delete operator. + +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/flash.xml.xml b/language-server/playerglobal_docs/flash.xml.xml new file mode 100644 index 0000000..40c7cf8 --- /dev/null +++ b/language-server/playerglobal_docs/flash.xml.xml @@ -0,0 +1,854 @@ +flash.xmlXMLNode + + The XMLNode class represents the legacy XML object + that was present in ActionScript 2.0 and that was renamed in ActionScript 3.0.Object + The XMLNode class represents the legacy XML object + that was present in ActionScript 2.0 and that was renamed in ActionScript 3.0. + In ActionScript 3.0, consider using the new top-level XML + class and related classes instead, + which support E4X (ECMAScript for XML). + The XMLNode class is present for backward compatibility. + + The following example uses the XMLDocument and XMLNode classes + to parse and format an XML document. Rather than loading an external + XML file, the example uses the top-level XML class to create an XML document, + then parses it. + +package { + import flash.display.Sprite; + import flash.xml.XMLDocument; + import flash.xml.XMLNode; + import flash.xml.XMLNodeType; + + public class XMLDocumentExample extends Sprite { + public function XMLDocumentExample() { + var result:XMLDocument = new XMLDocument(); + result.ignoreWhite = true; + result.parseXML(getXMLString()); + + var books:Array = parseBooks(result.firstChild); + trace("books: \n" + books); + } + + private function parseBooks(node:XMLNode):Array { + var books:Array = new Array(); + + var kids:Array = node.childNodes; + for each(var item:XMLNode in kids) { + parseBook(item, books); + } + + return books; + } + + private function parseBook(node:XMLNode, books:Array):void { + var item:Book = new Book(); + item.setPublisher(node.attributes.publisher); + item.setName(node.attributes.name); + books.push(item); + } + + private function getXMLString():String { + var list:XML = <books> + <book publisher="Addison-Wesley" name="Design Patterns" /> + <book publisher="Addison-Wesley" name="The Pragmatic Programmer" /> + <book publisher="Addison-Wesley" name="Test Driven Development" /> + <book publisher="Addison-Wesley" name="Refactoring to Patterns" /> + <book publisher="O'Reilly Media" name="The Cathedral & the Bazaar" /> + <book publisher="O'Reilly Media" name="Unit Test Frameworks" /> + </books>; + return list.toXMLString(); + } + } + +} +class Book { + private var publisher:String; + private var name:String; + + public function setPublisher(publisher:String):void { + this.publisher = publisher; + } + + public function setName(name:String):void { + this.name = name; + } + + public function toString():String { + return "[Book name: " + name + " publisher: " + publisher + "]\n"; + } +} +XMLflash.xml.XMLDocumentXMLNode + Creates a new XMLNode object.typeuintThe node type: either 1 for an XML element or 3 for a text node. + valueStringThe XML text parsed to create the new XMLNode object. + + + + + + + Creates a new XMLNode object. You must use the constructor to create an XMLNode object before you + call any of the methods of the XMLNode class. +

Note: Use the createElement() and createTextNode() + methods to add elements and text nodes to an XML document tree.

+ +
XMLDocument.createElement()XMLDocument.createTextNode()
appendChild + + Appends the specified node to the XML object's child list.nodeflash.xml:XMLNodeAn XMLNode that represents the node to be moved from its current location to the child + list of the my_xml object. + + + + + + Appends the specified node to the XML object's child list. This method operates directly on the + node referenced by the childNode parameter; it does not append a copy of the + node. If the node to be appended already exists in another tree structure, appending the node to the + new location will remove it from its current location. If the childNode + parameter refers to a node that already exists in another XML tree structure, the appended child node + is placed in the new tree structure after it is removed from its existing parent node. + + cloneNode + + Constructs and returns a new XML node of the same type, name, value, and attributes as the + specified XML object.An XMLNode Object. + + + + flash.xml:XMLNodedeepBooleanA Boolean value; if set to true, the children of the specified XML object will be recursively cloned. + + + + Constructs and returns a new XML node of the same type, name, value, and attributes as the + specified XML object. If deep is set to true, all child nodes are + recursively cloned, resulting in an exact copy of the original object's document tree. +

The clone of the node that is returned is no longer associated with the tree of the cloned item. + Consequently, nextSibling, parentNode, and previousSibling + all have a value of null. If the deep parameter is set to + false, or the my_xml node has no child nodes, + firstChild and lastChild are also null.

+ +
getNamespaceForPrefix + Returns the namespace URI that is associated with the specified prefix for the node.The namespace that is associated with the specified prefix. + + StringprefixStringThe prefix for which the method returns the associated namespace. + + + Returns the namespace URI that is associated with the specified prefix for the node. To determine + the URI, getPrefixForNamespace() searches up the XML hierarchy from the node, as + necessary, and returns the namespace URI of the first xmlns declaration for the + given prefix. + +

If no namespace is defined for the specified prefix, the method returns null.

+ +

If you specify an empty string ("") as the prefix and there is a + default namespace defined for the node (as in xmlns="http://www.example.com/"), + the method returns that default namespace URI. +

+ +
XMLNode.getPrefixForNamespace()XMLNode.namespaceURI
getPrefixForNamespace + Returns the prefix that is associated with the specified namespace URI for the node.The prefix associated with the specified namespace. + + StringnsStringThe namespace URI for which the method returns the associated prefix. + + + Returns the prefix that is associated with the specified namespace URI for the node. To determine + the prefix, getPrefixForNamespace() searches up the XML hierarchy from the node, as + necessary, and returns the prefix of the first xmlns declaration with a namespace URI + that matches ns. + +

If there is no xmlns + assignment for the given URI, the method returns null. If there is an + xmlns assignment for the given URI but no prefix is associated with the assignment, + the method returns an empty string + (""). +

+ +
XMLNode.getNamespaceForPrefix()XMLNode.namespaceURI
hasChildNodes + Indicates whether the specified XMLNode object has child nodes.Returns true if the + specified XMLNode object has child nodes; otherwise, false. + + Boolean + Indicates whether the specified XMLNode object has child nodes. This property is true if the + specified XMLNode object has child nodes; otherwise, it is false. + + insertBefore + Inserts a new child node into the XML object's child list, before the + beforeNode node.nodeflash.xml:XMLNodeThe XMLNode object to be inserted. + beforeflash.xml:XMLNodeThe XMLNode object before the insertion point for the childNode. + + + Inserts a new child node into the XML object's child list, before the + beforeNode node. If the beforeNode parameter is undefined + or null, the node is added using the appendChild() method. If beforeNode + is not a child of my_xml, the insertion fails. + + XMLNode.cloneNode()removeNode + Removes the specified XML object from its parent. + Removes the specified XML object from its parent. Also deletes all descendants of the node. + + + + toString + Evaluates the specified XMLNode object, constructs a textual representation of the XML structure, + including the node, children, and attributes, and returns the result as a string.The string representing the XMLNode object. + + + String + Evaluates the specified XMLNode object, constructs a textual representation of the XML structure, + including the node, children, and attributes, and returns the result as a string. + +

For top-level XMLDocument objects (those created with the constructor), + the XMLDocument.toString() method outputs the document's XML declaration + (stored in the XMLDocument.xmlDecl property), followed by the document's + DOCTYPE declaration (stored in the XMLDocument.docTypeDecl property), + followed by the text representation of all XML nodes in the object. The XML declaration is not + output if the XMLDocument.xmlDecl property is null. + The DOCTYPE declaration is not output if the + XMLDocument.docTypeDecl property is null.

+ +
XMLDocument.docTypeDeclXMLDocument.xmlDecl
firstChild + Evaluates the specified XMLDocument object and references the first child in the parent node's child list.flash.xml:XMLNode + Evaluates the specified XMLDocument object and references the first child in the parent node's child list. + This property is null if the node does not have children. This property is + undefined if the node is a text node. This is a read-only property and cannot be used + to manipulate child nodes; use the appendChild(), insertBefore(), and + removeNode() methods to manipulate child nodes. + + + XMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()lastChild + An XMLNode value that references the last child in the node's child list.flash.xml:XMLNode + An XMLNode value that references the last child in the node's child list. The + XMLNode.lastChild property is null if the node does not have children. + This property cannot be used to manipulate child nodes; use the appendChild(), + insertBefore(), and removeNode() methods to manipulate child nodes. + + + XMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()nextSibling + An XMLNode value that references the next sibling in the parent node's child list.flash.xml:XMLNode + An XMLNode value that references the next sibling in the parent node's child list. This property is + null if the node does not have a next sibling node. This property cannot be used to + manipulate child nodes; use the appendChild(), insertBefore(), and + removeNode() methods to manipulate child nodes. + + + XMLNode.firstChildXMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()nodeName + A string representing the node name of the XMLNode object.String + A string representing the node name of the XMLNode object. If the XMLNode object is an XML + element (nodeType == 1), nodeName is the name of the tag that + represents the node in the XML file. For example, TITLE is the nodeName + of an HTML TITLE tag. If the XMLNode object is a text node + (nodeType == 3), nodeName is null. + + + XMLNode.nodeTypenodeType + A nodeType constant value, either XMLNodeType.ELEMENT_NODE for an XML element or + XMLNodeType.TEXT_NODE for a text node.uint + A nodeType constant value, either XMLNodeType.ELEMENT_NODE for an XML element or + XMLNodeType.TEXT_NODE for a text node. +

The nodeType is a numeric value from the NodeType enumeration in the W3C DOM + Level 1 recommendation: + http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html. + The following table lists the values:

+

4CDATA_SECTION_NODEInteger valueDefined + constant1ELEMENT_NODE3TEXT_NODE5ENTITY_REFERENCE_NODE7PROCESSING_INSTRUCTION_NODE9DOCUMENT_NODE11DOCUMENT_FRAGMENT_NODE

+

In Flash Player, the built-in XMLNode class only supports XMLNodeType.ELEMENT_NODE and + XMLNodeType.TEXT_NODE.

+ +
XMLNodeType.TEXT_NODEXMLNodeType.ELEMENT_NODE
nodeValue + The node value of the XMLDocument object.String + The node value of the XMLDocument object. If the XMLDocument object is a text node, the nodeType + is 3, and the nodeValue is the text of the node. If the XMLDocument object is an XML element + (nodeType is 1), nodeValue is null and read-only. + + + XMLNode.nodeTypeparentNode + An XMLNode value that references the parent node of the specified XML object, or returns + null if the node has no parent.flash.xml:XMLNode + An XMLNode value that references the parent node of the specified XML object, or returns + null if the node has no parent. This is a read-only property and cannot be used to + manipulate child nodes; use the appendChild(), insertBefore(), and + removeNode() methods to manipulate child nodes. + + XMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()previousSibling + An XMLNode value that references the previous sibling in the parent node's child list.flash.xml:XMLNode + An XMLNode value that references the previous sibling in the parent node's child list. + The property has a value of null if the node does not have a previous sibling node. This property + cannot be used to manipulate child nodes; use the appendChild(), + insertBefore(), and removeNode() methods to manipulate child nodes. + + + XMLNode.lastChildXMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()attributes + An object containing all of the attributes of the specified XMLNode instance.Object + An object containing all of the attributes of the specified XMLNode instance. The + XMLNode.attributes object contains one variable for each attribute of the XMLNode instance. + Because these variables are defined as part of the object, they are generally referred to as + properties of the object. The value of each attribute is stored in the corresponding property as a + string. For example, if you have an attribute named color, you would retrieve + that attribute's value + by specifying color as the property name, as the following code shows: +
+	 var myColor:String = doc.firstChild.attributes.color
+	 
+ + +
childNodes + An array of the specified XMLNode object's children.Array + An array of the specified XMLNode object's children. Each element in the array is a reference + to an XMLNode object that represents a child node. This is a read-only property and cannot be + used to manipulate child nodes. Use the appendChild(), insertBefore(), + and removeNode() methods to manipulate child nodes. + +

This property is undefined for text nodes (nodeType == 3).

+ + +
XMLNode.nodeTypeXMLNode.appendChild()XMLNode.insertBefore()XMLNode.removeNode()
localName + The local name portion of the XML node's name.String + The local name portion of the XML node's name. This is the element name without + the namespace prefix. For example, the node + <contact:mailbox/>bob@example.com</contact:mailbox> + has the local name "mailbox", and the prefix "contact", which comprise the full + element name "contact.mailbox". + +

You can access the namespace prefix through the prefix property of + the XML node object. The nodeName property returns the full name + (including the prefix and the local name).

+ +
namespaceURI + If the XML node has a prefix, namespaceURI is the value of the xmlns + declaration for that prefix (the URI), which is typically called the namespace URI.StringThe URI of the namespace to which the XML node's prefix resolves. + + + If the XML node has a prefix, namespaceURI is the value of the xmlns + declaration for that prefix (the URI), which is typically called the namespace URI. + The xmlns declaration is in the current node or in a node higher in the XML + hierarchy. + +

If the XML node does not have a prefix, the value of the namespaceURI property + depends on whether there is a default namespace defined (as in + xmlns="http://www.example.com/"). If there is a default namespace, the value of + the namespaceURI property is the value of the default namespace. + If there is no default namespace, the namespaceURI property for + that node is an empty string ("").

+ +

You can use the getNamespaceForPrefix() method to identify the namespace associated with a + specific prefix. The namespaceURI property returns the prefix associated with the node name.

+ +
getNamespaceForPrefix()getPrefixForNamespace()
prefix + The prefix portion of the XML node name.String + The prefix portion of the XML node name. For example, the node + <contact:mailbox/>bob@example.com</contact:mailbox> prefix + "contact" and the local name "mailbox", which comprise the full element name "contact.mailbox". + +

The nodeName property of an XML node object returns the full name + (including the prefix and the local name). You can access the local name portion of the + element's name via the localName property.

+ + +
XMLNodeType + The XMLNodeType class contains constants used with + XMLNode.nodeType.Object + The XMLNodeType class contains constants used with + XMLNode.nodeType. The values are defined + by the NodeType enumeration in the + W3C DOM Level 1 recommendation: + http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html + + XMLNode.nodeTypeELEMENT_NODE + Specifies that the node is an element.1uint + Specifies that the node is an element. + This constant is used with XMLNode.nodeType. + The value is defined by the NodeType enumeration in the + W3C DOM Level 1 recommendation: + http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html + + XMLNode.nodeTypeTEXT_NODE + Specifies that the node is a text node.3uint + Specifies that the node is a text node. + This constant is used with XMLNode.nodeType. + The value is defined by the NodeType enumeration in the + W3C DOM Level 1 recommendation: + http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html + + XMLNode.nodeTypeXMLDocument + The XMLDocument class represents the legacy XML object + that was present in ActionScript 2.0.flash.xml:XMLNode + The XMLDocument class represents the legacy XML object + that was present in ActionScript 2.0. It was renamed in ActionScript 3.0 + to XMLDocument to avoid name conflicts with the new + XML class in ActionScript 3.0. In ActionScript 3.0, + it is recommended that you use the new + XML class and related classes, + which support E4X (ECMAScript for XML). + +

The XMLDocument class, as well as XMLNode and XMLNodeType, are present for backward + compatibility. The functionality for loading XML documents can now be found in the + URLLoader class.

+ +
The following example uses the XMLDocument and XMLNode classes + to parse and format an XML document. Rather than loading an external + XML file, the example uses the top-level XML class to create an XML document, + then parses it. + +package { + import flash.display.Sprite; + import flash.xml.XMLDocument; + import flash.xml.XMLNode; + import flash.xml.XMLNodeType; + + public class XMLDocumentExample extends Sprite { + public function XMLDocumentExample() { + var result:XMLDocument = new XMLDocument(); + result.ignoreWhite = true; + result.parseXML(getXMLString()); + + var books:Array = parseBooks(result.firstChild); + trace("books: \n" + books); + } + + private function parseBooks(node:XMLNode):Array { + var books:Array = new Array(); + + var kids:Array = node.childNodes; + for each(var item:XMLNode in kids) { + parseBook(item, books); + } + + return books; + } + + private function parseBook(node:XMLNode, books:Array):void { + var item:Book = new Book(); + item.setPublisher(node.attributes.publisher); + item.setName(node.attributes.name); + books.push(item); + } + + private function getXMLString():String { + var list:XML = <books> + <book publisher="Addison-Wesley" name="Design Patterns" /> + <book publisher="Addison-Wesley" name="The Pragmatic Programmer" /> + <book publisher="Addison-Wesley" name="Test Driven Development" /> + <book publisher="Addison-Wesley" name="Refactoring to Patterns" /> + <book publisher="O'Reilly Media" name="The Cathedral & the Bazaar" /> + <book publisher="O'Reilly Media" name="Unit Test Frameworks" /> + </books>; + return list.toXMLString(); + } + } + +} +class Book { + private var publisher:String; + private var name:String; + + public function setPublisher(publisher:String):void { + this.publisher = publisher; + } + + public function setName(name:String):void { + this.name = name; + } + + public function toString():String { + return "[Book name: " + name + " publisher: " + publisher + "]\n"; + } +} +
flash.net.URLLoaderXML classXMLDocument + Creates a new XMLDocument object.sourceStringnullThe XML text parsed to create the new XMLDocument object. + + + Creates a new XMLDocument object. You must use the constructor to create an XMLDocument object before you call any of the methods of the XMLDocument class. +

Note: Use the createElement() and createTextNode() methods to add elements and text nodes to an XML document tree.

+ +
XMLDocument.createElement()XMLDocument.createTextNode()
createElement + Creates a new XMLNode object with the name specified in the parameter.An XMLNode object. + + flash.xml:XMLNodenameStringThe tag name of the XMLDocument element being created. + + + Creates a new XMLNode object with the name specified in the parameter. + The new node initially has no parent, no children, and no siblings. + The method returns a reference to the newly created XMLNode object + that represents the element. This method and the XMLDocument.createTextNode() + method are the constructor methods for creating nodes for an XMLDocument object. + + XMLDocument.createTextNode()createTextNode + Creates a new XML text node with the specified text.An XMLNode object. + + flash.xml:XMLNodetextStringThe text used to create the new text node. + + + Creates a new XML text node with the specified text. The new node initially has no parent, and text nodes cannot have children or siblings. This method returns a reference to the XMLDocument object that represents the new text node. This method and the XMLDocument.createElement() method are the constructor methods for creating nodes for an XMLDocument object. + + + XMLDocument.createElement()parseXML + Parses the XML text specified in the value parameter + and populates the specified XMLDocument object with the resulting XML tree.sourceStringThe XML text to be parsed and passed to the specified XMLDocument object. + + + Parses the XML text specified in the value parameter + and populates the specified XMLDocument object with the resulting XML tree. Any existing trees in the XMLDocument object are discarded. + + toString + Returns a string representation of the XML object.A string representation of the XML object. + + String + Returns a string representation of the XML object. + + docTypeDecl + Specifies information about the XML document's DOCTYPE declaration.nullObject + Specifies information about the XML document's DOCTYPE declaration. + After the XML text has been parsed into an XMLDocument object, the + XMLDocument.docTypeDecl property of the XMLDocument object is set to the + text of the XML document's DOCTYPE declaration + (for example, <!DOCTYPE greeting SYSTEM "hello.dtd">). + This property is set using a string representation of the DOCTYPE declaration, + not an XMLNode object. +

The legacy ActionScript XML parser is not a validating parser. The DOCTYPE + declaration is read by the parser and stored in the XMLDocument.docTypeDecl property, + but no DTD validation is performed.

+

If no DOCTYPE declaration was encountered during a parse operation, + the XMLDocument.docTypeDecl property is set to null. + The XML.toString() method outputs the contents of XML.docTypeDecl + immediately after the XML declaration stored in XML.xmlDecl, and before any other + text in the XML object. If XMLDocument.docTypeDecl is null, no + DOCTYPE declaration is output.

+
idMap + An Object containing the nodes of the XML that have an id attribute assigned.unknownObject + An Object containing the nodes of the XML that have an id attribute assigned. + The names of the properties of the object (each containing a node) match the values of the + id attributes. + +

Consider the following XMLDocument object:

+ + + <employee id='41'> + <name> + John Doe + </name> + <address> + 601 Townsend St. + </address> + </employee> + + <employee id='42'> + <name> + Jane Q. Public + </name> + </employee> + <department id="IT"> + Information Technology + </department> + + +

In this example, the idMap property for this XMLDocument object is an Object with + three properties: 41, 42, and IT. Each of these + properties is an XMLNode that has the matching id value. For example, + the IT property of the idMap object is this node:

+ + + <department id="IT"> + Information Technology + </department> + + +

You must use the parseXML() method on the XMLDocument object for the + idMap property to be instantiated.

+ +

If there is more than one XMLNode with the same id value, the matching property + of the idNode object is that of the last node parsed. For example:

+ + + var x1:XML = new XMLDocument("<a id='1'><b id='2' /><c id='1' /></a>"); + x2 = new XMLDocument(); + x2.parseXML(x1); + trace(x2.idMap['1']); + + + This will output the <c> node: + + + <c id='1' /> + + +
ignoreWhite + When set to true, text nodes that contain only white space are discarded during the parsing process.falseBoolean + When set to true, text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white space are unaffected. The default setting is false. +

You can set the ignoreWhite property for individual XMLDocument objects, as the following code shows:

+ + my_xml.ignoreWhite = true; + + +
xmlDecl + A string that specifies information about a document's XML declaration.nullObject + A string that specifies information about a document's XML declaration. + After the XML document is parsed into an XMLDocument object, this property is set + to the text of the document's XML declaration. This property is set using a string + representation of the XML declaration, not an XMLNode object. If no XML declaration + is encountered during a parse operation, the property is set to null. + The XMLDocument.toString() method outputs the contents of the + XML.xmlDecl property before any other text in the XML object. + If the XML.xmlDecl property contains null, + no XML declaration is output. +
\ No newline at end of file diff --git a/language-server/playerglobal_docs/packages.dita b/language-server/playerglobal_docs/packages.dita new file mode 100644 index 0000000..5fe2d90 --- /dev/null +++ b/language-server/playerglobal_docs/packages.dita @@ -0,0 +1,16 @@ + diff --git a/language-server/playerglobal_docs/packages.dita.xml b/language-server/playerglobal_docs/packages.dita.xml new file mode 100644 index 0000000..8e38282 --- /dev/null +++ b/language-server/playerglobal_docs/packages.dita.xml @@ -0,0 +1,22 @@ + + + + \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..5fa2b00 --- /dev/null +++ b/plugin.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/as3mxml/eclipse/AS3MXMLConnectionProvider.java b/src/com/as3mxml/eclipse/AS3MXMLConnectionProvider.java new file mode 100644 index 0000000..879790c --- /dev/null +++ b/src/com/as3mxml/eclipse/AS3MXMLConnectionProvider.java @@ -0,0 +1,41 @@ +package com.as3mxml.eclipse; + +import java.io.File; +import java.io.IOException; + +import org.eclipse.core.runtime.Path; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.Platform; +import org.eclipse.lsp4e.server.ProcessStreamConnectionProvider; +import org.osgi.framework.Bundle; + +public class AS3MXMLConnectionProvider extends ProcessStreamConnectionProvider { + public AS3MXMLConnectionProvider() { + Bundle bundle = Activator.getDefault().getBundle(); + Path bundleDir = Path.EMPTY; + try { + bundleDir = new Path(FileLocator.toFileURL(FileLocator.find(bundle, new Path("language-server"), null)).getPath()); + } + catch(IOException e) {} + + String frameworkSDKHome = Activator.getDefault().getPreferenceStore().getString(AS3MXMLPreferenceInitializer.explicitSdkFrameworkPreference); + + List commands = new ArrayList<>(); + commands.add("java"); + commands.add("-Dfile.encoding=UTF8"); + commands.add("-Droyalelib=" + frameworkSDKHome + "/frameworks"); + commands.add("-cp"); + commands.add(bundleDir.toOSString() + "/bundled-compiler/*" + File.pathSeparator + bundleDir.toOSString() + "/bin/*"); + commands.add("com.as3mxml.vscode.Main"); + setCommands(commands); + setWorkingDirectory(Platform.getLocation().toOSString()); + } + + @Override + public String toString() { + return "ActionScript & MXML Connection Provider: " + super.toString(); + } +} diff --git a/src/com/as3mxml/eclipse/AS3MXMLPreferenceInitializer.java b/src/com/as3mxml/eclipse/AS3MXMLPreferenceInitializer.java new file mode 100644 index 0000000..699ee1d --- /dev/null +++ b/src/com/as3mxml/eclipse/AS3MXMLPreferenceInitializer.java @@ -0,0 +1,16 @@ +package com.as3mxml.eclipse; + +import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; +import org.eclipse.jface.preference.IPreferenceStore; + +public class AS3MXMLPreferenceInitializer extends AbstractPreferenceInitializer { + + public static String explicitSdkFrameworkPreference = "as3mxml.sdk.framework"; //$NON-NLS-1$ + + @Override + public void initializeDefaultPreferences() { + IPreferenceStore store = Activator.getDefault().getPreferenceStore(); + + store.setDefault(explicitSdkFrameworkPreference, "c:/Users/josht/Development/flash/sdks/Flex4.16.1_AIR32"); + } +} diff --git a/src/com/as3mxml/eclipse/Activator.java b/src/com/as3mxml/eclipse/Activator.java new file mode 100644 index 0000000..5c7afd4 --- /dev/null +++ b/src/com/as3mxml/eclipse/Activator.java @@ -0,0 +1,44 @@ +package com.as3mxml.eclipse; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "com.as3mxml.eclipse"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + @Override + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/syntaxes/AS3.tmLanguage b/syntaxes/AS3.tmLanguage new file mode 100644 index 0000000..8b030f2 --- /dev/null +++ b/syntaxes/AS3.tmLanguage @@ -0,0 +1,1427 @@ + + + + + fileTypes + + as + + name + Actionscript 3 + patterns + + + include + #comments + + + include + #package + + + include + #class + + + include + #interface + + + include + #namespace_declaration + + + include + #import + + + include + #mxml + + + include + #strings + + + include + #regexp + + + include + #variable_declaration + + + include + #numbers + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #primitive_functions + + + include + #language_constants + + + include + #language_variables + + + include + #guess_type + + + include + #guess_constant + + + include + #other_operators + + + include + #arithmetic_operators + + + include + #logical_operators + + + include + #array_access_operators + + + include + #vector_creation_operators + + + include + #control_keywords + + + include + #other_keywords + + + include + #use_namespace + + + include + #functions + + + repository + + arithmetic_operators + + match + (\+|\-|/|%|(?<!:)\*) + name + keyword.operator.actionscript.3 + + array_access_operators + + match + (\[|\]) + name + keyword.operator.actionscript.3 + + class + + begin + (?x) (^|\s+|;) (\b(dynamic|final|abstract)\b\s+)? (\b(internal|public)\b\s+)? (\b(dynamic|final|abstract)\b\s+)? (?=\bclass\b) + beginCaptures + + 3 + + name + storage.modifier.actionscript.3 + + 5 + + name + storage.modifier.actionscript.3 + + 7 + + name + storage.modifier.actionscript.3 + + + end + \} + name + meta.class.actionscript.3 + patterns + + + include + #class_declaration + + + include + #metadata + + + include + #method + + + include + #comments + + + include + #strings + + + include + #regexp + + + include + #numbers + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #primitive_functions + + + include + #language_constants + + + include + #language_variables + + + include + #other_operators + + + include + #other_keywords + + + include + #use_namespace + + + include + #guess_type + + + include + #guess_constant + + + include + #arithmetic_operators + + + include + #array_access_operators + + + include + #vector_creation_operators + + + include + #variable_declaration + + + include + #object_literal + + + + namespace_declaration + + captures + + 2 + + name + storage.modifier.actionscript.3 + + 3 + + name + storage.modifier.actionscript.3 + + + match + (?x) ((\w+)\s+)? (namespace) \s+ (?:[A-Za-z0-9_\$]+) + name + meta.namespace_declaration.actionscript.3 + + class_declaration + + begin + + (?x) \b(class)\b \s+ ([\.\w]+|\*) + beginCaptures + + 1 + + name + storage.type.class.actionscript.3 + + 2 + + name + entity.name.class.actionscript.3 + + + end + \{ + name + meta.class_declaration.actionscript.3 + patterns + + + include + #extends + + + include + #implements + + + include + #comments + + + + code_block + + begin + \{ + end + \} + name + meta.code_block.actionscript.3 + patterns + + + include + #code_block + + + include + #comments + + + include + #strings + + + include + #regexp + + + include + #variable_declaration + + + include + #numbers + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #primitive_functions + + + include + #language_constants + + + include + #language_variables + + + include + #guess_type + + + include + #guess_constant + + + include + #other_operators + + + include + #arithmetic_operators + + + include + #logical_operators + + + include + #array_access_operators + + + include + #vector_creation_operators + + + include + #control_keywords + + + include + #other_keywords + + + include + #use_namespace + + + include + #functions + + + include + #import + + + + comments + + patterns + + + begin + /\*\*(?!/) + end + \*/ + name + comment.block.documentation.actionscript.3 + patterns + + + match + @(copy|default|eventType|example|exampleText|includeExample|inheritDoc|internal|param|private|return|see|since|throws)\b + name + keyword.other.documentation.actionscript.3.asdoc + + + + + begin + /\* + end + \*/ + name + comment.block.actionscript.3 + + + match + //.* + name + comment.line.actionscript.3 + + + + control_keywords + + match + \b(if|else|do|while|for|each|continue|return|switch|case|default|break|try|catch|finally|throw)\b + name + keyword.control.actionscript.3 + + dynamic_type + + captures + + 1 + + name + support.type.actionscript.3 + + + match + (?<=:)\s*(\*) + + escapes + + match + \\(x\h{2}|[0-2][0-7]{,2}|3[0-6][0-7]|37[0-7]?|[4-7][0-7]?|.) + name + constant.character.escape.actionscript.3 + + extends + + captures + + 1 + + name + keyword.other.actionscript.3 + + 2 + + name + entity.other.inherited-class.actionscript.3 + + 3 + + name + entity.other.inherited-class.actionscript.3 + + + match + (?x) \b(extends)\b \s+ ([\.\w]+) \s* (?:, \s* ([\.\w]+))* \s* + name + meta.extends.actionscript.3 + + function_arguments + + begin + \( + end + \) + name + meta.function_arguments.actionscript.3 + patterns + + + include + #parameters + + + include + #comments + + + + parameters + + begin + (\.\.\.)?\s*([A-Za-z\_\$][A-Za-z0-9_\$]*)(?:\s*(\:)\s*(?:(?:([A-Za-z\$][A-Za-z0-9_\$]+(?:\.[A-Za-z\$][A-Za-z0-9_\$]+)*)(?:\.<([A-Za-z\$][A-Za-z0-9_\$]+(?:\.[A-Za-z\$][A-Za-z0-9_\$]+)*)>)?)|(\*)))?(?:\s*(=))? + end + ,|(?=\)) + beginCaptures + + 1 + + name + keyword.operator.actionscript.3 + + 2 + + name + variable.parameter.actionscript.3 + + 3 + + name + keyword.operator.actionscript.3 + + 4 + + name + support.type.actionscript.3 + + 5 + + name + support.type.actionscript.3 + + 6 + + name + support.type.actionscript.3 + + 7 + + name + keyword.operator.actionscript.3 + + + patterns + + + include + #strings + + + include + #numbers + + + include + #language_constants + + + include + #comments + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #guess_type + + + include + #guess_constant + + + + functions + + begin + (?x) \b(function)\b (?:\s+\b(get|set)\b\s+)? \s* ([a-zA-Z0-9_\$]+\b)? + beginCaptures + + 1 + + name + storage.type.function.actionscript.3 + + 2 + + name + storage.modifier.actionscript.3 + + 3 + + name + entity.name.function.actionscript.3 + + + end + ($|;|(?=\{)) + name + meta.function.actionscript.3 + patterns + + + include + #function_arguments + + + include + #return_type + + + include + #comments + + + + guess_constant + + captures + + 1 + + name + constant.other.actionscript.3 + + + comment + Following convention, let's guess that anything in all caps/digits (possible underscores) is a constant. + match + \b([A-Z\$][A-Z0-9_]+)\b + + guess_type + + captures + + 1 + + name + support.type.actionscript.3 + + + comment + Following convention, let's guess that any word starting with one or more capital letters (that contains at least some lower-case letters so that constants aren't detected) refers to a class/type. May be fully-qualified. + match + \b((?:[A-Za-z0-9_\$]+\.)*[A-Z][A-Z0-9]*[a-z]+[A-Za-z0-9_\$]*)\b + + implements + + captures + + 1 + + name + keyword.other.actionscript.3 + + 2 + + name + entity.other.inherited-class.actionscript.3 + + 3 + + name + entity.other.inherited-class.actionscript.3 + + + match + (?x) \b(implements)\b \s+ ([\.\w]+) \s* (?:, \s* ([\.\w]+))* \s* + name + meta.implements.actionscript.3 + + import + + captures + + 2 + + name + keyword.control.import.actionscript.3 + + 3 + + name + support.type.actionscript.3 + + + match + + (?x) (^|\s+|;) \b(import)\b \s+ ([A-Za-z0-9\$_\.]+(?:\.\*)?) \s* (?=;|$) + name + meta.import.actionscript.3 + + interface + + begin + (?x) (^|\s+|;) (\b(internal|public)\b\s+)? (?=\binterface\b) + beginCaptures + + 3 + + name + storage.modifier.actionscript.3 + + + end + \} + name + meta.interface.actionscript.3 + patterns + + + include + #interface_declaration + + + include + #metadata + + + include + #functions + + + include + #comments + + + + interface_declaration + + begin + + (?x) \b(interface)\b \s+ ([\.\w]+) + beginCaptures + + 1 + + name + storage.type.interface.actionscript.3 + + 2 + + name + entity.name.class.actionscript.3 + + + end + \{ + name + meta.class_declaration.actionscript.3 + patterns + + + include + #extends + + + include + #comments + + + + language_constants + + match + \b(true|false|null|Infinity|-Infinity|NaN|undefined)\b + name + constant.language.actionscript.3 + + language_variables + + match + \b(super|this|arguments)\b + name + variable.language.actionscript.3 + + logical_operators + + match + (&|<|~|\||>|\^|!|\?) + name + keyword.operator.actionscript.3 + + metadata_info + + begin + \( + end + \) + patterns + + + include + #strings + + + captures + + 1 + + name + variable.parameter.actionscript.3 + + 2 + + name + keyword.operator.actionscript.3 + + + match + (\w+)\s*(=) + + + + method + + begin + (?x) (^|\s+) ((\w+)\s+)? ((\w+)\s+)? ((\w+)\s+)? (\w+) (?=\s+\bfunction\b) + beginCaptures + + 3 + + name + storage.modifier.actionscript.3 + + 5 + + name + storage.modifier.actionscript.3 + + 7 + + name + storage.modifier.actionscript.3 + + 8 + + name + storage.modifier.actionscript.3 + + + end + (?<=(;|\})) + name + meta.method.actionscript.3 + patterns + + + include + #functions + + + include + #code_block + + + + mxml + + begin + <!\[CDATA\[ + end + \]\]> + name + meta.cdata.actionscript.3 + patterns + + + include + #comments + + + include + #import + + + include + #metadata + + + include + #class + + + include + #namespace_declaration + + + include + #use_namespace + + + include + #class_declaration + + + include + #method + + + include + #comments + + + include + #strings + + + include + #regexp + + + include + #numbers + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #primitive_functions + + + include + #language_constants + + + include + #language_variables + + + include + #other_keywords + + + include + #guess_type + + + include + #guess_constant + + + include + #other_operators + + + include + #arithmetic_operators + + + include + #array_access_operators + + + include + #vector_creation_operators + + + include + #variable_declaration + + + + numbers + + match + \b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\.?[0-9]*)|(\.[0-9]+))((e|E)(\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f)?\b + name + constant.numeric.actionscript.3 + + object_literal + + begin + \{ + end + \} + name + meta.object_literal.actionscript.3 + patterns + + + include + #object_literal + + + include + #comments + + + include + #strings + + + include + #regexp + + + include + #numbers + + + include + #primitive_types + + + include + #primitive_error_types + + + include + #dynamic_type + + + include + #primitive_functions + + + include + #language_constants + + + include + #language_variables + + + include + #guess_type + + + include + #guess_constant + + + include + #array_access_operators + + + include + #vector_creation_operators + + + include + #functions + + + + other_keywords + + match + \b(as|delete|in|instanceof|is|native|new|to|typeof)\b + name + keyword.other.actionscript.3 + + other_operators + + match + (\.|=) + name + keyword.operator.actionscript.3 + + package + + begin + (^|\s+)(package)\b + beginCaptures + + 2 + + name + keyword.other.actionscript.3 + + + end + \} + name + meta.package.actionscript.3 + patterns + + + include + #package_name + + + include + #variable_declaration + + + include + #method + + + include + #comments + + + include + #return_type + + + include + #import + + + include + #use_namespace + + + include + #strings + + + include + #numbers + + + include + #language_constants + + + include + #metadata + + + include + #class + + + include + #interface + + + include + #namespace_declaration + + + + package_name + + begin + (?<=package)\s+([\w\._]*)\b + end + \{ + name + meta.package_name.actionscript.3 + + primitive_types + + captures + + 1 + + name + support.class.builtin.actionscript.3 + + + match + \b(Array|Boolean|Class|Date|Function|int|JSON|Math|Namespace|Number|Object|QName|RegExp|String|uint|Vector|XML|XMLList|\*(?<=a))\b + + primitive_error_types + + captures + + 1 + + name + support.class.error.actionscript.3 + + + match + \b((Argument|Definition|Eval|Internal|Range|Reference|Security|Syntax|Type|URI|Verify)?Error)\b + + primitive_functions + + captures + + 1 + + name + support.function.actionscript.3 + + + match + \b(decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|escape|isFinite|isNaN|isXMLName|parseFloat|parseInt|trace|unescape)(?=\s*\() + + regexp + + begin + (?<=[=(:,\[]|^|return|&&|\|\||!)\s*(/)(?![/*+{}?]) + end + $|(/)[igm]* + name + string.regex.actionscript.3 + patterns + + + match + \\. + name + constant.character.escape.actionscript.3 + + + match + \[(\\\]|[^\]])*\] + name + constant.character.class.actionscript.3 + + + + return_type + + captures + + 1 + + name + keyword.operator.actionscript.3 + + 2 + + name + support.type.actionscript.3 + + 3 + + name + support.type.actionscript.3 + + 4 + + name + support.type.actionscript.3 + + + match + (\:)\s*(?:([A-Za-z\$][A-Za-z0-9_\$]+(?:\.[A-Za-z\$][A-Za-z0-9_\$]+)*)(?:\.<([A-Za-z\$][A-Za-z0-9_\$]+(?:\.[A-Za-z\$][A-Za-z0-9_\$]+)*)>)?)|(\*) + + strings + + patterns + + + begin + " + end + " + name + string.quoted.double.actionscript.3 + patterns + + + include + #escapes + + + + + begin + ' + end + ' + name + string.quoted.single.actionscript.3 + patterns + + + include + #escapes + + + + + + metadata + + begin + \[\s*\b(\w+)\b + beginCaptures + + 1 + + name + keyword.other.actionscript.3 + + + end + \] + name + meta.metadata_info.actionscript.3 + patterns + + + include + #metadata_info + + + + use_namespace + + captures + + 2 + + name + keyword.other.actionscript.3 + + 3 + + name + keyword.other.actionscript.3 + + 4 + + name + storage.modifier.actionscript.3 + + + match + (?x) (^|\s+|;) (use\s+)? (namespace) \s+ (\w+) \s* (;|$) + + variable_declaration + + captures + + 2 + + name + storage.modifier.actionscript.3 + + 4 + + name + storage.modifier.actionscript.3 + + 6 + + name + storage.modifier.actionscript.3 + + 7 + + name + storage.modifier.actionscript.3 + + 8 + + name + keyword.operator.actionscript.3 + + + match + (?x) ((static)\s+)? ((\w+)\s+)? ((static)\s+)? (const|var) \s+ (?:[A-Za-z0-9_\$]+)(?:\s*(:))? + name + meta.variable_declaration.actionscript.3 + + vector_creation_operators + + match + (<|>) + name + keyword.operator.actionscript.3 + + + scopeName + source.actionscript.3 + uuid + aa6f75ba-ab10-466e-8c6f-28c69aca1e9d + + \ No newline at end of file diff --git a/syntaxes/MXML.tmLanguage b/syntaxes/MXML.tmLanguage new file mode 100644 index 0000000..9878b71 --- /dev/null +++ b/syntaxes/MXML.tmLanguage @@ -0,0 +1,193 @@ + + + + + fileTypes + + mxml + + name + MXML + patterns + + + begin + (?=<(?:fx|mx):Script(?:\s+(?:\w+:)?\w+=(["']).+\1)*\s*>) + end + (?<=<\/(?:fx|mx):Script>) + name + meta.script.mxml + patterns + + + match + <(?:fx|mx):Script[^>]*> + name + entity.name.tag.xml + + + match + <\/(?:fx|mx):Script> + name + entity.name.tag.xml + + + begin + (?=<!\[CDATA\[) + end + (?<=\]\]>) + name + meta.cdata.mxml.script + patterns + + + include + source.actionscript.3 + + + + + + + begin + <(?:fx|mx):Style> + end + <\/(?:fx|mx):Style> + name + entity.name.tag.xml.mxml.style + patterns + + + include + source.css + + + + + begin + (?=<(?:fx|mx):Metadata(?:\s+(?:\w+:)?\w+=(["']).+\1)*\s*>) + end + (?<=<\/(?:fx|mx):Metadata>) + name + meta.metadata.mxml + patterns + + + match + <(?:fx|mx):Metadata[^>]*> + name + entity.name.tag.xml + + + match + <\/(?:fx|mx):Metadata> + name + entity.name.tag.xml + + + include + #metadata + + + begin + /\*\*(?!/) + end + \*/ + name + comment.block.documentation.actionscript.3 + patterns + + + match + @(copy|default|eventType|example|exampleText|includeExample|inheritDoc|internal|param|private|return|see|since|throws)\b + name + keyword.other.documentation.actionscript.3.asdoc + + + + + + + include + text.xml + + + repository + + metadata + + begin + \[\s*\b(\w+)\b + beginCaptures + + 1 + + name + keyword.other.actionscript.3 + + + end + \] + name + meta.metadata_info.actionscript.3 + patterns + + + include + #metadata_info + + + + metadata_info + + begin + \( + end + \) + patterns + + + include + #strings + + + captures + + 1 + + name + variable.parameter.actionscript.3 + + + match + (\w+)\s*= + + + + strings + + patterns + + + begin + " + end + " + name + string.quoted.double.actionscript.3 + + + begin + ' + end + ' + name + string.quoted.single.actionscript.3 + + + + + scopeName + text.mxml + +