Вы находитесь на странице: 1из 1244

ACTIONSCRIPT 3.


. - http://help.adobe.com/ru_RU/legalnotices/index.html.

23.11.2012.

iii

1.

...................................................................... 1

.............................................................................. 4

:
2.

.................................................................. 6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

length

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


: ASCII-
3.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Array

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

: PlayList

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

4.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

ActionScript 3.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Flash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

: CustomErrors

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

5.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83


: Wiki

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

23.11.2012.

iv

ACTIONSCRIPT 3.0

6. XML
XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
E4X XML
XML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

XMLList

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

XML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

XML
XML-

XML
XML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

XML-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

XML ActionScript: RSS

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

7. JSON
API- JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
JSON

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

8.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
ActionScript 3.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

Event

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

9.
10.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211


: SpriteArranger

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

11.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Point

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Rectangle
Matrix

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

:
12. API
API-
Graphics

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

23.11.2012.

ACTIONSCRIPT 3.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Math
API

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

API :
API

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

13.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Bitmap BitmapData

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284

14.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

: Filter Workbench

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314

15. Pixel Bender


Pixel Bender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

16.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
MovieClip

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

MovieClip ActionScript
SWF-

: RuntimeAssetsExplorer
17.


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361

Flash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

23.11.2012.

vi

ACTIONSCRIPT 3.0

18.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

IK Mover

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377

19. (3D)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378

Flash Player AIR


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391

20.
21. TextField
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402



. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416

TextField:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

22. Flash Text Engine


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
FTE

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442

Flash Text Engine:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448

23. Text Layout Framework


Text Layout Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Text Layout Framework

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459

TLF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464

TLF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468

TLF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

TLF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470

, TLF
TLF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472

23.11.2012.

vii

ACTIONSCRIPT 3.0

24.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

: Podcast Player

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500

25.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

Video

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520



NetStream

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537


: Video Jukebox

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542

StageVideo

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548

26.
Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564

27. (DRM)

DRM NetStream
DRMStatusEvent

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576

DRMAuthenticateEvent
DRMErrorEvent

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

23.11.2012.

viii

ACTIONSCRIPT 3.0

DRMManager

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581

DRMContentData

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583

Flash Player Adobe Access

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

Open Source Media Framework

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589

28. PDF- AIR


PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
PDF-
PDF

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594

PDF AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595

29.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599

30.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
IME

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609

31.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
: WordSearch

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620

32. ,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637

33.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641

HTML AIR
Clipboard

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644

34.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652

23.11.2012.

ix

ACTIONSCRIPT 3.0

35. AIR
AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654


HTML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662

HTML-
HTML-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667

: HTML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667

HTML

36.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679

(AIR)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686

HTML (AIR)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688

(AIR)

. . . . . . . . . . . . . . . . . . 669

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690

: (AIR)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

37. AIR
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699

38.
FileReference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
API- AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716

39.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763

40. SQL AIR


SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772

SQL

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779


SQL
SQL

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831

41.
ByteArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
ByteArray: zip-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841

42.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851

(DNS)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853

23.11.2012.

ACTIONSCRIPT 3.0

43.
TCP- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
UDP- (AIR)
IPv6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869

44. HTTP

-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880

URL-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888

45. Flash Player AIR


LocalConnection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892

AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895

46. AIR
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901

47. API
API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
API
ExternalInterface

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 906

API: ActionScript JavaScript -

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910

48. XML AIR


XML- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
XML-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922

IURIDereferencer

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925

49.

System

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 933

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934

Capabilities

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936

50. AIR
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943

AIR
AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949

51. AIR
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 951

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952

23.11.2012.

xi

ACTIONSCRIPT 3.0

AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953

52. AIR
AIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 954

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 971

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 983

53. AIR
AIR

54.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 991

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 992

Flash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 993

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 996

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 998

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1000

: ,
:
55. Geolocation

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1002

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1004

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007

56.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1011
flash.globalization

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1012

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1014

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1015

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1018

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1020

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1022

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023

. ,

. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1024

57.
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1029
Flex

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030

Flash
AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030

58. HTML
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1033
AIR WebKit

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1036

23.11.2012.

xii

ACTIONSCRIPT 3.0

59. HTML JavaScript AIR


HTMLLoader
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1053
JavaScript

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1055

API- AIR JavaScript


URL- AIR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1060

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1062

ActionScript JavaScript
DOM JavaScript ActionScript
SWF- HTML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1064

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1066

ActionScript HTML-
Date RegExp

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1069

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1071

HTML ActionScript

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1071


1073
60. HTML- AIR
HTMLLoader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1078
HTML
HTML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1081

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1082

HTML
HTML

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1083

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1083

, , HTML
HTMLLoader

. . . 1084

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1095

61. AIR HTML


HTMLLoader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097
DOM ActionScript

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1098

JavaScript

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1098

JavaScript

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1100

62. HTML-
StageWebView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1103

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1104

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1105

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1106
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1107

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1109

63. worker
worker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1111
worker
worker

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1112

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1115

64.
Flash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1120

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1122

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1127

API-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1136

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1138

23.11.2012.

xiii

ACTIONSCRIPT 3.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1140

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1141

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1144

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1148

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1150

SWF-,

LocalConnection

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1155

URL-

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1155

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1157

, ,
AIR

. . . . . . . . . . . . . . . . . . 1154

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159

65. ActionScript
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1184
ActionScript 3.0 Flash Professional
ActionScript 3.0 Flash Builder

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1187

ActionScript 3.0

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1188

66. SQL
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1194

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1217

67. SQL,
68. AGAL (Adobe Graphics Assembly Language)
- AGAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1227

23.11.2012.

1.
Flash Player 9 , Adobe AIR 1.0
, .
ActionScript 3.0 ,
. : Date
Timer flash.utils.
, ActionScript.
,
. ActionScript Date
, . Date
, , , , , , , ,
. ActionScript Timer,
- .


Date
flash.utils.Timer


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 Date.
Date , UTC
. UTC , (GMT).

Date
Flash Player 9 , Adobe AIR 1.0
Date .
.
-, Date() , ,
. :
var now:Date = new Date();

23.11.2012.

ACTIONSCRIPT 3.0

-, Date() ,
1 1970 ., Date.
, 1 1970 . UTC.
, Date , ,
UTC. Date
milliseconds UTC.
Date, 1 1970 . UTC:
var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
// gets a Date one day after the start date of 1/1/1970
var startTime:Date = new Date(millisecondsPerDay);

-, Date() .
, , , , ,
Date. , UTC.
Date, 1 2000 . :
var millenium:Date = new Date(2000, 0, 1, 0, 0, 0, 0);

-, Date() -.
, Date.
Date() try..catch
. Date() (
c ActionScript 3.0 Adobe Flash Platform).
Date :
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");

Date() -, . ,
Date .


Flash Player 9 , Adobe AIR 1.0
Date
Date. Date:

fullYear;
month, 0 11, 0 , 11 ;
date, 1 31;
day, , 0 ();
hours 0 23;

minutes;

seconds;
milliseconds.
Date . ,
Date :

month;
getMonth();

23.11.2012.

ACTIONSCRIPT 3.0

monthUTC;
getMonthUTC().
, .
. ,
milliseconds 999, 1000 seconds
1, milliseconds 0.
Date 1 1970 (UTC),
getTime(). setTime()
Date 1 1970 (UTC).


Flash Player 9 , Adobe AIR 1.0
Date . ,
.
,
, :
public static const millisecondsPerMinute:int = 1000 * 60;
public static const millisecondsPerHour:int = 1000 * 60 * 60;
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;

, ,
.
getTime() setTime().
var oneHourFromNow:Date = new Date();
oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour);

Date
milliseconds. , 30 .
// sets the invoice date to today's date
var invoiceDate:Date = new Date();
// adds 30 days to get the due date
var dueDate:Date = new Date(invoiceDate.getTime() + (30 * millisecondsPerDay));

, millisecondsPerDay 30 30 ,
invoiceDate dueDate.


Flash Player 9 , Adobe AIR 1.0
,
. getTimezoneOffset(),
, Date UTC.
, :
.

23.11.2012.

ACTIONSCRIPT 3.0

,
UTC.
, Date :
// creates a Date in local time
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");
// converts the Date to UTC by adding or subtracting the time zone offset
var offsetMilliseconds:Number = nextDay.getTimezoneOffset() * 60 * 1000;
nextDay.setTime(nextDay.getTime() + offsetMilliseconds);


Flash Player 9 , Adobe AIR 1.0
Adobe Flash CS4 Professional ,
. ActionScript
.


Flash Player 9 , Adobe AIR 1.0

for do..while.
, , , ,
- , - .
, .
: , , ,
.
ActionScript 3.0 Timer . ActionScript
3.0 Timer .

Timer
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 Timer
(flash.utils.Timer), .
Timer, ,
.
, , Timer,
60 :
var oneMinuteTimer:Timer = new Timer(1000, 60);

Timer TimerEvent .
TimerEvent timer ( TimerEvent.TIMER). TimerEvent
, Event.

23.11.2012.

ACTIONSCRIPT 3.0

Timer , timerComplete
( TimerEvent.TIMER_COMPLETE) .
, Timer:
package
{
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class ShortTimer extends Sprite
{
public function ShortTimer()
{
// creates a new five-second Timer
var minuteTimer:Timer = new Timer(1000, 5);
// designates listeners for the interval and completion events
minuteTimer.addEventListener(TimerEvent.TIMER, onTick);
minuteTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
// starts the timer ticking
minuteTimer.start();
}
public function onTick(event:TimerEvent):void
{
// displays the tick count so far
// The target of this event is the Timer instance itself.
trace("tick " + event.target.currentCount);
}
public function onTimerComplete(event:TimerEvent):void
{
trace("Time's Up!");
}
}
}

ShortTimer Timer,
. ,
, timerComplete.
, onTick() .
onTick() .
onTimerComplete(), , .

, :
tick 1
tick 2
tick 3
tick 4
tick 5
Time's Up!

23.11.2012.

ACTIONSCRIPT 3.0

flash.utils
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 , ActionScript 2.0.
flash.utils, , ActionScript 2.0.

clearInterval(id:uint):void

setInterval().

clearTimeout(id:uint):void

setTimeout().

getTimer():int

,
Adobe Flash Adobe AIR.

setInterval(closure:Function,
delay:Number, ... arguments):uint

( ).

setTimeout(closure:Function,
delay:Number, ... arguments):uint

( ).

ActionScript 3.0 . Adobe


ActionScript 3.0. ,
Timer .

:
Flash Player 9 , Adobe AIR 1.0
:

, ;
Timer .

www.adobe.com/go/learn_programmingAS3samples_flash_ru. SimpleClock
Samples/SimpleClock. .
File

SimpleClockApp.mxml

Flash (FLA) Flex (MXML).

SimpleClockApp.fla
com/example/programmingas3/simpleclock/SimpleClock.as

com/example/programmingas3/simpleclock/AnalogClockFace.as

,
.

23.11.2012.

ACTIONSCRIPT 3.0

SimpleClock
Flash Player 9 , Adobe AIR 1.0
, ,
, . SimpleClock
SimpleClock , AnalogClockFace
.
SimpleClock ( ,
Flash SimpleClock Sprite):
public class SimpleClock extends UIComponent
{
/**
* The time display component.
*/
private var face:AnalogClockFace;
/**
* The Timer that acts like a heartbeat for the application.
*/
private var ticker:Timer;

face, AnalogClockFace;
ticker, Timer.
SimpleClock . initClock() :
Timer.


Flash Player 9 , Adobe AIR 1.0
SimpleClock :
/**
* Sets up a SimpleClock instance.
*/
public function initClock(faceSize:Number = 200)
{
// creates the clock face and adds it to the display list
face = new AnalogClockFace(Math.max(20, faceSize));
face.init();
addChild(face);
// draws the initial clock display
face.draw();

initClock(). faceSize ,
200 .

addChild(), DisplayObjectContainer.
AnalogClockFace.draw(), .

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
initClock() :
// creates a Timer that fires an event once per second
ticker = new Timer(1000);
// designates the onTick() method to handle Timer events
ticker.addEventListener(TimerEvent.TIMER, onTick);
// starts the clock ticking
ticker.start();

Timer, (
1000 ). Timer() repeatCount, Timer
.
SimpleClock.onTick() timer:
public function onTick(event:TimerEvent):void
{
// updates the clock display
face.draw();
}

AnalogClockFace.draw() .


Flash Player 9 , Adobe AIR 1.0
AnalogClockFace
. AnalogClockFace ,
, Shape: ,
.
SimpleClock AnalogClockFace.draw(),
:
/**
* Called by the parent container when the display is being drawn.
*/
public override function draw():void
{
// stores the current date and time in an instance variable
currentTime = new Date();
showTime(currentTime);
}

,
. showTime(), ,
:

23.11.2012.

ACTIONSCRIPT 3.0

/**
* Displays the given Date/Time in that good old analog clock style.
*/
public function showTime(time:Date):void
{
// gets the time values
var seconds:uint = time.getSeconds();
var minutes:uint = time.getMinutes();
var hours:uint = time.getHours();
// multiplies by 6 to get degrees
this.secondHand.rotation = 180 + (seconds * 6);
this.minuteHand.rotation = 180 + (minutes * 6);
// Multiply by 30 to get basic degrees, then
// add up to 29.5 degrees (59 * 0.5)
// to account for the minutes.
this.hourHand.rotation = 180 + (hours * 30) + (minutes * 0.5);
}

, .
. 60
, 6 (360/60).
.
, .
30 (360/12), ( 30 60 ).

23.11.2012.

10

2.
Flash Player 9 , Adobe AIR 1.0
String , .
. , , ,
, TextField, StaticText, XML, ContextMenu FileReference.
. ActionScript 3.0 ASCII
.


String
RegExp
parseFloat()
parseInt()


Flash Player 9 , Adobe AIR 1.0
, ,
, . ,
String .
var albumName:String = "Three for the money";

, ActionScript
. .
"Hello"
"555-7649"
"http://www.adobe.com/"

ActionScript, . ActionScript
String , .
String , ..
ActionScript.

, .
ASCII . ASCII

26- .
( ).

23.11.2012.

ACTIONSCRIPT 3.0

.
, , "".

String . String
, String,
String , .
( ).
( ) ,

, .
, .
.


Flash Player 9 , Adobe AIR 1.0
String () ActionScript 3.0.
ActionScript ASCII .
. , (")
('). , :
var str1:String = "hello";
var str2:String = 'hello';

new, .
var str1:String = new String("hello");
var str2:String = new String(str1);
var str3:String = new String();
// str3 == ""

:
var str1:String = "hello";
var str2:String = new String("hello");

(') ,
('), (\). ,
(") ,
("), (\).
:
var str1:String = "That's \"A-OK\"";
var str2:String = 'That\'s "A-OK"';

,
, .
var str1:String = "ActionScript <span class='heavy'>3.0</span>";
var str2:String = '<item id="155">banana</item>';

23.11.2012.

11

ACTIONSCRIPT 3.0

, ActionScript (')
(' '). .
. ActionScript,
, .
, (\)
.
ESC

\b

\f

\n

\r

\t

\unnnn

, nnnn,
\u263a.

\\xnn

ASCII , nn

\'

\"

\\

length
Flash Player 9 , Adobe AIR 1.0
length, .
var str:String = "Adobe";
trace(str.length);

// output: 5

, .
var str1:String = new String();
trace(str1.length);
// output: 0
str2:String = '';
trace(str2.length);

// output: 0


Flash Player 9 , Adobe AIR 1.0
( ).
0. , y 0, w 5.

23.11.2012.

12

ACTIONSCRIPT 3.0

"yellow"

charAt()
charCodeAt(), .
var str:String = "hello world!";
for (var i:int = 0; i < str.length; i++)
{
trace(str.charAt(i), "-", str.charCodeAt(i));
}

.
h
e
l
l
o
w
o
r
l
d
!

- 104
- 101
- 108
- 108
- 111
32
- 119
- 111
- 114
- 108
- 100
- 33

, fromCharCode(),
.
var myStr:String = String.fromCharCode(104,101,108,108,111,32,119,111,114,108,100,33);
// Sets myStr to "hello world!"


Flash Player 9 , Adobe AIR 1.0
: <, <=, !=, ==, => >.
if while, .
var str1:String = "Apple";
var str2:String = "apple";
if (str1 < str2)
{
trace("A < a, B < b, C < c, ...");
}

, ActionScript
, , .
trace("A" < "B"); // true
trace("A" < "a"); // true
trace("Ab" < "az"); // true
trace("abc" < "abza"); // true

== != ,
.

23.11.2012.

13

ACTIONSCRIPT 3.0

var str1:String = "1";


var str1b:String = "1";
var str2:String = "2";
trace(str1 == str1b); // true
trace(str1 == str2); // false
var total:uint = 1;
trace(str1 == total); // true

Flash Player 9 , Adobe AIR 1.0


String .
toString().
var n:Number = 99.47;
var str:String = n.toString();
// str == "99.47"

+ String ,
toString() . . .
String() , ,
toString().


Flash Player 9 , Adobe AIR 1.0
. ,
+.
var str1:String = "green";
var str2:String = "ish";
var str3:String = str1 + str2; // str3 == "greenish"

+=, .
var str:String = "green";
str += "ish"; // str == "greenish"

, String concat(), .
var str1:String = "Bonjour";
var str2:String = "from";
var str3:String = "Paris";
var str4:String = str1.concat(" ", str2, " ", str3);
// str4 == "Bonjour from Paris"

+ ( +=) String , ActionScript


String, ,
.

23.11.2012.

14

ACTIONSCRIPT 3.0

var str:String = "Area = ";


var area:Number = Math.PI * Math.pow(3, 2);
str = str + area; // str == "Area = 28.274333882308138"

,
+, .
trace("Total: $" + 4.55 + 1.45); // output: Total: $4.551.45
trace("Total: $" + (4.55 + 1.45)); // output: Total: $6


Flash Player 9 , Adobe AIR 1.0
. , "abc" :
"", "a", "ab", "abc", "b", "bc", "c".
ActionScript.
ActionScript . ,
: A, B C (
).
/ABC\d/

ActionScript
. .
. .
82.


Flash Player 9 , Adobe AIR 1.0
substr() substring() . .
.
. substr() length,
, substring() end,
( ).
.
var str:String = "Hello from Paris, Texas!!!";
trace(str.substr(11,15)); // output: Paris, Texas!!!
trace(str.substring(11,15)); // output: Pari

slice() substring().
, . slice()
. , .

23.11.2012.

15

ACTIONSCRIPT 3.0

var str:String = "Hello from Paris,


trace(str.slice(11,15)); // output:
trace(str.slice(-3,-1)); // output:
trace(str.slice(-3,26)); // output:
trace(str.slice(-3,str.length)); //
trace(str.slice(-8,-3)); // output:

Texas!!!";
Pari
!!
!!!
output: !!!
Texas

slice()
.


Flash Player 9 , Adobe AIR 1.0
indexOf() lastIndexOf() ,
.
var str:String = "The moon, the stars, the sea, the land";
trace(str.indexOf("the")); // output: 10

, indexOf() .
, , ,
.
var str:String = "The moon, the stars, the sea, the land"
trace(str.indexOf("the", 11)); // output: 21

lastIndexOf() .
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the")); // output: 30

lastIndexOf() ,
( ).
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the", 29)); // output: 21

,
Flash Player 9 , Adobe AIR 1.0
split() , . , , ,
.
, ,
(&).
var queryStr:String = "first=joe&last=cheng&title=manager&StartDate=3/6/65";
var params:Array = queryStr.split("&", 2); // params == ["first=joe","last=cheng"]

, split() .
.
var str:String = "Give me\t5."
var a:Array = str.split(/\s+/); // a == ["Give","me","5."]

23.11.2012.

16

ACTIONSCRIPT 3.0

. 82
c ActionScript 3.0 Adobe Flash Platform.


Flash Player 9 , Adobe AIR 1.0
String .

match() search() , .
replace() , ,
.
.
, ,
. .
82.

search() , ,
.
var str:String = "The more the merrier.";
// (This search is case-sensitive.)
trace(str.search("the")); // output: 9

, .
var pattern:RegExp = /the/i;
var str:String = "The more the merrier.";
trace(str.search(pattern)); // 0

trace() 0, 0.
i, .
search() ,
g (global).
,
, .
var pattern:RegExp = /"[^"]*"/;
var str:String = "The \"more\" the merrier.";
trace(str.search(pattern)); // output: 4
str = "The \"more the merrier.";
trace(str.search(pattern)); // output: -1
// (Indicates no match, since there is no closing double quotation mark.)

match() . . ,
global, , match()
.
var str:String = "bob@example.com, omar@example.org";
var pattern:RegExp = /\w*@\w*\.[org|com]+/g;
var results:Array = str.match(pattern);

23.11.2012.

17

ACTIONSCRIPT 3.0

result :
["bob@example.com","omar@example.org"]

.
82.

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

, ,
i (ignoreCase), , g (global).
. 82.
$. $
, .
$

$$

$&

$`

, .
(`), (') (').

$'

, .
(').

$n

n, n 1 9, $n
.

$nn

nn, nn ( 01 99).
nn , .

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

replace().
.

23.11.2012.

18

19

ACTIONSCRIPT 3.0

var str:String = "Now only $9.95!";


var price:RegExp = /\$([\d,]+.\d+)+/i;
trace(str.replace(price, usdToEuro));
function usdToEuro(matchedSubstring:String, capturedMatch1:String,
str:String):String
{
var usd:String = capturedMatch1;
usd = usd.replace(",", "");
var exchangeRate:Number = 0.853690;
var euro:Number = parseFloat(usd) * exchangeRate;
const euroSymbol:String = String.fromCharCode(8364);
return euro.toFixed(2) + " " + euroSymbol;
}

index:int,

replace() ,
:

.
.
. ,
arguments.length - 3 .

, .
.


Flash Player 9 , Adobe AIR 1.0
, toLowerCase() toUpperCase()
.
var str:String = "Dr. Bob Roberts, #9."
trace(str.toLowerCase()); // dr. bob roberts, #9.
trace(str.toUpperCase()); // DR. BOB ROBERTS, #9.

.
, :
str = str.toUpperCase();

, az AZ.
var str:String = "Jos Bara";
trace(str.toUpperCase(), str.toLowerCase()); // JOS BARA jos bara

23.11.2012.

ACTIONSCRIPT 3.0

: ASCII-
Flash Player 9 , Adobe AIR 1.0
ASCII- String ActionScript 3.0,
.

split() String ,
( -).

,
, split(),
substring() substr().

getCharAt() (
ASCII, ).

, ASCII- .
ASCII- ,
, Courier New.
ASCII-, .

, ASCII-, .


www.adobe.com/go/learn_programmingAS3samples_flash_ru. ASCIIArt
Samples/AsciiArt. .

23.11.2012.

20

21

ACTIONSCRIPT 3.0

File

AsciiArtApp.mxml

Flash (FLA) Flex (MXML)

AsciiArtApp.fla
com/example/programmingas3/asciiArt/AsciiArtBuilder.as

, ,

, ,
.

com/example/programmingas3/asciiArt/BitmapToAsciiConverter.as

, parseBitmapData()

String.

com/example/programmingas3/asciiArt/Image.as

,
.

com/example/programmingas3/asciiArt/ImageInfo.as

,
ASCII- (, , URL-
..).

image/

, ,
.

txt/ImageData.txt

-,
,
.

,
Flash Player 9 , Adobe AIR 1.0
,
. , (,
), SWF-.
, , URL- ,
) ( txt/ImageData.txt
). :
FILENAMETITLEWHITE_THRESHHOLDBLACK_THRESHHOLD
FruitBasket.jpgPear, apple, orange, and bananad810
Banana.jpgA picture of a bananaC820
Orange.jpgorangeFF20
Apple.jpgpicture of an apple6E10

-.
. ,
:

;
;
;
, .
, AsciiArtBuilder
,
parseImageInfo() AsciiArtBuilder:

23.11.2012.

ACTIONSCRIPT 3.0

var lines:Array = _imageInfoLoader.data.split("\n");


var numLines:uint = lines.length;
for (var i:uint = 1; i < numLines; i++)
{
var imageInfoRaw:String = lines[i];
...
if (imageInfoRaw.length > 0)
{
// Create a new image info record and add it to the array of image info.
var imageInfo:ImageInfo = new ImageInfo();
// Split the current line into values (separated by tab (\t)
// characters) and extract the individual properties:
var imageProperties:Array = imageInfoRaw.split("\t");
imageInfo.fileName = imageProperties[0];
imageInfo.title = normalizeTitle(imageProperties[1]);
imageInfo.whiteThreshold = parseInt(imageProperties[2], 16);
imageInfo.blackThreshold = parseInt(imageProperties[3], 16);
result.push(imageInfo);
}
}

String, _imageInfoLoader.data.
split(), ("\n")
String (lines),
. ( ,
, ). split(),
( Array
imageProperties). split()
("\t"), .

String

Flash Player 9 , Adobe AIR 1.0



,
( , ). ,
,
.

:
imageInfo.title = normalizeTitle(imageProperties[1]);

normalizeTitle()
ImageInfo.

23.11.2012.

22

ACTIONSCRIPT 3.0

private
{
var
var
for
{

function normalizeTitle(title:String):String
words:Array = title.split(" ");
len:uint = words.length;
(var i:uint; i < len; i++)
words[i] = capitalizeFirstLetter(words[i]);

}
return words.join(" ");
}

split() ( ),
capitalizeFirstLetter(), join() Array
.
capitalizeFirstLetter() .
/**
* Capitalizes the first letter of a single word, unless it's one of
* a set of words that are normally not capitalized in English.
*/
private function capitalizeFirstLetter(word:String):String
{
switch (word)
{
case "and":
case "the":
case "in":
case "an":
case "or":
case "at":
case "of":
case "a":
// Don't do anything to these words.
break;
default:
// For any other word, capitalize the first character.
var firstLetter:String = word.substr(0, 1);
firstLetter = firstLetter.toUpperCase();
var otherLetters:String = word.substring(1);
word = firstLetter + otherLetters;
}
return word;
}

23.11.2012.

23

ACTIONSCRIPT 3.0

: and, the, in, an, or,


at, of a. ( .) ,
switch, , .
, switch. ,
, .
1 substr(0, 1),

0 ( , 0).
( 1).
2 toUpperCase().
3 substring(1),

1 ( ) (
substring()).
4

: firstLetter + otherLetters.

ASCII-
Flash Player 9 , Adobe AIR 1.0
BitmapToAsciiConverter
ASCII.
parseBitmapData(), .
var result:String = "";
// Loop through the rows of pixels top to bottom:
for (var y:uint = 0; y < _data.height; y += verticalResolution)
{
// Within each row, loop through pixels left to right:
for (var x:uint = 0; x < _data.width; x += horizontalResolution)
{
...
// Convert the gray value in the 0-255 range to a value
// in the 0-64 range (since that's the number of "shades of
// gray" in the set of available characters):
index = Math.floor(grayVal / 4);
result += palette.charAt(index);
}
result += "\n";
}
return result;

23.11.2012.

24

ACTIONSCRIPT 3.0

String result,
ASCII- .
. (
), ,
( 0 255). 4 ( ),
0-63, index. (
0 63, ASCII, ,
64 .) String
BitmapToAsciiConverter.
// The characters are in order from darkest to lightest, so that their
// position (index) in the string corresponds to a relative color value
// (0 = black).
private static const palette:String =
"@#$%&8BMW*mwqpdbkhaoQ0OZXYUJCLtfjzxnuvcr[]{}1()|/?Il!i><+_~-;,. ";

index , ASCII ,
String palette charAt().
String result (+=).
, result ,
-.

23.11.2012.

25

26

3.
Flash Player 9 , Adobe AIR 1.0
.
,
.
, . , ,
, Vector.


Array
Vector


Flash Player 9 , Adobe AIR 1.0
, . ,
,
. .
Song .
, ,
. ,
ActionScript. .
.
, .
( ).
( , ).
( ).
, ,
. ActionScript addSongsToPlaylist(),
. ,
(, ), addSongsToPlaylist()
, Song. addSongsToPlaylist() ,
()
.
ActionScript .
( ).
.
. Array ,
.

23.11.2012.

ACTIONSCRIPT 3.0

(,
). Array
. Vector ,
. Vector Array,
. Vector ,
Flash Player 10 Adobe AIR 1.5.
.
, (, ,
).
,
. , ActionScript 3.0
Dictionary, . ,
.

,
, :
, .
([]) , ,

.
, , .
, .
, Vector.
, -.

.
.
, .
,

() .
,

.
, , ,

.
T , Vector
, . T ,
Type. ( , ).
, Vector, (

). (.),
(<>). : Vector.<T>. ,
, : T.
, .

23.11.2012.

27

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
, . 0,
1. ActionScript 3.0
: Array Vector.
32- .
232 - 1 4 294 967 295. ,
, .
([]),
. ,
( 0) songTitles.
songTitles[0]

, ,
. ( , , .)
,
.
songTitles[1] = "Symphony No. 5 in D minor";

,
.
var nextSong:String = songTitles[2];

. (
, ,
Number, .)

. .
Array oddNumbers. trace()
: oddNumber[index] = value.
var oddNumbers:Array = [1, 3, 5, 7, 9, 11];
var len:uint = oddNumbers.length;
for (var i:uint = 0; i < len; i++)
{
trace("oddNumbers[" + i.toString() + "] = " + oddNumbers[i].toString());
}

Array
Array. Array
. Array , .
, Array String 0, Number
1 XML 2.

23.11.2012.

28

ACTIONSCRIPT 3.0

Vector
, ActionScript 3.0, Vector.
Vector , Vector
.
. Vector , Flash Player 10 Adobe AIR 1.5.
Vector Vector,
, Vector.
Vector. ( ) ,
Vector.
Vector, .
, , Vector ,
Array:

. Array
0 7, 1 6. Vector, ,
( null) .

Vector. ,
Vector .

.
, (length 1).
, ( ,
[length]).
Vector
Array, :

:
Vector, Array.

: , .
Vector
Vector.
Vector. ,
push() unshift()
. ,
.

: ( )
Array.
, Vector Array.
Vector ( )
Vector. , Array,
, Vector.


Flash Player 9 , Adobe AIR 1.0
Array Vector . ,
, .

23.11.2012.

29

ACTIONSCRIPT 3.0

Array
Flash Player 9 , Adobe AIR 1.0
Array, Array() Array.
Array(). -,
. length Array
. , Array()
:
var names:Array = new Array();
trace(names.length); // output: 0

-, , Array(),
, undefined.
0 4 294 967 295. ,
Array(), :
var names:Array = new Array(3);
trace(names.length); // output: 3
trace(names[0]); // output: undefined
trace(names[1]); // output: undefined
trace(names[2]); // output: undefined

-, ,
, .
Array():
var names:Array = new Array("John", "Jane", "David");
trace(names.length); // output: 3
trace(names[0]); // output: John
trace(names[1]); // output: Jane
trace(names[2]); // output: David

Array. Array
, :
var names:Array = ["John", "Jane", "David"];

Vector
Flash Player 10 , Adobe AIR 1.5
Vector, Vector.<T>().
Vector Vector.<T>().
Vector. Flash Professional CS5 , Flash Builder 4 ,
Flex 4 Vector
Vector.
Vector (
Vector) . ,
Vector Vector.<T>(). ,
Vector ActionScript .
.
Vector. (.) ,
(<>), :

23.11.2012.

30

31

ACTIONSCRIPT 3.0

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

v Vector.<String>. ,
, String.
Vector() Vector ( Vector,
String). v.
Vector.<T>()
Vector.<T>() , Vector.
, Vector , length. ,
Vector.<T>() .
var names:Vector.<String> = new Vector.<String>();
trace(names.length); // output: 0

, Vector,
Vector. Vector
, ( length).
Vector , .
, null,
null. . ,
, , null.
Vector ages , 0.
var ages:Vector.<uint> = new Vector.<uint>(7);
trace(ages); // output: 0,0,0,0,0,0,0

, , Vector.<T>() Vector
, true ( fixed). Vector
, . ,
Vector .
Vector
Flash Professional CS5 , Flash Builder 4 , Flex 4
Vector.<T>(),
Vector:
// var v:Vector.<T> = new <T>[E0, ..., En-1 ,];
// For example:
var v:Vector.<int> = new <int>[0,1,2,];

.
; , var

v:Vector.<int> = new

<int>[0,,2,] .

Vector .
.

Vector .
fixed.

, ,
. :

23.11.2012.

ACTIONSCRIPT 3.0

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

Vector.<T>()
Vector.<T>() Vector ,
Vector Vector.<T>(). Vector.<T>()
. Vector.<T>(),
Vector, .
( Array Vector). Vector ,
.
Vector.<T>().
var friends:Vector.<String> = Vector.<String>(["Bob", "Larry", "Sarah"]);

Vector.<T>() . -,
Array, Vector. -,
( Array Vector)
.
ActionScript. , String Array
Vector. ("1.5") ,
("Waffles") 0 :
var numbers:Vector.<int> = Vector.<int>(["1.5", "17", "Waffles"]);
trace(numbers); // output: 1,17,0

, .
Vector.<T>()
, Vector (
). Vector.<T>()
Vector T Vector , T.


Flash Player 9 , Adobe AIR 1.0

([]). ,
Array Vector .
songTitles[5] = "Happy Birthday";

Array Vector ,
. ,
.
Array . Vector, ,
.
length Vector.
Vector , :
myVector[myVector.length] = valueToAdd;

23.11.2012.

32

ACTIONSCRIPT 3.0

Array Vector: push(), unshift() splice()


. push() . ,
, push(), .
unshift() , 0.
splice() .
. planets
. push() Mars.
unshift() Mercury. ,
splice() Venus Earth Mercury Mars. ,
splice(), 1. ,
1. , splice(), 0. ,
. , Venus Earth,
splice(), .
var planets:Array = new Array();
planets.push("Mars"); // array contents: Mars
planets.unshift("Mercury"); // array contents: Mercury,Mars
planets.splice(1, 0, "Venus", "Earth");
trace(planets); // array contents: Mercury,Venus,Earth,Mars

push() unshift() ,
. splice(), .
, splice()
. splice() ,
. splice() ,
.
. fixed Vector true,
. Vector
, .


Flash Player 9 , Adobe AIR 1.0

([]). , Array
Vector .
var myFavoriteSong:String = songTitles[3];

Array Vector, ,
. Array undefined, Vector
RangeError.
Array Vector: pop(), shift() splice() . pop()
. , . shift()
, . . 0. splice(),
, ,
, .
Array.
Array oceans .
, , .

23.11.2012.

33

ACTIONSCRIPT 3.0

-, splice() Aral Superior


Atlantic Indian. , splice(), 2. ,
, . . 2. , 2,
, . : Atlantic Indian ,
2.
-, pop() Huron. B-,
shift() Victoria.
var oceans:Array = ["Victoria", "Pacific", "Aral", "Superior", "Indian", "Huron"];
oceans.splice(2, 2, "Arctic", "Atlantic"); // replaces Aral and Superior
oceans.pop(); // removes Huron
oceans.shift(); // removes Victoria
trace(oceans);// output: Pacific,Arctic,Atlantic,Indian

pop() shift() , . Array,


Object, .
Vector . splice()
Array Vector . oceans ,
splice() Array Array, :
var lakes:Array = oceans.splice(2, 2, "Arctic", "Atlantic");
trace(lakes); // output: Aral,Superior

, delete Array. delete


Array undefined, . ,
delete oceans, Array 5.
var oceans:Array = ["Arctic", "Pacific", "Victoria", "Indian", "Atlantic"];
delete oceans[2];
trace(oceans);// output: Arctic,Pacific,,Indian,Atlantic
trace(oceans[2]); // output: undefined
trace(oceans.length); // output: 5

Array Vector length. length


, ,
length 1 . , oceans ,
, length
, :
var oceans:Array = ["Arctic", "Pacific", "Victoria", "Aral", "Superior"];
oceans.length = 2;
trace(oceans); // output: Arctic,Pacific

. fixed Vector true,


. Vector
, .

23.11.2012.

34

35

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
: reverse(), sort() sortOn(),
. .
Array
Vector.

Array

Vector

reverse()

,
, Array
, .

sort()

Array
,
.

sortOn()

,
Vector
,
.


,
.

reverse()
reverse() ,
. oceans
:
var oceans:Array = ["Arctic", "Atlantic", "Indian", "Pacific"];
oceans.reverse();
trace(oceans); // output: Pacific,Indian,Atlantic,Arctic

sort() ( Array)
Array sort()
. .
.

,
. , D b.

, .. (, A)
(, B).

, .
, (,
10 3, "1" , "3").
, ,
, , .
sort() Array options,
. Array,
.

Array.CASEINSENSITIVE . , ,

b D.

23.11.2012.

ACTIONSCRIPT 3.0

Array.DESCENDING . ,

Array.UNIQUESORT , .

Array.NUMERIC , 3

10.
. Array poets,
.
var poets:Array = ["Blake", "cummings", "Angelou", "Dante"];
poets.sort(); // default sort
trace(poets); // output: Angelou,Blake,Dante,cummings
poets.sort(Array.CASEINSENSITIVE);
trace(poets); // output: Angelou,Blake,cummings,Dante
poets.sort(Array.DESCENDING);
trace(poets); // output: cummings,Dante,Blake,Angelou
poets.sort(Array.DESCENDING | Array.CASEINSENSITIVE); // use two options
trace(poets); // output: Dante,cummings,Blake,Angelou

sort() ( Array Vector)


, Array,
. sort()
Vector. ,
sort().
, , ,
,
. ,
, Array.sort():
var names:Array = new Array("John Q. Smith", "Jane Doe", "Mike Jones");
function orderLastName(a, b):int
{
var lastName:RegExp = /\b\S+$/;
var name1 = a.match(lastName);
var name2 = b.match(lastName);
if (name1 < name2)
{
return -1;
}
else if (name1 > name2)
{
return 1;
}
else
{
return 0;
}
}
trace(names); // output: John Q. Smith,Jane Doe,Mike Jones
names.sort(orderLastName);
trace(names); // output: Jane Doe,Mike Jones,John Q. Smith

23.11.2012.

36

ACTIONSCRIPT 3.0

orderLastName()
.
orderLastName sort() names.
, a b,
. , , ,
:

-1 , (a) (b).
1 , (b) (a).
0 , .
sortOn() ( Array)
sortOn() Array , .
, .
sortOn() .
. Vector sortOn(). Array.
Array poets ,
. .
var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});

sortOn() Array born. sortOn()


: fieldName options. fieldName .
sortOn() "born" Array.NUMERIC. Array.NUMERIC
, , .
, , ,
, , .
poets.sortOn("born", Array.NUMERIC);
for (var i:int = 0; i < poets.length; ++i)
{
trace(poets[i].name, poets[i].born);
}
/* output:
Wang 701
Dante 1265
Blake 1757
cummings 1894
Angelou 1928
*/

23.11.2012.

37

ACTIONSCRIPT 3.0

( Array)
, sort() sortOn() Array.
Array, Array.RETURNINDEXEDARRAY
options. , Array
. ,
Array. ,
poets Array
Array.RETURNINDEXEDARRAY , options.
Array indices,
indices poets,
.
var indices:Array;
indices = poets.sortOn("born", Array.NUMERIC | Array.RETURNINDEXEDARRAY);
for (var i:int = 0; i < indices.length; ++i)
{
var index:int = indices[i];
trace(poets[index].name, poets[index].born);
}
/* output:
Wang 701
Dante 1265
Blake 1757
cummings 1894
Angelou 1928
*/


Flash Player 9 , Adobe AIR 1.0
Array Vector: concat(), join(), slice(), toString()
, . concat() slice() , join()
toString() . concat()
. slice()
startIndex endIndex. ,
, .
startIndex endIndex. ,
endIndex .
concat() slice()
:
var array1:Array = ["alpha", "beta"];
var array2:Array = array1.concat("gamma", "delta");
trace(array2); // output: alpha,beta,gamma,delta
var array3:Array = array1.concat(array2);
trace(array3); // output: alpha,beta,alpha,beta,gamma,delta
var array4:Array = array3.slice(2,5);
trace(array4); // output: alpha,beta,gamma

23.11.2012.

38

ACTIONSCRIPT 3.0

join() toString()
. join() ,
, , . join(),
toString(), delimiter,
.
Array rivers, join() toString()
. toString() ,
(riverCSV), join() , +.
var rivers:Array = ["Nile", "Amazon", "Yangtze", "Mississippi"];
var riverCSV:String = rivers.toString();
trace(riverCSV); // output: Nile,Amazon,Yangtze,Mississippi
var riverPSV:String = rivers.join("+");
trace(riverPSV); // output: Nile+Amazon+Yangtze+Mississippi

join() , Array
Vector , , ,
. :
var nested:Array = ["b","c","d"];
var letters:Array = ["a",nested,"e"];
var joined:String = letters.join("+");
trace(joined); // output: a+b,c,d+e


Flash Player 9 , Adobe AIR 1.0
, - ,
.
, .
Object, .
-. .
ActionScript 3.0 .
Dictionary flash.utils ,
. , String.

-
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 . -,
Object. Object ,
. Object, ,
.
.
, monitorInfo ,
-.

23.11.2012.

39

ACTIONSCRIPT 3.0

var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};


trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200

,
Object, :
var monitorInfo:Object = new Object();

Object
([]),
(.). , monitorArray:
monitorInfo["aspect ratio"] = "16:10"; // bad form, do not use spaces
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspect ratio"], monitorInfo.colors);
// output: 16:10 16.7 million

, aspect ratio .
([]) , .
.
Array (
), ([]) (.)
- .
Array, . ,
monitorInfo Array type
resolution :
var monitorInfo:Array = new Array();
monitorInfo["type"] = "Flat Panel";
monitorInfo["resolution"] = "1600 x 1200";
trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200

Array
. Array.length
Array, Array Array. Array
.

- ()
Flash Player 9 , Adobe AIR 1.0
Dictionary ,
, . , -
. , , Sprite
. Dictionary,
Sprite .
Sprite, Dictionary.
GroupA GroupB. ,
GroupA, GroupB Object. , ,
([]), ,
:

23.11.2012.

40

ACTIONSCRIPT 3.0

import flash.display.Sprite;
import flash.utils.Dictionary;
var groupMap:Dictionary = new Dictionary();
// objects to use
var spr1:Sprite =
var spr2:Sprite =
var spr3:Sprite =

as keys
new Sprite();
new Sprite();
new Sprite();

// objects to use as values


var groupA:Object = new Object();
var groupB:Object = new Object();
// Create new key-value pairs in dictionary.
groupMap[spr1] = groupA;
groupMap[spr2] = groupB;
groupMap[spr3] = groupB;
if (groupMap[spr1]
{
trace("spr1 is
}
if (groupMap[spr2]
{
trace("spr2 is
}
if (groupMap[spr3]
{
trace("spr3 is
}

== groupA)
in groupA");
== groupB)
in groupB");
== groupB)
in groupB");

-
Dictionary for..in for each..in. for..in
, for each..in ,
.
for..in - Dictionary.
Dictionary ([]).
groupMap Dictionary
for..in:
for (var key:Object in groupMap)
{
trace(key, groupMap[key]);
}
/* output:
[object Sprite] [object Object]
[object Sprite] [object Object]
[object Sprite] [object Object]
*/

for each..in Dictionary.


groupMap Dictionary for
each..in:

23.11.2012.

41

ACTIONSCRIPT 3.0

for each (var item:Object in groupMap)


{
trace(item);
}
/* output:
[object Object]
[object Object]
[object Object]
*/

-
Adobe Flash Player Adobe AIR
, . ,
,
. , , myObject
:
var myObject:Object = new Object();

,
. myObject null,
, , , ,
.
myObject Dictionary, .
, myObject
myMap:
import flash.utils.Dictionary;
var myObject:Object = new Object();
var myMap:Dictionary = new Dictionary();
myMap[myObject] = "foo";

, myObject, ,
. myObject myObject myMap, :
myObject = null;
delete myMap[myObject];

useWeakReference Dictionary,
. , . . ,
, . ,
myObject myMap, :
import flash.utils.Dictionary;
var myObject:Object = new Object();
var myMap:Dictionary = new Dictionary(true);
myMap[myObject] = "foo";
myObject = null; // Make object eligible for garbage collection.

23.11.2012.

42

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
. , ,
:
var tasks:Array = ["wash dishes", "take out trash"];

,
, . ,
tasks, .
.
. .


Flash Player 9 , Adobe AIR 1.0
.
, .
,
. , masterTaskList,
Array. , 0 , 6
. .
, masterTaskList.
.
var masterTaskList:Array = new Array();
masterTaskList[0] = ["wash dishes", "take out trash"];
masterTaskList[1] = ["wash dishes", "pay bills"];
masterTaskList[2] = ["wash dishes", "dentist", "wash dog"];
masterTaskList[3] = ["wash dishes"];
masterTaskList[4] = ["wash dishes", "clean house"];
masterTaskList[5] = ["wash dishes", "wash car", "pay rent"];
masterTaskList[6] = ["mow lawn", "fix chair"];


([]). , .
, 2
, 1 .
trace(masterTaskList[2][1]); // output: dentist

, 6 ,
0 .
trace(masterTaskList[6][0]); // output: mow lawn

23.11.2012.

43

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
.
,
. ,
- :
var masterTaskList:Object = new Object();
masterTaskList["Monday"] = ["wash dishes", "take out trash"];
masterTaskList["Tuesday"] = ["wash dishes", "pay bills"];
masterTaskList["Wednesday"] = ["wash dishes", "dentist", "wash dog"];
masterTaskList["Thursday"] = ["wash dishes"];
masterTaskList["Friday"] = ["wash dishes", "clean house"];
masterTaskList["Saturday"] = ["wash dishes", "wash car", "pay rent"];
masterTaskList["Sunday"] = ["mow lawn", "fix chair"];

,
.
trace(masterTaskList.Wednesday[1]); // output: dentist
trace(masterTaskList.Sunday[0]);// output: mow lawn

for..in,
([]) ,
. masterTaskList ,
, :
for (var day:String in masterTaskList)
{
trace(day + ": " + masterTaskList[day])
}
/* output:
Sunday: mow lawn,fix chair
Wednesday: wash dishes,dentist,wash dog
Friday: wash dishes,clean house
Thursday: wash dishes
Monday: wash dishes,take out trash
Saturday: wash dishes,wash car,pay rent
Tuesday: wash dishes,pay bills
*/


Flash Player 9 , Adobe AIR 1.0
Array .
concat() slice() .
, , .
, . .

23.11.2012.

44

ACTIONSCRIPT 3.0

, , ,
, . ,
.
Array.
clone(), .
Java. ,
ByteArray, .
, ,
, :
import flash.utils.ByteArray;
function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}

Array
Flash Player 9 , Adobe AIR 1.0
Array ,
Array. ,
Array , .
, ActionScript ,
Array, .
Array TypedArray,
. TypedArray
, Array,
. -, , . , TypedArray , ,
, , . -,
-
. -, , .
. .
Vector. Vector
Array .
Array.

extends , Array.
dynamic, Array.
.

23.11.2012.

45

ACTIONSCRIPT 3.0

TypedArray,
, .
, :
public dynamic class TypedArray extends Array
{
private const dataType:Class;
public function TypedArray(...args) {}
AS3 override function concat(...args):Array {}
AS3 override function push(...args):uint {}
AS3 override function splice(...args) {}
AS3 override function unshift(...args):uint {}
}

AS3 public,
, -as3 = true, -es =
false. Adobe Flash Builder AdobeFlashProfessional.
,
TypedArray,
-es true. -, override
AS3 public. -, super
Array.prototypesuper.
TypedArray
,
. ,
. ,
Array, 1 .
Function.apply(),
,
. , Function.apply() .
Array TypedArray.
, Array,
Array:

23.11.2012.

46

ACTIONSCRIPT 3.0

public dynamic class Array


{
public function Array(...args)
{
var n:uint = args.length
if (n == 1 && (args[0] is Number))
{
var dlen:Number = args[0];
var ulen:uint = dlen;
if (ulen != dlen)
{
throw new RangeError("Array index is not a 32-bit unsigned integer ("+dlen+")");
}
length = ulen;
}
else
{
length = n;
for (var i:int=0; i < n; i++)
{
this[i] = args[i]
}
}
}
}

TypedArray Array,
. -, Class,
. -, , ,
dataType. -, else length
for, length . -, for
push(),
. TypedArray:

23.11.2012.

47

ACTIONSCRIPT 3.0

public dynamic class TypedArray extends Array


{
private var dataType:Class;
public function TypedArray(typeParam:Class, ...args)
{
dataType = typeParam;
var n:uint = args.length
if (n == 1 && (args[0] is Number))
{
var dlen:Number = args[0];
var ulen:uint = dlen
if (ulen != dlen)
{
throw new RangeError("Array index is not a 32-bit unsigned integer ("+dlen+")")
}
length = ulen;
}
else
{
for (var i:int=0; i < n; i++)
{
// type check done in push()
this.push(args[i])
}
length = this.length;
}
}
}

TypedArray
TypedArray Array,
. ,
. ,
.
push() for..in
. , , args
splice(). for..in args dataType.
push() args,
:
AS3 override function push(...args):uint
{
for (var i:* in args)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
return (super.push.apply(this, args));
}

23.11.2012.

48

ACTIONSCRIPT 3.0

concat() TypedArray passArgs ,


. push(). for..in
args push() .
passArgs TypedArray, push() TypedArray. concat()
, :
AS3 override function concat(...args):Array
{
var passArgs:TypedArray = new TypedArray(dataType);
for (var i:* in args)
{
// type check done in push()
passArgs.push(args[i]);
}
return (super.concat.apply(this, passArgs));
}

splice() ,
. splice()
args 2 .
, splice() for, ,
args Array, TypedArray, , args.splice()
. for..in args
2 , splice() ,
:
AS3 override function splice(...args):*
{
if (args.length > 2)
{
for (var i:int=2; i< args.length; i++)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
}
return (super.splice.apply(this, args));
}

unshift(), ,
. unshift() , push(),
:
AS3 override function unshift(...args):uint
{
for (var i:* in args)
{
if (!(args[i] is dataType))
{
args.splice(i,1);
}
}
return (super.unshift.apply(this, args));
}
}

23.11.2012.

49

50

ACTIONSCRIPT 3.0

: PlayList
Flash Player 9 , Adobe AIR 1.0
PlayList ,
. :

;
;
;
, .

www.adobe.com/go/learn_programmingAS3samples_flash_ru. PlayList
Samples/PlayList. .
File

PlayList.mxml

Flash (FLA) Flex (MXML).

PlayList.fla
com/example/programmingas3/playlist/PlayList.as

, .
Array.
.

com/example/programmingas3/playlist/Song.as

,
. , PlayList,
Song.

com/example/programmingas3/playlist/SortProperty.as

,
Song,
Song .

PlayList
Flash Player 9 , Adobe AIR 1.0
PlayList Song. ,
( addSong())
( sortList()). , , songList,
. PlayList
Array:
public class PlayList
{
private var _songs:Array;
private var _currentSort:SortProperty = null;
private var _needToSort:Boolean = false;
...
}

Array _songs, PlayList ,


, (_needToSort),
(_currentSort).

23.11.2012.

ACTIONSCRIPT 3.0

, Array
. Array,
PlayList.
public function PlayList()
{
this._songs = new Array();
// Set the initial sorting.
this.sortList(SortProperty.TITLE);
}

_songs, .
, sortList().


Flash Player 9 , Adobe AIR 1.0
,
PlayList addSong().
/**
* Adds a song to the playlist.
*/
public function addSong(song:Song):void
{
this._songs.push(song);
this._needToSort = true;
}

addSong() push() _songs, Song,


addSong(), . push()
, . ,
push() ,
_needToSort true. sortList() ,
, .
, .
, , , ,
.


Flash Player 9 , Adobe AIR 1.0
Song, , ,
,
. PlayList
: , ;
; .

23.11.2012.

51

ACTIONSCRIPT 3.0


Song , , , ,
, . .
SortProperty, ,
.
public static const TITLE:SortProperty = new SortProperty("title");
public static const ARTIST:SortProperty = new SortProperty("artist");
public static const YEAR:SortProperty = new SortProperty("year");

SortProperty : TITLE, ARTIST YEAR,


Song, .
. , PlayList
sortList(), :
// Set the initial sorting.
this.sortList(SortProperty.TITLE);

SortProperty.TITLE, .

PlayList sortList(), :
/**
* Sorts the list of songs according to the specified property.
*/
public function sortList(sortProperty:SortProperty):void
{
...
var sortOptions:uint;
switch (sortProperty)
{
case SortProperty.TITLE:
sortOptions = Array.CASEINSENSITIVE;
break;
case SortProperty.ARTIST:
sortOptions = Array.CASEINSENSITIVE;
break;
case SortProperty.YEAR:
sortOptions = Array.NUMERIC;
break;
}
// Perform the actual sorting of the data.
this._songs.sortOn(sortProperty.propertyName, sortOptions);
// Save the current sort property.
this._currentSort = sortProperty;
// Record that the list is sorted.
this._needToSort = false;
}

23.11.2012.

52

ACTIONSCRIPT 3.0

,
. switch
, sortOptions,
, sortProperty.
, .
, _songs
sortOn(), .
, .

Flash Player 9 , Adobe AIR 1.0


PlayList,
Song.
Song:
private var _genres:String;
public function Song(title:String, artist:String, year:uint, filename:String, genres:Array)
{
...
// Genres are passed in as an array
// but stored as a semicolon-separated string.
this._genres = genres.join(";");
}

Song genres, ( )
, Array.
, . , Song
_genres String ,
. Array , ,
join() ";" .
genres
:
public function get genres():Array
{
// Genres are stored as a semicolon-separated String,
// so they need to be transformed into an Array to pass them back out.
return this._genres.split(";");
}
public function set genres(value:Array):void
{
// Genres are passed in as an array,
// but stored as a semicolon-separated string.
this._genres = value.join(";");
}

23.11.2012.

53

ACTIONSCRIPT 3.0

genresset : join()
, . get
: split() _genres,
( , , ";").

23.11.2012.

54

55

4.
Flash Player 9 , Adobe AIR 1.0
, ,
.
. ,
, .
, .

.
,
, , .
(,
),
ActionScript 3.0.


Flash Player 9 , Adobe AIR 1.0
, ActionScript ,
.
ActionScript , ,
, , , .
.
,
, , .
, , ,
, SWF-.
, ,
. ,
if..then..else,
,
.
:
ActionScript, ;
,
.
, .

23.11.2012.

ACTIONSCRIPT 3.0

,
. , .
, ActionScript - -,
. - ,
, , .

.
, .
ActionScript .

: . ,
Flash (, Flash Player Adobe AIR) ,
. ,
, .

: , Flash
. . .
Flash , .
, , .
c ActionScript 3.0 Adobe Flash Platform.

,
.
, (, )
. ( ) .
( ) ,
, . Flash
ActionScript .
Flash, , Flash Player

AIR Debug Launcher (ADL),


. Flash Player Adobe AIR (
) , ActionScript, .
( Adobe Flash CS4 Professional Adobe Flash Builder)
.
, ,
Flash .
Flash
. ,
.
, , ,
.
.
Flash (, ,
ActionScript) .

23.11.2012.

56

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0

, .
.

ActionScript .
,
.

.
SWF- Flash (, Adobe Flash
Player Adobe AIR).
,
. , ,
.

,
, .
Flash.
, .
catch.
, , browse()
, :
var fileRef:FileReference = new FileReference();
try
{
fileRef.upload(new URLRequest("http://www.yourdomain.com/fileupload.cfm"));
}
catch (error:IllegalOperationError)
{
trace(error);
// Error #2037: Functions called in incorrect sequence, or earlier
// call was unsuccessful.
}

, Flash Player ,
browse() , :
.
62.

23.11.2012.

57

ACTIONSCRIPT 3.0

,
. , .
, ,
. ,
. - ,
.
,
. , ,
.
, .
browse() Flash Player .
, , open.
complete.
( , ),
addEventListener(),
:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.OPEN, openHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
fileRef.browse();
function selectHandler(event:Event):void
{
trace("...select...");
var request:URLRequest = new URLRequest("http://www.yourdomain.com/fileupload.cfm");
request.method = URLRequestMethod.POST;
event.target.upload(request);
}
function openHandler(event:Event):void
{
trace("...open...");
}
function completeHandler(event:Event):void
{
trace("...complete...");
}

.
68.

,
, (, catch).
,
catch ,
.
, uncaughtError.
.
UncaughtErrorEvents, SWF LoaderInfo.uncaughtErrorEvents.
uncaughtError ,
, SWF-.

23.11.2012.

58

ACTIONSCRIPT 3.0

uncaughtError, Flash
.
trace .
Error ,
.
Flash . Flash
61.
. uncaughtError,
uncaughtError, .
. .

ActionScript 3.0
Flash Player 9 , Adobe AIR 1.0
,
. ,
,
, . ActionScript 2.0 Error,
.
, ActionScript
3.0 .
. ActionScript 3.0 Flash Platform ,
,
. , ,
, ,
.

ActionScript 3.0
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 , .

Error. ActionScript 3.0 Error, ,


. Error
. (,
MemoryError), (, ArgumentError),
(, URIError) .
. 71.

. Flash Player
, throw. Flash Player 9
Flash ActionScript
.
, .

23.11.2012.

59

ACTIONSCRIPT 3.0

.
Flash ,
.
. .
Flash 61.

.
Flash Player FileReference.upload() false,
upload() , .
upload() ActionScript 3.0,
,
.

. .
, ActionScript 2.0 FileReference name null
( , name ,
null). ActionScript 3.0 name ,
, Flash Player AIR IllegalOperationError,
, ,
try..catch..finally. .
try..catch..finally 62.

.
try..catch..finally
ActionScript.

ErrorEvent
. .
68.


Flash Player 9 , Adobe AIR 1.0
,
. , ,
,
.
.
.

try..catch..finally.
. ,
. .
try..catch..finally 62.

. ,
, Error
. try..catch..finally
. .
67.

23.11.2012.

60

ACTIONSCRIPT 3.0

.
, ,
try..catch..finally.
.
. 68.


Flash
Flash Player 9 , Adobe AIR 1.0
Adobe Flash,
. Flash Player
Adobe Flash Professional Adobe Flash Builder. ,
Adobe AIR, ADL,
Adobe AIR SDK.

Flash Player Adobe AIR. (Error, IOError EOFError),
.
. , :
try
{
tf.text = myByteArray.readBoolean();
}
catch (error:EOFError)
{
tf.text = error.toString();
}

Flash Player readBoolean() EOFError,


tf : EOFError: Error #2030: End of file was encountered. (
).
Flash Player Adobe AIR : EOFError:
Error #2030.
. allComplete;
allComplete.
.
,
. ,
(. c ActionScript 3.0 Adobe Flash Platform).
, Flash Player AIR,
.

23.11.2012.

61

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
.
, .

. try..catch..finally,
(try) , (catch)
Flash (finally) - , .

try..catch..finally
Flash Player 9 , Adobe AIR 1.0

try..catch..finally. , Flash
. , ,
Error. Error catch.
try , .
catch try. try,
catch, try.
finally ,
try . , finally
try. ,
catch, finally.
try..catch..finally:
try
{
// some code that could throw an error
}
catch (err:Error)
{
// code to react to the error
}
finally
{
// Code that runs whether an error was thrown. This code can clean
// up after the error, or take steps to keep the application running.
}

catch , .
catch , Error.
catch . catch,
. , Error
, Error, Error .
:

23.11.2012.

62

ACTIONSCRIPT 3.0

try
{
throw new ArgumentError("I am an ArgumentError");
}
catch (error:Error)
{
trace("<Error> " + error.message);
}
catch (error:ArgumentError)
{
trace("<ArgumentError> " + error.message);
}

:
<Error> I am an ArgumentError

ArgumentError,
, , :
try
{
throw new ArgumentError("I am an ArgumentError");
}
catch (error:ArgumentError)
{
trace("<ArgumentError> " + error.message);
}
catch (error:Error)
{
trace("<Error> " + error.message);
}

API- ActionScript ,
. , close() Sound
IOError, () , :
var mySound:Sound = new Sound();
try
{
mySound.close();
}
catch (error:IOError)
{
// Error #2029: This URLStream object does not have an open stream.
}

c ActionScript 3.0 Adobe Flash Platform, ,


. .

23.11.2012.

63

ACTIONSCRIPT 3.0

throw
Flash Player 9 , Adobe AIR 1.0
Flash ,
. , ,
throw. Adobe
Error . , throw
Error MyErr, myFunction()
:
var MyError:Error = new Error("Encountered an error with the numUsers value", 99);
var numUsers:uint = 0;
try
{
if (numUsers == 0)
{
trace("numUsers equals 0");
}
}
catch (error:uint)
{
throw MyError; // Catch unsigned integer errors.
}
catch (error:int)
{
throw MyError; // Catch integer errors.
}
catch (error:Number)
{
throw MyError; // Catch number errors.
}
catch (error:*)
{
throw MyError; // Catch any other error.
}
finally
{
myFunction(); // Perform any necessary cleanup here.
}

, catch ,
. catch Number ,
catch uint, catch int .
. Java , ,
, throws,
. ActionScript , .

23.11.2012.

64

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0

, - .
.
try..catch
:
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class SimpleError extends Sprite
{
public var employee:XML =
<EmpCode>
<costCenter>1234</costCenter>
<costCenter>1-234</costCenter>
</EmpCode>;
public function SimpleError()
{
try
{
if (employee.costCenter.length() != 1)
{
throw new Error("Error, employee must have exactly one cost center assigned.");
}
}
catch (error:Error)
{
var errorMessage:TextField = new TextField();
errorMessage.autoSize = TextFieldAutoSize.LEFT;
errorMessage.textColor = 0xFF0000;
errorMessage.text = error.message;
addChild(errorMessage);
}
}
}
}

, ActionScript 3.0
ActionScript.
.

23.11.2012.

65

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
, . ,
try..catch, ApplicationError,
catch :
try
{
try
{
trace("<< try >>");
throw new ApplicationError("some error which will be rethrown");
}
catch (error:ApplicationError)
{
trace("<< catch >> " + error);
trace("<< throw >>");
throw error;
}
catch (error:Error)
{
trace("<< Error >> " + error);
}
}
catch (error:ApplicationError)
{
trace("<< catch >> " + error);
}

:
<<
<<
<<
<<

try >>
catch >> ApplicationError: some error which will be rethrown
throw >>
catch >> ApplicationError: some error which will be rethrown

try ApplicationError,
catch. catch ,
, ApplicationError try..catch.

23.11.2012.

66

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
ActionScript ,
.
.

,
.
, ,
, , Flash.
Error try..catch.

,
.
, toString(),
. lookupErrorString(),
,
.
Error ActionScript.
AppError, Error:
public class AppError extends Error
{
public function AppError(message:String, errorID:int)
{
super(message, errorID);
}
}

AppError :
try
{
throw new AppError("Encountered Custom AppError", 29);
}
catch (error:AppError)
{
trace(error.errorID + ": " + error.message)
}

. Error.toString() ,
... (rest). Error.toString()
ECMAScript, ActionScript 3.0,
ActionScript 3.0 . , Error.toString()
.
toString() , .

23.11.2012.

67

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0
. ( .
57).
.
, . ,
XMLSocket : Event.CLOSE, Event.CONNECT
DataEvent.DATA. , XMLSocket
IOErrorEvent.IOError SecurityErrorEvent.SECURITY_ERROR.
. 134.
.

, ErrorEvent
flash.events.ErrorEvent ,
. AsyncErrorEvent, IOErrorEvent
SecurityErrorEvent ErrorEvent.
Flash ,
, .

,
, , netStatus status
. Flash ,
netStatus.info.level status.level ( )
"error". ,
level "error" .


Flash Player 9 , Adobe AIR 1.0
ErrorEvent , ,
Flash, .
try..catch,
, .

, your error-handling code here ( ).

23.11.2012.

68

ACTIONSCRIPT 3.0

package
{
import
import
import
import
import
import
import
import
import

flash.display.Sprite;
flash.errors.IOError;
flash.events.IOErrorEvent;
flash.events.TextEvent;
flash.media.Sound;
flash.media.SoundChannel;
flash.net.URLRequest;
flash.text.TextField;
flash.text.TextFieldAutoSize;

public class LinkEventExample extends Sprite


{
private var myMP3:Sound;
public function LinkEventExample()
{
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);
// your error-handling code here
}
myMP3.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
}
private function linkHandler(linkEvent:TextEvent):void
{
playMP3(linkEvent.text);
// your error-handling code here
}
private function errorHandler(errorEvent:IOErrorEvent):void
{
trace(errorEvent.text);
// your error-handling code here
}
}
}

23.11.2012.

69

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Flash netStatus.info.level status.level
, level . ,
netStatus.info.level, : NetConnection, NetStream SharedObject. ,
status.level, : HTTPStatusEvent, Camera, Microphone LocalConnection.
level .
netStatusHandler() level.
level , : Video stream failed
( ).
package
{
import
import
import
import
import
import

flash.display.Sprite;
flash.events.NetStatusEvent;
flash.events.SecurityErrorEvent;
flash.media.Video;
flash.net.NetConnection;
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
{
if (event.info.level == "error")
{
trace("Video stream failed")
}
else

23.11.2012.

70

ACTIONSCRIPT 3.0

{
connectStream();
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + event);
}
private function connectStream():void
{
var stream:NetStream = new NetStream(connection);
var video:Video = new Video();
video.attachNetStream(stream);
stream.play(videoUrl);
addChild(video);
}
}
}


Flash Player 9 , Adobe AIR 1.0
ActionScript Error.
Error . ActionScript 3.0 :
Error flash.error. flash.error ,
ActionScript 3.0.

Error
Flash Player 9 , Adobe AIR 1.0
Error : Error, ArgumentError, EvalError, RangeError, ReferenceError,
SecurityError, SyntaxError, TypeError, URIError VerifyError.
.

23.11.2012.

71

72

ACTIONSCRIPT 3.0

Error

Error
.
,
ECMAScript: EvalError, RangeError, ReferenceError,
SyntaxError, TypeError URIError.

Error .

.

ArgumentError

ArgumentError ,
, ,
,
, .

EvalError

,
, .

EvalError ,
,
eval().

ActionScript 3.0 eval(),



.

RangeError

RangeError ,

.

, RangeError Timer,
.
RangeError
.

ReferenceError

ReferenceError

()
. ActionScript 3.0

undefined.
ActionScript 3.0 ReferenceError.



. ,

,

ActionScript.

SecurityError

SecurityError ,

.

SyntaxError

Flash Player eval()



, ,
.


, -
.

URL,
.

,
.


, .

SyntaxError , SyntaxError
ActionScript .
.
ActionScript SyntaxError,
RegExp
.

ActionScript SyntaxError,
XMLDocument
XML.

23.11.2012.

73

ACTIONSCRIPT 3.0

TypeError

TypeError ,

.

TypeError
:

URIError

VerifyError

,
.

is instanceof
.

super .

,
- .

. ,
TypeError ,
RegExp ,
.

URIError ,

URI .

URIError
:

VerifyError ,

SWF-.

SWF- SWF-,

VerifyError, .

URI
(API) Flash Player,
URI Socket.connect().

flash.error
Flash Player 9 , Adobe AIR 1.0
flash.error Error, Flash.
flash.error ,
Flash (, Flash Player Adobe AIR).

23.11.2012.

74

ACTIONSCRIPT 3.0

EOFError

EOFError

.

, EOFError ,

IDataInput,
.

IllegalOperationError

IllegalOperationError ,

.
.
, DisplayObjectContainer,
,
. ,

( stage.mask)
Flash
IllegalOperationError : The
Stage class does not implement this property or
method (
).

IOError

IOError
-.

,
.


,
Flash Player
.


Flash Player (
).

,
.

,
/ ,
.

23.11.2012.

75

ACTIONSCRIPT 3.0

MemoryError

MemoryError

.

ActionScript
Virtual Machine 2
ActionScript.

. ,

. ,

,
. , 3
, 32 Microsoft Windows
2
.

ScriptTimeoutError

ScriptTimeoutError ,
15
.
ScriptTimeoutError
.



.



,
,
.
ScriptTimeoutError

.

StackOverflowError

StackOverflowError ,
, ,
.

StackOverflowError
.

: CustomErrors
Flash Player 9 , Adobe AIR 1.0
CustomErrors
. :

XML




www.adobe.com/go/learn_programmingAS3samples_flash_ru. CustomErrors
Samples/CustomError. .

23.11.2012.

76

ACTIONSCRIPT 3.0

File

CustomErrors.mxml

Flash (FLA) Flex (MXML)

CustomErrors.fla
com/example/programmingas3/errors/ApplicationError.as

, FatalError WarningError.

com/example/programmingas3/errors/FatalError.as

, FatalError,
.
ApplicationError.

com/example/programmingas3/errors/Validator.as

, ,
XML.

com/example/programmingas3/errors/WarningError.as

, WarningError,
.
ApplicationError.

CustomErrors
Flash Player 9 , Adobe AIR 1.0
Flex initApp(), Flash Professional
( ). XML,
Validator. :
employeeXML =
<employee id="12345">
<firstName>John</firstName>
<lastName>Doe</lastName>
<costCenter>12345</costCenter>
<costCenter>67890</costCenter>
</employee>;
}

XML TextArea .
XML .
Validate () validateData().
XML ( ) validateEmployeeXML() Validator.
validateData():

23.11.2012.

ACTIONSCRIPT 3.0

function validateData():void
{
try
{
var tempXML:XML = XML(xmlText.text);
Validator.validateEmployeeXML(tempXML);
status.text = "The XML was successfully validated.";
}
catch (error:FatalError)
{
showFatalError(error);
}
catch (error:WarningError)
{
showWarningError(error);
}
catch (error:Error)
{
showGenericError(error);
}
}

XML TextArea
xmlText. validateEmployeeXML() Validator
com.example.programmingas3/errors/Validator.as), XML
. XML , status Label
. validateEmployeeXML()
( FatalError, WarningError Error),
catch , : showFatalError(),
showWarningError() showGenericError().
statusText
. status Label
.
XML ,
statusText , xmlText TextArea
validateBtn Button , :
function showFatalError(error:FatalError):void
{
var message:String = error.message + "\n\n";
var title:String = error.getTitle();
statusText.text = message + " " + title + "\n\nThis application has ended.";
this.xmlText.enabled = false;
this.validateBtn.enabled = false;
hideButtons();
}

, statusText
, TextArea (xmlText) Button
. showWarningError()
statusText. :
XML .
showWarningError():

23.11.2012.

77

ACTIONSCRIPT 3.0

function showWarningError(error:WarningError):void
{
var message:String = error.message + "\n\n" + "Do you want to exit this application?";
showButtons();
var title:String = error.getTitle();
statusText.text = message;
}

closeHandler() .
closeHandler():
function closeHandler(event:CloseEvent):void
{
switch (event.detail)
{
case yesButton:
showFatalError(new FatalError(9999));
break;
case noButton:
statusText.text = "";
hideButtons();
break;
}
}

,
FatalError, .


Flash Player 9 , Adobe AIR 1.0
Validator validateEmployeeXML().
validateEmployeeXML() employee,
XML. validateEmployeeXML() :
public static function validateEmployeeXML(employee:XML):void
{
// checks for the integrity of items in the XML
if (employee.costCenter.length() < 1)
{
throw new FatalError(9000);
}
if (employee.costCenter.length() > 1)
{
throw new WarningError(9001);
}
if (employee.ssn.length() != 1)
{
throw new FatalError(9002);
}
}

23.11.2012.

78

ACTIONSCRIPT 3.0

( ) .
,
FatalError, validateData() .
, WarningError.
XML ,
( ssn XML). ssn ,
FatalError.
validateEmployeeXML() . ,
, ssn
, .
XML ,
.

ApplicationError
Flash Player 9 , Adobe AIR 1.0
ApplicationError FatalError WarningError. ApplicationError
Error. ,
, XML,
. ,
.
ApplicationError :
public function ApplicationError()
{
messages =
<errors>
<error code="9000">
<![CDATA[Employee must be assigned to a cost center.]]>
</error>
<error code="9001">
<![CDATA[Employee must be assigned to only one cost center.]]>
</error>
<error code="9002">
<![CDATA[Employee must have one and only one SSN.]]>
</error>
<error code="9999">
<![CDATA[The application has been stopped.]]>
</error>
</errors>;
}

XML .
E4X,
getMessageText():
public function getMessageText(id:int):String
{
var message:XMLList = messages.error.(@code == id);
return message[0].text();
}

23.11.2012.

79

ACTIONSCRIPT 3.0

getMessageText() id . id
, . , id 9001 ,
,
. , ActionScript
(message[0] XMLList).
, getTitle(),
, .
, XML.
getTitle():
public function getTitle():String
{
return "Error #" + id;
}

ApplicationError toString(). ,
Error, .
, , .
public override function toString():String
{
return "[APPLICATION ERROR #" + id + "] " + message;
}

FatalError
Flash Player 9 , Adobe AIR 1.0
FatalError ApplicationError. :
FatalError, getTitle() toString(). , FatalError,
, errorID,
, ApplicationError, ,
getMessageText() ApplicationError. FatalError
:
public function FatalError(errorID:int)
{
id = errorID;
severity = ApplicationError.FATAL;
message = getMessageText(errorID);
}

FatalError, getTitle(), getTitle(),


ApplicationError, FATAL,
. getTitle() :
public override function getTitle():String
{
return "Error #" + id + " -- FATAL";
}

, toString(), toString(),
ApplicationError. toString() :

23.11.2012.

80

ACTIONSCRIPT 3.0

public override function toString():String


{
return "[FATAL ERROR #" + id + "] " + message;
}

WarningError
Flash Player 9 , Adobe AIR 1.0
WarningError ApplicationError.
FatalError,
ApplicationError.WARNING ApplicationError.FATAL, :
public function WarningError(errorID:int)
{
id = errorID;
severity = ApplicationError.WARNING;
message = super.getMessageText(errorID);
}

23.11.2012.

81

82

5.

Flash Player 9 , Adobe AIR 1.0


,
. , ,
. , ,
, :
/A\d+/

.
.
. ,
- . ActionScript 3.0
, ECMAScript 3
(ECMA-262).


RegExp


Flash Player 9 , Adobe AIR 1.0
.
(, ,
, , )
, .
. , , ,
ABC, ABC .
, ,
A, B C, :
/ABC/

, /.
, ,
, ,
:
/([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}/

23.11.2012.

ACTIONSCRIPT 3.0

.

String. String
: match(), replace(), search() split().
. 17.
RegExp : test() exec(). .
97.

, .
, ,
, .
(\), , ,
, .
, , , ,

.
,

.
( ), .

, ,
.
, ,
.


Flash Player 9 , Adobe AIR 1.0
ActionScript.
, .
. ,
- . ActionScript 3.0
, ECMAScript
3 (ECMA-262).
, ,
. , , A, B
C, :
/ABC\d/

\d . (\)
, ( d),
.
ABC,
( ):

23.11.2012.

83

ACTIONSCRIPT 3.0

/ABC\d*/

(*) . ,
. ,

. . 89.
,
. ,
i, , .
/ABC\d*/i

. 93.
String: match(), replace()
search(). .

17.


Flash Player 9 , Adobe AIR 1.0
.
(/), new.
, :
var pattern1:RegExp = /bob/i;
var pattern2:RegExp = new RegExp("bob", "i");

, .
, , .
, .
, .
new .
, , :
var pattern2:RegExp = new RegExp("bob", "i");

,
, (\)
. , 1/2 :
var pattern:RegExp = /1\/2/;

, new,
\ ( ,
). , eat at "joe's"
:
var pattern1:RegExp = new RegExp("eat at \"joe's\"", "");
var pattern2:RegExp = new RegExp('eat at "joe\'s"', "");

, ,
. , ,
new, .
; 1/2 "joe's":

23.11.2012.

84

ACTIONSCRIPT 3.0

var pattern1:RegExp = /1\/2 "joe's"/;


var pattern2:RegExp = new RegExp("1/2 \"joe's\"", "");
var pattern3:RegExp = new RegExp('1/2 "joe\'s"', '');

, new,
, (\) (, \d,
), :
var pattern:RegExp = new RegExp("\\d+", ""); // matches one or more digits

,
RegExp() .
, .
, , .
. 93.

,
Flash Player 9 , Adobe AIR 1.0
,
, :
var pattern:RegExp = /hello/;

, ,, :
^ $ \ . * + ? ( ) [ ] { } |

, ,
B ( ), , ,
C:
/AB*C/

,
\ . ,
, B, , , ,
C:
var pattern:RegExp = /AB\*C/;

, , .
.
.

, .

23.11.2012.

85

ACTIONSCRIPT 3.0

^ ( )

. m (multiline)
(. 93). ,
, .
. 87.

$ ( )

. m (multiline) $
(\n) . .
93.

\ ( )

.
,
, /1\/2/ (
1, , 2).

. ()

.
(\n), s (dotall).
. 93.

* ()

, .
. 89.

+ ()

, .
. 89.

? ( )

, .
. 89.

()

. .

| : /(a|b|c)d/

: /(walla.){1,2}/

. , \1 ,
:

/(\w*) is repeated: \1/

. 91.
[]

, :
/[aeiou]/ .

(-) :
/[A-Z0-9]/ Z 0 9.

]
- :
/[+\-]\d+/ +, - .

, ,
( ),
:
/[$]/ $, .

. 87.
| ( )

, , :
/abc|xyz/ abc, xyz.

23.11.2012.

86

ACTIONSCRIPT 3.0


,
.
.

{n}

{n,}

/A{27}/ A, 27 .

/A{3,}/ A, 3 .

{n,n}

/A{3,5}/ A, 3 5 .

. 89.
\b

.
,
.

\B

.
.

\d

\D

, .

\f

\n

\r

\s

( , ,
).

\S

, .

\t

\unnnn

, nnnn.
, \u263a .

\v

\w

(AZ, az, 0-9 _). , \w


, , , .

\W

, .

\\xnn

ASCII, nn.


Flash Player 9 , Adobe AIR 1.0

. ( [ ] ). ,
, bag, beg, big, bog bug:
/b[aeiou]g/

23.11.2012.

87

ACTIONSCRIPT 3.0


,
, . ,
, ,
.
:
/[abc*123]/

, , ,
.

(. ).

( ),
. ,
, ($, \, ] -):
/[$\\\]\-]/

, ,
:

\n

\r

\t

\unnnn

(
nnnn).

\\xnn

ASCII ( nn).


.

, A-Z, a-z 0-9.
. ,
a-z :
/[a-z0-9]/

ASCII ASCII \\xnn. ,


ASCII (
):
\\x

23.11.2012.

88

ACTIONSCRIPT 3.0


(^)
.
, (az) :
/[^a-z0-9]/

(^) .
. ,
, :
/[!.,#+*%$&^]/

Flash Player 9 , Adobe AIR 1.0


,
.

* ()

, .

+ ()

, .

? ( )

, .

{n}

{n,}

/A{27}/ , 27 .

/A{3,}/ , 3 .

{n,n}

/A{3,5}/ , 3 5 .

, :

/a+/ a, .

/\d+/ .

/[abc]+/ , a,
b, c.

/(very, )*/ very, ,

.
,
. , , word word-word-word:
/\w+(-\w+)*/

, .
( .*
, . ,
:
var pattern:RegExp = /<p>.*<\/p>/;
str:String = "<p>Paragraph 1</p> <p>Paragraph 2</p>";

23.11.2012.

89

ACTIONSCRIPT 3.0

:
<p>Paragraph 1</p> <p>Paragraph 2</p>

, <p>...</p>.
:
<p>Paragraph 1</p>

(? , ,
. , ,
*? , <p>, ()
, </p>:
/<p>.*?<\/p>/

, .

{0} {0,0} .
, /abc+*/.
(.) , s (dotall),
*. , :
var str:String = "<p>Test\n";
str += "Multiline</p>";
var re:RegExp = /<p>.*<\/p>/;
trace(str.match(re)); // null;
re = /<p>.*<\/p>/s;
trace(str.match(re));
// output: <p>Test
//

Multiline</p>

. 93.

Flash Player 9 , Adobe AIR 1.0


(|) ,
. ,
cat, dog, pig, rat:
var pattern:RegExp = /cat|dog|pig|rat/;


|. cat, nap nip.
var pattern:RegExp = /cat(nap|nip)/;

. 91.
, |,
( [ ]), .
/1|3|5|7|9/
/[13579]/

. 87.

23.11.2012.

90

ACTIONSCRIPT 3.0

Flash Player 9 , Adobe AIR 1.0


:
/class-(\d*)/

. .

.
( |).
( , \1
$1
replace() String).

.

, ,
, :
var pattern:RegExp = /ab*/ ;
// matches the character a followed by
// zero or more occurrences of the character b
pattern = /a\d+/;
// matches the character a followed by
// one or more digits
pattern = /a[123]{1,3}/;
// matches the character a followed by
// one to three occurrences of either 1, 2, or 3


:
var pattern:RegExp = /(ab)*/;
// matches zero or more occurrences of the character a
// followed by the character b, such as ababab
pattern = /(a\d)+/;
// matches one or more occurrences of the character a followed by
// a digit, such as a1a5a8a3
pattern = /(spam ){1,3}/;
// matches 1 to 3 occurrences of the word spam followed by a space

. 89.
(|)
,
|), :

23.11.2012.

91

ACTIONSCRIPT 3.0

var pattern:RegExp = /cat|dog/;


// matches cat or dog
pattern = /ca(t|d)og/;
// matches catog or cadog



. ,
. , \1
, :
var pattern:RegExp = /(\d+)-by-\1/;
// matches the following: 48-by-48

99 , \1, \2, ... , \99.


replace() String $1$99
:
var pattern:RegExp = /Hi, (\w+)\./;
var str:String = "Hi, Bob.";
trace(str.replace(pattern, "$1, hello."));
// output: Bob, hello.

exec() RegExp match() String


, :
var pattern:RegExp = /(\w+)@(\w+).(\w+)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example,com


, ,
. (?: ) ,
:
var pattern = /(?:com|org|net);

, (com|org)
( exec() ):
var pattern:RegExp = /(\w+)@(\w+).(com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example,com
//noncapturing:
var pattern:RegExp = /(\w+)@(\w+).(?:com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@example.com,bob,example

, :
.

23.11.2012.

92

ACTIONSCRIPT 3.0

(?= ) ,
. ,
, . ,
(?=e) , e,
, ,
\w*):
var pattern:RegExp = /sh(?=e)(\w*)/i;
var str:String = "Shelly sells seashells by the seashore";
trace(pattern.exec(str));
// Shelly,elly

(?! ) ,
. :
var pattern:RegExp = /sh(?!e)(\w*)/i;
var str:String = "She sells seashells by the seashore";
trace(pattern.exec(str));
// shore,ore


,
. (?P<name> ) . ,
digits:
var pattern = /[a-z]+(?P<digits>\d+)[a-z]+/;

exec()
result:
var myPattern:RegExp = /([a-z]+)(?P<digits>\d+)[a-z]+/;
var str:String = "a123bcd";
var result:Array = myPattern.exec(str);
trace(result.digits); // 123

, name dom:
var emailPattern:RegExp =
/(?P<name>(\w|[_.\-])+)@(?P<dom>((\w|-)+))+\.\w{2,4}+/;
var address:String = "bob@example.com";
var result:Array = emailPattern.exec(address);
trace(result.name); // bob
trace(result.dom); // example

. ECMAScript.
ActionScript 3.0 .


Flash Player 9 , Adobe AIR 1.0
, .
.

23.11.2012.

93

ACTIONSCRIPT 3.0

global

ignoreCase

. AZ az,
, .

multiline

, $ ^
.

dotall

, . () (\n).

extended

.
, .
.

, .
, (g, i, m, s, x) :
var re:RegExp = /abc/gimsx;

. ,
:
var re:RegExp = /abc/;
re.global = true; // This generates an error.

, ,
false.
, .

lastIndex
exec() test() .

source , , ,
.
g (global)
g (global) , . ,
g , String.match()
:
var str:String = "she sells seashells by the seashore.";
var pattern:RegExp = /sh\w*/;
trace(str.match(pattern)) // output: she

g , Sting.match() , :
var str:String = "she sells seashells by the seashore.";
var pattern:RegExp = /sh\w*/g;
// The same pattern, but this time the g flag IS set.
trace(str.match(pattern)); // output: she,shells,shore

i (ignoreCase)
. i (ignoreCase),
. , s
S , :

23.11.2012.

94

ACTIONSCRIPT 3.0

var str:String = "She sells seashells by the seashore.";


trace(str.search(/sh/)); // output: 13 -- Not the first character

, i, S:
var str:String = "She sells seashells by the seashore.";
trace(str.search(/sh/i)); // output: 0

i AZ az, ,
.
m (multiline)
m (multiline) , ^ , $ .
m , .
, :
var str:String = "Test\n";
str += "Multiline";
trace(str.match(/^\w*/g)); // Match a word at the beginning of the string.

g (global), match()
, ^ ,
. :
Test

m:
var str:String = "Test\n";
str += "Multiline";
trace(str.match(/^\w*/gm)); // Match a word at the beginning of lines.

:
Test,Multiline

, \n .
.

(\r)
(\u2028)
(\u2029)
s (dotall)
s (dotall dot all) , (.)
(\n). :
var str:String = "<p>Test\n";
str += "Multiline</p>";
var re:RegExp = /<p>.*?<\/p>/;
trace(str.match(re));

, s , :
var str:String = "<p>Test\n";
str += "Multiline</p>";
var re:RegExp = /<p>.*?<\/p>/s;
trace(str.match(re));

23.11.2012.

95

96

ACTIONSCRIPT 3.0

<p>, :
<p>Test
Multiline</p>

x (extended)
,
. :
/<p(>|(\s*[^>]*>)).*?<\/p>/gi

x (extended) , ,
. , :
/

<p

(>

(\s*

[^>]*

>))

.*?

<\/p>

/gix

x ,
. , :
/foo bar/
/foo \ bar/x

lastIndex
lastIndex , .
exec() test(), ,
g true. , :
var pattern:RegExp = /p\w*/gi;
var str:String = "Pedro Piper picked a peck of pickled peppers.";
trace(pattern.lastIndex);
var result:Object = pattern.exec(str);
while (result != null)
{
trace(pattern.lastIndex);
result = pattern.exec(str);
}

lastIndex 0 ( ).
, .
:
0
5
11
18
25
36
44

global false, exec() test() lastIndex.


match(), replace() search() String ,
lastIndex , . (
match() lastIndex 0.)
lastIndex ,
.

23.11.2012.

ACTIONSCRIPT 3.0

source
source , , ,
. :
var pattern:RegExp = /foo/gi;
trace(pattern.source); // foo



Flash Player 9 , Adobe AIR 1.0
RegExp : exec() test().
exec() test() RegExp, String ,
: match(), replace(), search() splice().

test()
Flash Player 9 , Adobe AIR 1.0
test() RegExp
, :
var pattern:RegExp = /Class-\w/;
var str = "Class-A";
trace(pattern.test(str)); // output: true

exec()
Flash Player 9 , Adobe AIR 1.0
exec() RegExp
.



index, .
, :
var pattern:RegExp = /\d{3}\-\d{3}-\d{4}/; //U.S phone number
var str:String = "phone: 415-555-1212";
var result:Array = pattern.exec(str);
trace(result.index, " - ", result);
// 7-415-555-1212

g (global), exec()
.

23.11.2012.

97

ACTIONSCRIPT 3.0

var pattern:RegExp = /\w*sh\w*/gi;


var str:String = "She sells seashells by the seashore";
var result:Array = pattern.exec(str);
while (result != null)
{
trace(result.index, "\t", pattern.lastIndex, "\t", result);
result = pattern.exec(str);
}
//output:
// 0 3 She
// 10 19 seashells
// 27 35 seashore

String, RegExp
Flash Player 9 , Adobe AIR 1.0
String : match(),
replace(), search() split(). .
17.

:
Wiki
Flash Player 9 , Adobe AIR 1.0
Wiki .

, Wiki
HTML.

URL <a> HTML.


(
"$9.95") ( "8.24 ").


www.adobe.com/go/learn_programmingAS3samples_flash_ru. WikiEditor
Samples/WikiEditor. .

23.11.2012.

98

99

ACTIONSCRIPT 3.0

File

WikiEditor.mxml

Flash (FLA) Flex


(MXML).

WikiEditor.fla
com/example/programmingas3/regExpExamples/WikiParser.as

, ,

Wiki
HTML.

com/example/programmingas3/regExpExamples/URLParser.as

, ,

URL <a> HTML.

com/example/programmingas3/regExpExamples/CurrencyConverter.as

, ,

.

WikiParser
Flash Player 9 , Adobe AIR 1.0
WikiParser , Wiki
HTML. , ,
,
.
setWikiData()
Wiki :
public function WikiParser()
{
wikiData = setWikiData();
}

,
parseWikiString() WikiParser. , ,
, HTML.
public function parseWikiString(wikiString:String):String
{
var result:String = parseBold(wikiString);
result = parseItalic(result);
result = linesToParagraphs(result);
result = parseBullets(result);
return result;
}

parseBold(), parseItalic(), linesToParagraphs()


parseBullets() replace() ,
, Wiki HTML.

parseBold() Wiki ( , '''foo''')
HTML ( , <b>foo</b>) :

23.11.2012.

ACTIONSCRIPT 3.0

private function parseBold(input:String):String


{
var pattern:RegExp = /'''(.*?)'''/g;
return input.replace(pattern, "<b>$1</b>");
}

, (.?*) (*)
'''. ? ,
, '''aaa''' bbb '''ccc''', '''aaa''',
( ''').
, replace()
$1 . g (global)
replace() ( ).
parseItalic() , parseBold(), ,
( ) (''),
:
private function parseItalic(input:String):String
{
var pattern:RegExp = /''(.*?)''/g;
return input.replace(pattern, "<i>$1</i>");
}


, parseBullet()
Wiki, ( , * foo) HTML ( , <li>foo</li>):
private function parseBullets(input:String):String
{
var pattern:RegExp = /^\*(.*)/gm;
return input.replace(pattern, "<li>$1</li>");
}

^ . m (multiline)
, ^ ,
.
\* (
*).
, replace()
$1 . g (global)
replace() ( ).
Wiki
linesToParagraphs() Wiki <p> HTML.
Wiki:
var pattern:RegExp = /^$/gm;
var result:String = input.replace(pattern, "");

^ $ . (multiline) m
, ^
, .

23.11.2012.

100

ACTIONSCRIPT 3.0

replace() ( ) (""). g (global)


replace() (
).

URL- <a> HTML


Flash Player 9 , Adobe AIR 1.0
urlToATag
URLParser.urlToATag() URL
Wiki <a> HTML.
var
var
var
var
var

protocol:String = "((?:http|ftp)://)";
urlPart:String = "([a-z0-9_-]+\.[a-z0-9_-]+)";
optionalUrlPart:String = "(\.[a-z0-9_-]*)";
urlPattern:RegExp = new RegExp(protocol + urlPart + optionalUrlPart, "ig");
result:String = input.replace(urlPattern, "<a href='$1$2$3'><u>$1$2$3</u></a>");

RegExp()
(urlPattern). ,
.
, protocol, URL-:
http:// , ftp://. , ?.
, ,
|; ($1, $2, $3)
replace().
(
), ($1, $2, $3)
replace().
, urlPart, , ,
: a-z, 0-9, _ -. + . \.
(.) .
: a-z, 0-9, _ -.
, optionalUrlPart, :
(.), - ( _ -). *
.
replace() ,
HTML.
urlToATag() emailToATag(),
<a> HTML . ,
HTTP, FTP, URL- ,
;
URL-.

23.11.2012.

101

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
dollarToEuro
CurrencyConverter.usdToEuro()
(, "$9.95") (, "8.24 ") :
var usdPrice:RegExp = /\$([\d,]+.\d+)+/g;
return input.replace(usdPrice, usdStrToEuroStr);

. ,
$ \ .
replace() ,
usdStrToEuroStr() ( ).
replace(),
.

.
.
.
,
arguments.length - 3 .

, .
.
usdStrToEuroStr()
:
private function usdToEuro(...args):String
{
var usd:String = args[1];
usd = usd.replace(",", "");
var exchangeRate:Number = 0.828017;
var euro:Number = Number(usd) * exchangeRate;
trace(usd, Number(usd), euro);
const euroSymbol:String = String.fromCharCode(8364); //
return euro.toFixed(2) + " " + euroSymbol;
}

, args[1] ,
usdPrice. :
$. (
$).

23.11.2012.

102

103

6. XML
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 , ECMAScript XML (E4X)
(ECMA-357 2). ,
XML-. E4X , XML, .
, .


XML
ECMA-357

XML
Flash Player 9 , Adobe AIR 1.0
XML ,
.
XML : . XML
www.w3.org/XML/.
XML , ,
. XML , HTML.
XML-:
<song>
<title>What you know?</title>
<artist>Steve and the flubberblubs</artist>
<year>1989</year>
<lastplayed>2006-10-17-08:31</lastplayed>
</song>

XML- , ,
. XML-:

23.11.2012.

ACTIONSCRIPT 3.0
XML

<album>
<title>Questions, unanswered</title>
<artist>Steve and the flubberblubs</artist>
<year>1989</year>
<tracks>
<song tracknumber="1" length="4:05">
<title>What do you know?</title>
<artist>Steve and the flubberblubs</artist>
<lastplayed>2006-10-17-08:31</lastplayed>
</song>
<song tracknumber="2" length="3:45">
<title>Who do you know?</title>
<artist>Steve and the flubberblubs</artist>
<lastplayed>2006-10-17-08:35</lastplayed>
</song>
<song tracknumber="3" length="5:14">
<title>When do you know?</title>
<artist>Steve and the flubberblubs</artist>
<lastplayed>2006-10-17-08:39</lastplayed>
</song>
<song tracknumber="4" length="4:19">
<title>Do you know?</title>
<artist>Steve and the flubberblubs</artist>
<lastplayed>2006-10-17-08:44</lastplayed>
</song>
</tracks>
</album>

, XML- XML- (
song ). XML-,
(tracknumber length song) , ( tracks).
XML
XML ,
XML-. XML-
, .
XML- XML-. XML-
(
). XML-
;
, , , ,
.. , XML- :
<song tracknumber="1" length="4:05">
<title>What do you know?</title>
<artist>Steve and the flubberblubs</artist>
<mood>Happy</mood>
<lastplayed>2006-10-17-08:31</lastplayed>
</song>

, (
). , , :
<title>

, , :

23.11.2012.

104

ACTIONSCRIPT 3.0
XML

</title>

, (
). XML :
<lastplayed/>

:
<lastplayed></lastplayed>

, ,
, , .
, XML- length "4:19":
<song length="4:19"></song>

XML- , ,
XML-, ( ).
XML
XML ,
XML, -:

XML W3Schools: http://w3schools.com/xml/


XML , : http://xmlpitstop.com/
ActionScript XML
ActionScript 3.0 , XML
. :

XML: XML-, XML-


.

XMLList: XML-. XMLList


XML- (
XML-). , XMLList
XML- (
XML-).
<artist type="composer">Fred Wilson</artist>
<artist type="conductor">James Schmidt</artist>
<artist type="soloist">Susan Harriet Thurndon</artist>

XML ActionScript
Namespace QName. . XML
119.
XML, ActionScript 3.0 ,
XML- .
XML ECMAScript XML (E4X),
ECMA-357 2.

23.11.2012.

105

ACTIONSCRIPT 3.0
XML


,
XML.
XML-, ,

( ). XML-
.
XML-, .

( , <element/>).
XML-. XML- (

); XML-
, .
XML-.
, ,
attributename="value", , .

E4X XML
Flash Player 9 , Adobe AIR 1.0
ECMAScript XML XML-.
E4X. ActionScript 3.0 E4X:
XML, XMLList, QName Namespace.
, E4X .

, E4X XML-.
E4X
ActionScript.

XML- ,
(.).
. ActionScript 2.0. XML. ActionScript 3.0
XMLDocument, XML ActionScript 3.0, E4X.
ActionScript 3.0 XMLDocument, XMLNode, XMLParser XMLTag
flash.xml . E4X ,
, . XML
ActionScript 2.0 . flash.xml c ActionScript 3.0 Adobe Flash
Platform.
E4X:

23.11.2012.

106

ACTIONSCRIPT 3.0
XML

var myXML:XML =
<order>
<item id='1'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>

XML- , - RSS-.
XML .
, E4X ,
(.), (@) XML:
trace(myXML.item[0].menuName); // Output: burger
trace(myXML.item.(@id==2).menuName); // Output: fries
trace(myXML.item.(menuName=="burger").price); // Output: 3.95

appendChild() XML,
:
var newItem:XML =
<item id="3">
<menuName>medium cola</menuName>
<price>1.25</price>
</item>
myXML.appendChild(newItem);

@ . , ,
:
myXML.item[0].menuName="regular burger";
myXML.item[1].menuName="small fries";
myXML.item[2].menuName="medium cola";
myXML.item.(menuName=="regular burger").@quantity = "2";
myXML.item.(menuName=="small fries").@quantity = "2";
myXML.item.(menuName=="medium cola").@quantity = "2";

for XML, :
var total:Number = 0;
for each (var property:XML in myXML.item)
{
var q:int = Number(property.@quantity);
var p:Number = Number(property.price);
var itemTotal:Number = q * p;
total += itemTotal;
trace(q + " " + property.menuName + " $" + itemTotal.toFixed(2))
}
trace("Total: $", total.toFixed(2));

23.11.2012.

107

ACTIONSCRIPT 3.0
XML

XML
Flash Player 9 , Adobe AIR 1.0
XML , , ,
.
XML: . XML,
, . XML
, : , ,
.
, XML ,
:
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
var x1:XML =
<order>
<!--This is a comment. -->
<?PROC_INSTR sample ?>
<item id='1'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>

, XML,
comments() processingInstructions():
var x2:XML = x1.comments()[0];
var x3:XML = x1.processingInstructions()[0];

XML
Flash Player 9 , Adobe AIR 1.0
XML .

ignoreComments ignoreProcessingInstructions ,
XML .

ignoreWhitespace
, .

prettyIndent

prettyPrinting ,
toString() toXMLString() XML.

. ActionScript 3.0 Flash


Platform.

23.11.2012.

108

ACTIONSCRIPT 3.0
XML

XML
Flash Player 9 , Adobe AIR 1.0
XML:

appendChild()

child()

childIndex()

children()

descendants()

elements()

insertChildAfter()

insertChildBefore()

parent()

prependChild()

XML:

attribute()

attributes()

XML:

hasOwnProperty()

propertyIsEnumerable()

replace()

setChildren()

addNamespace()

inScopeNamespaces()

localName()

name()

namespace()

namespaceDeclarations()

removeNamespace()

setLocalName()

setName()

setNamespace()

XML-
:

comments()

hasComplexContent()

23.11.2012.

109

ACTIONSCRIPT 3.0
XML

hasSimpleContent()

nodeKind()

processingInstructions()

text()

XML:

defaultSettings()

setSettings()

settings()

normalize()

toString()

toXMLString()

contains()

copy()

valueOf()

length()

. c ActionScript 3.0 Adobe Flash


Platform.

XMLList
Flash Player 9 , Adobe AIR 1.0
XMLList XML.
XML-, XML- XML-.
XMLList:

child()

children()

descendants()

elements()

parent()

XMLList:

attribute()

attributes()

XMLList:

hasOwnProperty()

propertyIsEnumerable()

23.11.2012.

110

ACTIONSCRIPT 3.0
XML

XML-
:

comments()

hasComplexContent()

hasSimpleContent()

processingInstructions()

text()

XMLList:

normalize()

toString()

toXMLString()

contains()

copy()

length()

valueOf()

. c ActionScript 3.0 Adobe Flash


Platform.
XMLList, XML-,
XML, XMLList XML- ,
XML. , appendChild() XML,
doc.div XMLList, .
var doc:XML =
<body>
<div>
<p>Hello</p>
</div>
</body>;
doc.div.appendChild(<p>World</p>);

XML . XML 108.

XML
Flash Player 9 , Adobe AIR 1.0
XML XML :

23.11.2012.

111

ACTIONSCRIPT 3.0
XML

var myXML:XML =
<order>
<item id='1'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>

, XML , XML, new:


var str:String = "<order><item id='1'><menuName>burger</menuName>"
+ "<price>3.95</price></item></order>";
var myXML:XML = new XML(str);

XML- (, ),
.
XML ( ),
:
var tagname:String = "item";
var attributename:String = "id";
var attributevalue:String = "5";
var content:String = "Chicken";
var x:XML = <{tagname} {attributename}={attributevalue}>{content}</{tagname}>;
trace(x.toXMLString())
// Output: <item id="5">Chicken</item>

XML- URL-, URLLoader,


:
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
var externalXML:XML;
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("xmlFile.xml");
loader.load(request);
loader.addEventListener(Event.COMPLETE, onComplete);
function onComplete(event:Event):void
{
var loader:URLLoader = event.target as URLLoader;
if (loader != null)
{
externalXML = new XML(loader.data);
trace(externalXML.toXMLString());
}
else
{
trace("loader is not a URLLoader!");
}
}

23.11.2012.

112

ACTIONSCRIPT 3.0
XML

XML- XMLSocket.
. XMLSocket c ActionScript 3.0 Adobe Flash Platform.

XML
Flash Player 9 , Adobe AIR 1.0
prependChild() appendChild()
XML, :
var
var
var
x =
x =
x =

x1:XML = <p>Line 1</p>


x2:XML = <p>Line 2</p>
x:XML = <body></body>
x.appendChild(x1);
x.appendChild(x2);
x.prependChild(<p>Line 0</p>);
// x == <body><p>Line 0</p><p>Line 1</p><p>Line 2</p></body>

insertChildBefore() insertChildAfter()
, :
var x:XML =
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</body>
var newNode:XML = <p>Paragraph 1.5</p>
x = x.insertChildAfter(x.p[0], newNode)
x = x.insertChildBefore(x.p[2], <p>Paragraph 1.75</p>)

, ( )
XML ({ }):
var ids:Array = [121, 122, 123];
var names:Array = [["Murphy","Pat"], ["Thibaut","Jean"], ["Smith","Vijay"]]
var x:XML = new XML("<employeeList></employeeList>");
for (var i:int = 0; i < 3; i++)
{
var newnode:XML = new XML();
newnode =
<employee id={ids[i]}>
<last>{names[i][0]}</last>
<first>{names[i][1]}</first>
</employee>;
x = x.appendChild(newnode)
}

= XML , :

23.11.2012.

113

ACTIONSCRIPT 3.0
XML

var x:XML =
<employee>
<lastname>Smith</lastname>
</employee>
x.firstname = "Jean";
x.@id = "239";

XML x :
<employee id="239">
<lastname>Smith</lastname>
<firstname>Jean</firstname>
</employee>

XMLList + += :
var x1:XML = <a>test1</a>
var x2:XML = <b>test2</b>
var xList:XMLList = x1 + x2;
xList += <c>test3</c>

XMLList xList :
<a>test1</a>
<b>test2</b>
<c>test3</c>

XML-
Flash Player 9 , Adobe AIR 1.0
XML
, . XML ActionScript
(
, XML- ).
XML XMLList XML-.
(.) (..)
XML. XML:

23.11.2012.

114

ACTIONSCRIPT 3.0
XML

var myXML:XML =
<order>
<book ISBN="0942407296">
<title>Baking Extravagant Pastries with Kumquats</title>
<author>
<lastName>Contino</lastName>
<firstName>Chuck</firstName>
</author>
<pageCount>238</pageCount>
</book>
<book ISBN="0865436401">
<title>Emu Care and Breeding</title>
<editor>
<lastName>Case</lastName>
<firstName>Justin</firstName>
</editor>
<pageCount>115</pageCount>
</book>
</order>

myXML.book XMLList, myXML


book. XML, book myXML.
myXML..lastName XMLList,
lastName. XML, lastName myXML.
myXML.book.editor.lastName XMLList,
lastName editor book myXML;
XMLList XML ( lastName "Case").


Flash Player 9 , Adobe AIR 1.0
parent() XML.

. , XML myXML,
book. book
:
myXML.book[0]
myXML.book[1]

,
:
myXML.book[0].title[0]

x.book[0] title
:
myXML.book[0].title

book x ,
title,
:

23.11.2012.

115

ACTIONSCRIPT 3.0
XML

myXML.book.title

child()
, :
var myXML:XML =
<order>
<book>
<title>Dictionary</title>
</book>
</order>;
var childName:String = "book";
trace(myXML.child(childName).title) // output: Dictionary


Flash Player 9 , Adobe AIR 1.0
@ ( ) XML
XMLList, :
var employee:XML =
<employee id="6401" code="233">
<lastName>Wu</lastName>
<firstName>Erin</firstName>
</employee>;
trace(employee.@id); // 6401

* @
XML XMLList, :
var employee:XML =
<employee id="6401" code="233">
<lastName>Wu</lastName>
<firstName>Erin</firstName>
</employee>;
trace(employee.@*.toXMLString());
// 6401
// 233

attribute() attributes()
XML XMLList, :
var employee:XML =
<employee id="6401" code="233">
<lastName>Wu</lastName>
<firstName>Erin</firstName>
</employee>;
trace(employee.attribute("id")); // 6401
trace(employee.attribute("*").toXMLString());
// 6401
// 233
trace(employee.attributes().toXMLString());
// 6401
// 233

23.11.2012.

116

ACTIONSCRIPT 3.0
XML

, ,
:
employee.attribute("id")
employee["@id"]
employee.@["id"]

employee.@id. employee.@id
.


Flash Player 9 , Adobe AIR 1.0
( )
. XML:
var x:XML =
<employeeList>
<employee id="347">
<lastName>Zmed</lastName>
<firstName>Sue</firstName>
<position>Data analyst</position>
</employee>
<employee id="348">
<lastName>McGee</lastName>
<firstName>Chuck</firstName>
<position>Jr. data analyst</position>
</employee>
</employeeList>

x.employee.(lastName == "McGee") employee.

x.employee.(lastName == "McGee").firstName firstName employee.

x.employee.(lastName == "McGee").@id id employee.

x.employee.(@id == 347) employee.

x.employee.(@id == 347).lastName lastName employee.

x.employee.(@id > 300) XMLList employee.

x.employee.(position.toString().search("analyst") > -1) XMLList

position.
,
. , ,
p id:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(@id == '123'));

23.11.2012.

117

ACTIONSCRIPT 3.0
XML

,
p b:
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(b == 'Bob'));

, attribute() elements() ,
, :
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(attribute('id') == '123'));
trace(doc.p.(elements('b') == 'Bob'));

hasOwnProperty(), :
var doc:XML =
<body>
<p id='123'>Hello, <b>Bob</b>.</p>
<p>Hello.</p>
</body>;
trace(doc.p.(hasOwnProperty('@id') && @id == '123'));
trace(doc.p.(hasOwnProperty('b') && b == 'Bob'));

for..in for each..in


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 for..in for each..in,
XMLList. , XML myXML XMLList myXML.item.
XMLList myXML.item item XML.
var myXML:XML =
<order>
<item id='1' quantity='2'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2' quantity='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>;

for..in XMLList:
var total:Number = 0;
for (var pname:String in myXML.item)
{
total += myXML.item.@quantity[pname] * myXML.item.price[pname];
}

23.11.2012.

118

ACTIONSCRIPT 3.0
XML

for each..in XMLList:


var total2:Number = 0;
for each (var prop:XML in myXML.item)
{
total2 += prop.@quantity * prop.price;
}

XML
Flash Player 9 , Adobe AIR 1.0
( ) XML , .
, XML- -,
SOAP, XML :
var message:XML =
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<soap:Body xmlns:w="http://www.test.com/weather/">
<w:getWeatherResponse>
<w:tempurature >78</w:tempurature>
</w:getWeatherResponse>
</soap:Body>
</soap:Envelope>;

soap URI http://schemas.xmlsoap.org/soap/envelope/,


.
ActionScript 3.0 Namespace, XML.
XML Namespace :
var soapNS:Namespace = message.namespace("soap");
trace(soapNS); // Output: http://schemas.xmlsoap.org/soap/envelope/
var wNS:Namespace = new Namespace("w", "http://www.test.com/weather/");
message.addNamespace(wNS);
var encodingStyle:XMLList = message.@soapNS::encodingStyle;
var body:XMLList = message.soapNS::Body;
message.soapNS::Body.wNS::GetWeatherResponse.wNS::tempurature = "78";

XML , :
addNamespace(), inScopeNamespaces(), localName(), name(), namespace(), namespaceDeclarations(),
removeNamespace(), setLocalName(), setName() setNamespace().
default xml namespace XML .
, x1, x2 :
var ns1:Namespace = new Namespace("http://www.example.com/namespaces/");
default xml namespace = ns1;
var x1:XML = <test1 />;
var x2:XML = <test2 />;

23.11.2012.

119

ACTIONSCRIPT 3.0
XML

XML
Flash Player 9 , Adobe AIR 1.0
XML XMLList .
XML XMLList. , ,
XML .
XML.

XML XMLList
Flash Player 9 , Adobe AIR 1.0
XML XMLList toString() toXMLString(). toXMLString()
, , , XML.
XML ( ) toString()
toXMLString(). XML ( )
toString() , :
var myXML:XML =
<order>
<item id='1' quantity='2'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<order>;
trace(myXML.item[0].menuName.toXMLString());
// <menuName>burger</menuName>
trace(myXML.item[0].menuName.toString());
// burger

trace() toString() toXMLString()


toString(), :
var myXML:XML =
<order>
<item id='1' quantity='2'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<order>;
trace(myXML.item[0].menuName);
// burger

trace()
toXMLString(), trace() .

XML
Flash Player 9 , Adobe AIR 1.0
XML new XML() :

23.11.2012.

120

ACTIONSCRIPT 3.0
XML

var x:XML = new XML("<a>test</a>");

XML ,
XML, , :
var x:XML = new XML("<a>test"); // throws an error

Flash Player 9 , Adobe AIR 1.0


, ,
. ,
Number() :
var myXML:XML =
<order>
<item>
<price>3.95</price>
</item>
<item>
<price>1.00</price>
</item>
</order>;
var total:XML = <total>0</total>;
myXML.appendChild(total);
for each (var item:XML in myXML.item)
{
myXML.total.children()[0] = Number(myXML.total.children()[0])
+ Number(item.price.children()[0]);
}
trace(myXML.total); // 4.95;

Number() , +
, trace() :
01.003.95

XML-
Flash Player 9 , Adobe AIR 1.0
XML- URL- URLLoader.
, XML_URL URL-:

23.11.2012.

121

ACTIONSCRIPT 3.0
XML

import flash.events.Event;
import flash.net.URLLoader;
var myXML:XML = new XML();
var XML_URL:String = "http://www.example.com/Sample3.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(event:Event):void
{
myXML = XML(myLoader.data);
trace("Data loaded.");
}

XMLSocket XML
. . c ActionScript 3.0 Adobe Flash Platform.

XML ActionScript: RSS

Flash Player 9 , Adobe AIR 1.0


RSSViewer , XML
ActionScript, .

XML XML- RSS-.


XML XML- HTML
.
RSS XML. RSS-
:

23.11.2012.

122

ACTIONSCRIPT 3.0
XML

<?xml version="1.0" encoding="UTF-8" ?>


<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Alaska - Weather</title>
<link>http://www.nws.noaa.gov/alerts/ak.html</link>
<description>Alaska - Watches, Warnings and Advisories</description>
<item>
<title>
Short Term Forecast - Taiya Inlet, Klondike Highway (Alaska)
</title>
<link>
http://www.nws.noaa.gov/alerts/ak.html#A18.AJKNK.1900
</link>
<description>
Short Term Forecast Issued At: 2005-04-11T19:00:00
Expired At: 2005-04-12T01:00:00 Issuing Weather Forecast Office
Homepage: http://pajk.arh.noaa.gov
</description>
</item>
<item>
<title>
Short Term Forecast - Haines Borough (Alaska)
</title>
<link>
http://www.nws.noaa.gov/alerts/ak.html#AKZ019.AJKNOWAJK.190000
</link>
<description>
Short Term Forecast Issued At: 2005-04-11T19:00:00
Expired At: 2005-04-12T01:00:00 Issuing Weather Forecast Office
Homepage: http://pajk.arh.noaa.gov
</description>
</item>
</channel>
</rss>

SimpleRSS RSS- , ,
(), , . SimpleRSSUI
SimpleRSS, XML.

www.adobe.com/go/learn_programmingAS3samples_flash_ru.
RSSViewer Samples/RSSViewer. .

23.11.2012.

123

124

ACTIONSCRIPT 3.0
XML

File

RSSViewer.mxml

Flash (FLA) Flex (MXML).

RSSViewer.fla
com/example/programmingas3/rssViewer/RSSParser.as

, , E4X RSS
(XML)- HTML.

RSSData/ak.rss

RSS-.
RSS- RSS- Flex,
Adobe.
RSS- ,
, RSS- Flex.

XML-
Flash Player 9 , Adobe AIR 1.0
RSSParser xmlLoaded(), RSS-,
rssXML, rssOutput, HTML.
RSS- ,
XML .
if (rssXML.namespace("") != undefined)
{
default xml namespace = rssXML.namespace("");
}

XML-,
item:
for each (var item:XML in rssXML..item)
{
var itemTitle:String = item.title.toString();
var itemDescription:String = item.description.toString();
var itemLink:String = item.link.toString();
outXML += buildItemHTML(itemTitle,
itemDescription,
itemLink);
}

,
item XML-. buildItemHTML()
HTML- XMLList ,
.

XMLList
Flash Player 9 , Adobe AIR 1.0
HTML- ( XMLList) :

23.11.2012.

ACTIONSCRIPT 3.0
XML

<b>itemTitle</b>
<p>
itemDescription
<br />
<a href="link">
<font color="#008000">More...</font>
</a>
</p>

xml :
default xml namespace = new Namespace();

default xml namespace . ,


buildItemHTML().
, XMLList, :
var body:XMLList = new XMLList();
body += new XML("<b>" + itemTitle + "</b>");
var p:XML = new XML("<p>" + itemDescription + "</p>");
var link:XML = <a></a>;
link.@href = itemLink; // <link href="itemLinkString"></link>
link.font.@color = "#008000";
// <font color="#008000"></font></a>
// 0x008000 = green
link.font = "More...";
p.appendChild(<br/>);
p.appendChild(link);
body += p;

XMLList , HTML ActionScript.


xmlLoaded() buildItemHTML() :
XML.prettyPrinting = false;
rssOutput = outXML.toXMLString();

RSS-
Flash Player 9 , Adobe AIR 1.0
xmlLoaded() rssTitle XML- RSS-.
rssTitle = rssXML.channel.title.toString();

, , xmlLoaded() , ,
:
dataWritten = new Event("dataWritten", true);

23.11.2012.

125

126

7.
JSON
ActionScript 3.0 API-
ActionScript JSON (JavaScript Object Notation). JSON
5- ECMA-262,
.
(Todd Anderson) API JSON as3corelib JSON. . Working with Native JSON in Flash
Player 11 ( API- JSON Flash Player 11).


JSON

API- JSON
API- ActionScript JSON JSON toJSON() .
, JSON - ,
ActionScript .
JSON ActionScript,
toJSON(). JSON
. , JSON
. toJSON(), JSON
.
JSON , stringify(), , parse().
,
JSON. stringify() replacer; parse() reviver.
, :
function(k, v):*

toJSON()
toJSON()
public function toJSON(k:String):*
JSON.stringify() toJSON(), , ,
. /. stringify()
toJSON(), , k, .
toJSON()
.

23.11.2012.

127

ACTIONSCRIPT 3.0
JSON

toJSON() ( *), .
toJSON() , . ,
,
toJSON() , . JSON
. .

toJSON() , , stringify() .
toJSON() , stringify() ,
, .
JSON,
. JSON.
JSON .
toJSON() Object, .
, JSON .
toJSON() .
, ActionScript
. ActionScript
, .
, toJSON():

ByteArray
Date
Dictionary
XML
ByteArray , toJSON().
. Date XML, ,
toJSON(). Dictionary
, toJSON().

JSON
JSON ,
:

toJSON()

toJSON()
toJSON
JSON.stringify()

replacer JSON.parser() reviver


ECMA-262, 5-

23.11.2012.

ACTIONSCRIPT 3.0
JSON

toJSON()
JSON ActionScript ECMAScript JSON (. 5- ECMA262). ECMAScript , ActionScript JSON
. ActionScript 3.0,
, .
ActionScript toJSON() .
, . toJSON()
, ,
. , toJSON()
MovieClip:
MovieClip.prototype.toJSON = function(k):* {
trace("prototype.toJSON() called.");
return "toJSON";
}

stringify() MovieClip, stringify()


toJSON():
var mc:MovieClip = new MovieClip();
var js:String = JSON.stringify(mc); //"prototype toJSON() called."
trace("js: " + js); //"js: toJSON"

toJSON() . ,
Date.toJSON():
Date.prototype.toJSON = function (k):* {
return "any date format you like via toJSON: "+
"this.time:"+this.time + " this.hours:"+this.hours;
}
var dt:Date = new Date();
trace(JSON.stringify(dt));
// "any date format you like via toJSON: this.time:1317244361947 this.hours:14"

toJSON()
toJSON().
toJSON() , .
, ByteArray toJSON().

23.11.2012.

128

ACTIONSCRIPT 3.0
JSON

package {
import flash.utils.ByteArray;
public class MyByteArray extends ByteArray
{
public function MyByteArray() {
}
public function toJSON(s:String):*
{
return "MyByteArray";
}
}
}

var ba:ByteArray = new ByteArray();


trace(JSON.stringify(ba)); //"ByteArray"
var mba:MyByteArray = new MyByteArray(); //"MyByteArray"
trace(JSON.stringify(mba)); //"MyByteArray"

, toJSON
:
var d:Dictionary = new Dictionary();
trace(JSON.stringify((d))); // "Dictionary"
d.toJSON = function(){return {c : "toJSON override."};} // overrides existing function
trace(JSON.stringify((d))); // {"c":"toJSON override."}

toJSON() ActionScript.
ActionScript toJSON(). Object toJSON
.
. , toJSON()
.
, toJSON(), JSON
JSON. .
toJSON(), JSON .

replacer JSON.stringify()
toJSON() JSON
.
. ,
replacer JSON.stringify().
stringify() , replacer .
toJSON():
function (k,v):*

23.11.2012.

129

ACTIONSCRIPT 3.0
JSON

toJSON(), replacer , v, , k. ,
stringify() JSON, .
JSON.stringify() replacer(k,v), .
this, replacer, , .
JSON.stringify() ,
, . this[k]
. v ,
toJSON().
toJSON(), replacer . replacer
, JSON ,
. , stringify()
JSON, JSON.parse().
replacer this time
hours Date.
JSON.stringify(d, function (k,v):* {
return "any date format you like via replacer: "+
"holder[k].time:"+this[k].time + " holder[k].hours:"+this[k].hours;
});

reviver JSON.parse()
reviver JSON.parse() , replacer:
JSON ActionScript. reviver
, :
function (k,v):*

k , v reviver k. stringify(), parse() JSON reviver, .


, JSON ActionScript .
, .
. toJSON(), replacer reviver
ActionScript,
.


,
JSON. : JSONGenericDictExample JSONDictionaryExtnExample.
JSONGenericDictExample .
, .
JSONGenericDictExample
.
JSONGenericDictExample revive(),
id. revive()
.

23.11.2012.

130

ACTIONSCRIPT 3.0
JSON

JSONDictionaryExtnExample ActionScript Dictionary.


. , ,
JSONDictionaryExtnExample.
JSONDictionaryExtnExample JSONGenericDictExample .
JSONDictionaryExtnExample , JSONGenericDictExample.revive()
, JSONDictionaryExtnExample .
, JSONDictionaryExtnExample
JSONDictionaryExtnExample.toJSON() . JSON
JSONDictionaryExtnExample. ,
JSON.parse().
package {
// Generic dictionary example:
public class JSONGenericDictExample {
static var revivableObjects = [];
static var nextId = 10000;
public var id;
public var dname:String;
public var birthday;
public function JSONGenericDictExample(name, birthday) {
revivableObjects[nextId] = this;
this.id
= "id_class_JSONGenericDictExample_" + nextId;
this.dname
= name;
this.birthday = birthday;
nextId++;
}
public function toString():String { return this.dname; }
public static function revive(id:String):JSONGenericDictExample {
var r:RegExp = /^id_class_JSONGenericDictExample_([0-9]*)$/;
var res = r.exec(id);
return JSONGenericDictExample.revivableObjects[res[1]];
}
}
}
package {
import flash.utils.Dictionary;
import flash.utils.ByteArray;
// For this extension of dictionary, we serialize the contents of the
// dictionary by using toJSON
public final class JSONDictionaryExtnExample extends Dictionary {
public function toJSON(k):* {
var contents = {};
for (var a in this) {
contents[a.id] = this[a];
}
// We also wrap the contents in an object so that we can
// identify it by looking for the marking property "class E"
// while in the midst of JSON.parse.

23.11.2012.

131

ACTIONSCRIPT 3.0
JSON

return {"class JSONDictionaryExtnExample": contents};


}
// This is just here for debugging and for illustration
public function toString():String {
var retval = "[JSONDictionaryExtnExample <";
var printed_any = false;
for (var k in this) {
retval += k.toString() + "=" +
"[e="+this[k].earnings +
",v="+this[k].violations + "], "
printed_any = true;
}
if (printed_any)
retval = retval.substring(0, retval.length-2);
retval += ">]"
return retval;
}
}
}

JSON.parse() JSONDictionaryExtnExample,
reviver JSONGenericDictExample.revive()
JSONDictionaryExtnExample. , .
JSONGenericDictExample.revive()
JSONDictionaryExtnExample .
import flash.display.MovieClip;
import flash.text.TextField;
var a_bob1:JSONGenericDictExample = new JSONGenericDictExample("Bob", new
Date(Date.parse("01/02/1934")));
var a_bob2:JSONGenericDictExample = new JSONGenericDictExample("Bob", new
Date(Date.parse("05/06/1978")));
var a_jen:JSONGenericDictExample = new JSONGenericDictExample("Jen", new
Date(Date.parse("09/09/1999")));
var e = new
e[a_bob1] =
e[a_bob2] =
e[a_jen] =

JSONDictionaryExtnExample();
{earnings: 40, violations: 2};
{earnings: 10, violations: 1};
{earnings: 25, violations: 3};

trace("JSON.stringify(e): " + JSON.stringify(e)); // {"class JSONDictionaryExtnExample":


//{"id_class_JSONGenericDictExample_10001":
//{"earnings":10,"violations":1},
//"id_class_JSONGenericDictExample_10002":
//{"earnings":25,"violations":3},
//"id_class_JSONGenericDictExample_10000":
// {"earnings":40,"violations":2}}}
var e_result = JSON.stringify(e);
var e1 = new JSONDictionaryExtnExample();
var e2 = new JSONDictionaryExtnExample();
// It's somewhat easy to convert the string from JSON.stringify(e) back
// into a dictionary (turn it into an object via JSON.parse, then loop

23.11.2012.

132

ACTIONSCRIPT 3.0
JSON

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

over that object's properties to construct a fresh dictionary).


The harder exercise is to handle situations where the dictionaries
themselves are nested in the object passed to JSON.stringify and
thus does not occur at the topmost level of the resulting string.
(For example: consider roundtripping something like
var tricky_array = [e1, [[4, e2, 6]], {table:e3}]
where e1, e2, e3 are all dictionaries. Furthermore, consider
dictionaries that contain references to dictionaries.)
This parsing (or at least some instances of it) can be done via
JSON.parse, but it's not necessarily trivial. Careful consideration
of how toJSON, replacer, and reviver can work together is
necessary.

var e_roundtrip =
JSON.parse(e_result,
// This is a reviver that is focused on rebuilding JSONDictionaryExtnExample objects.
function (k, v) {
if ("class JSONDictionaryExtnExample" in v) { // special marker tag;
//see JSONDictionaryExtnExample.toJSON().
var e = new JSONDictionaryExtnExample();
var contents = v["class JSONDictionaryExtnExample"];
for (var i in contents) {
// Reviving JSONGenericDictExample objects from string
// identifiers is also special;
// see JSONGenericDictExample constructor and
// JSONGenericDictExample's revive() method.
e[JSONGenericDictExample.revive(i)] = contents[i];
}
return e;
} else {
return v;
}
});
trace("// == Here is an extended Dictionary that has been round-tripped ==");
trace("// == Note that we have revived Jen/Jan during the roundtrip.
==");
trace("e:
" + e); //[JSONDictionaryExtnExample <Bob=[e=40,v=2], Bob=[e=10,v=1],
//Jen=[e=25,v=3]>]
trace("e_roundtrip: " + e_roundtrip); //[JSONDictionaryExtnExample <Bob=[e=40,v=2],
//Bob=[e=10,v=1], Jen=[e=25,v=3]>]
trace("Is e_roundtrip a JSONDictionaryExtnExample? " + (e_roundtrip is
JSONDictionaryExtnExample)); //true
trace("Name change: Jen is now Jan");
a_jen.dname = "Jan"
trace("e:

" + e); //[JSONDictionaryExtnExample <Bob=[e=40,v=2], Bob=[e=10,v=1],


//Jan=[e=25,v=3]>]
trace("e_roundtrip: " + e_roundtrip); //[JSONDictionaryExtnExample <Bob=[e=40,v=2],
//Bob=[e=10,v=1], Jan=[e=25,v=3]>]

23.11.2012.

133

134

8.
Flash Player 9 , Adobe AIR 1.0

. ActionScript 3.0 ,
, .
(DOM) (
),
ActionScript.
ActionScript 3.0 .
,
162.


flash.events
(DOM), 3,


Flash Player 9 , Adobe AIR 1.0
SWF-,
. , SWF-
( ,
, ).
SWF- .
(, ).
ActionScript 3.0 ,
Event . ,
, . , Flash Player
AIR , ( MouseEvent),
.
Flash Player AIR . ,
, . ,
, . ,
, Flash Player ,
, .
, ,
.
. .

23.11.2012.

ACTIONSCRIPT 3.0

.
,
. ,
,
.
(,
, ,
):
function eventResponse(eventObject:EventType):void
{
// Actions performed in response to the event go here.
}
eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse);

. -, . ,
. -, addEventListener()
, . ,
, .
, ,
. , .
, 4 .
, (
, eventResponse). -,
, ,
(EventType ). ,
(EVENT_NAME ). -, addEventListener(),
, (eventTarget ). ,
(eventObject ).

, :
,

, .
,

. .
,
. .
,

. ,
, .
, , .
( - ).
, .
, .

23.11.2012.

135

ACTIONSCRIPT 3.0

( ) ,

, ,
. ,
, , ,
. .
Event , ,
.
, . ,
Sprite, ,
, , (
).
, ,

.
, .

ActionScript 3.0

Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0
, ActionScript 3.0 ,
ActionScript .
ActionScript,
ActionScript 3.0.

ActionScript
Flash Player 9 , Adobe AIR 1.0
ActionScript, ActionScript 3.0,
:

on(), Button
MovieClip;

onClipEvent(), MovieClip;
(, XML.onload Camera.onActivity);
, addListener();
UIEventDispatcher, DOM.

23.11.2012.

136

ACTIONSCRIPT 3.0

. on()
onClipEvent() , , ,
, .
,
. :
, ,
.
.
ActionScript 2.0 .
, UIEventDispatcher, DOM.
, ,
ActionScript 3.0.
, , ,
. , ActionScript 2.0 (, TextField.onChanged)
.
,
, , UIEventDispatcher. Key, Mouse,
MovieClipLoader, Selection, Stage TextField addListener(),
addEventListener().
, , ,

. , this
.

ActionScript 3.0
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 ,
, .
(DOM) .
SWF- ,
DOM,
DOM. DOM,
.
DOM, Flash Player AIR,
. , Flash Player
AIR .

, , .
, Flash Player AIR ,
. Flash Player AIR
, .

23.11.2012.

137

ACTIONSCRIPT 3.0

, TextField, ,
TextField, Flash Player AIR. ,
, .
TextField, Flash Player AIR TextEvent,
. TextField,
TextEvent preventDefault().
, . , Flash Player AIR
MouseEvent, TextField. ,
, .
. , Flash Player
,
. API- Event
, ,
.
, ,
Flash Player AIR, ,
ActionScript. ,
EventDispatcher textInput,
. , Flash Player AIR
TextField textInput, .
ActionScript 3.0
, addListener() ActionScript 2.0,
ActionScript 2.0
ActionScript 3.0. :

ActionScript 2.0,
addListener() addEventListener() . ActionScript 3.0
addEventListener().

ActionScript 2.0 . , addListener()


, . ActionScript 3.0
addEventListener() , .

ActionScript 2.0 , ,
ActionScript 3.0 .


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR .
, Flash Player AIR .
, Flash Player URLStream.
, Flash Player
, .

23.11.2012.

138

ACTIONSCRIPT 3.0

.
, .
, ,
. flash.display.Stage.
. stage,
.
Flash Player AIR , ,
. DOM
, . ,
, . ,
child1, Flash Player AIR ,
child1.
. ;
.
, .
. ,
.
, ,
, :
Stage

Parent Node

Child1 Node

Child2 Node

Child1 Node, Flash Player AIR .


, Stage,
Parent Node, Child1 , ,
Stage, Parent Node
Stage.
Stage

arent Node

Child1 Node

Child2 Node

23.11.2012.

139

ACTIONSCRIPT 3.0

Stage Parent Node


. ,
Child1. Parent Node
Stage, .
, ,
ActionScript. ActionScript .
, , .
ActionScript 3.0 ,
.
,
. ,
, .
, ,
, ,
.
, , ,
, .
.
(, enterFrame init)
, . ,
(, , Socket).
,
.
, , API,
. .

Event
Flash Player 9 , Adobe AIR 1.0
. -,
,
. -, ,
.
, Flash Player API Event,
. Event
, .
Event,
Event, , Event.

23.11.2012.

140

ACTIONSCRIPT 3.0

Event
Flash Player 9 , Adobe AIR 1.0
Event ,
. :

Event Event.type.
, ,
Event.cancelable.

.
Event
.
Event.type . ,
. , , clickHandler()
, myDisplayObject:
myDisplayObject.addEventListener(MouseEvent.CLICK, clickHandler);

Event 24 , Event.
Event:
package flash.events
{
public class Event
{
// class constants
public static const ACTIVATE:String = "activate";
public static const ADDED:String= "added";
// remaining constants omitted for brevity
}
}

.
, .
, , , ,
. ,
. ,
:
myDisplayObject.addEventListener(MouseEvent.CLICK, clickHandler);


myDisplayObject.addEventListener("click", clickHandler);


,
cancelable. cancelable ,
, . ,
, preventDefault().
. Event
143.

23.11.2012.

141

ACTIONSCRIPT 3.0


Event
, :

bubbles ,
.

eventPhase .
target .
currentTarget ,
.
bubbles
, ,
. ,
, . Event.bubbles
,
. ,
.
true, . false,
.
eventPhase
eventPhase.
eventPhase , .
Flash Player API EventPhase, ,
, :
package flash.events
{
public final class EventPhase
{
public static const CAPTURING_PHASE:uint = 1;
public static const AT_TARGET:uint = 2;
public static const BUBBLING_PHASE:uint= 3;
}
}

eventPhase.
, . , ,
myFunc() ,
, :
if (event.eventPhase == EventPhase.AT_TARGET)
{
myFunc();
}

23.11.2012.

142

ACTIONSCRIPT 3.0


target , .
(, Microphone).
, . ,
,
, Flash Player AIR ,
.
SWF-, , ,
, target ,
.
currentTarget,
, target .
currentTarget
currentTarget ,
. ,
, ,
, . ,
. ,
, currentTarget .

Event
Flash Player 9 , Adobe AIR 1.0
Event :

: .
, .
: , .
Event
Event . clone() .
toString() .
,
.
, Event,
, .

,
Event.stopPropagation() Event.stopImmediatePropagation().
,
:

Event.stopPropagation() .
,
.

23.11.2012.

143

ACTIONSCRIPT 3.0

Event.stopImmediatePropagation()
, .
, .
, Event,
.

: preventDefault() isDefaultPrevented().
preventDefault() , . ,
preventDefault() , isDefaultPrevented(),
true, , false .
preventDefault() , .
API
ActionScript cancelable .
.
Event .

Event
Flash Player 9 , Adobe AIR 1.0
, Event.
, ,
Event. ActionScript 3.0 ,
Event.
,
. , , ,
, , Event. MouseEvent
Event. , ,
.
Event , , .
, MouseEvent , click,
doubleClick, mouseDown mouseUp.
Event 140 Event,
Event clone() toString(),
.

23.11.2012.

144

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, ,
Flash Player AIR .
. -, Flash Player AIR,
.
. -, addEventListener(),
,
.


Flash Player 9 , Adobe AIR 1.0
, ActionScript 3.0
DOM. DOM
. ,
EventListener,
handleEvent(). DOM ,
, .
ActionScript 3.0 .
ActionScript 3.0 EventListener,
. , handleEvent():
. ActionScript 3.0
.

SWF-, .
clickHandler(), - ,
.

23.11.2012.

145

ACTIONSCRIPT 3.0

package
{
import flash.display.Sprite;
public class ClickExample extends Sprite
{
public function ClickExample()
{
var child:ChildSprite = new ChildSprite();
addChild(child);
}
}
}
import flash.display.Sprite;
import flash.events.MouseEvent;
class ChildSprite extends Sprite
{
public function ChildSprite()
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0,0,100,100);
graphics.endFill();
addEventListener(MouseEvent.CLICK, clickHandler);
}
}
function clickHandler(event:MouseEvent):void
{
trace("clickHandler detected an event of type: " + event.type);
trace("the this keyword refers to: " + this);
}

SWF-, , Flash Player AIR


:
clickHandler detected an event of type: click
the this keyword refers to: [object global]

, clickHandler().
. type , ,
.
this. this
. , .
,
, ClickExample,
, clickHandler() ChildSprite:

23.11.2012.

146

ACTIONSCRIPT 3.0

package
{
import flash.display.Sprite;
public class ClickExample extends Sprite
{
public function ClickExample()
{
var child:ChildSprite = new ChildSprite();
addChild(child);
}
}
}
import flash.display.Sprite;
import flash.events.MouseEvent;
class ChildSprite extends Sprite
{
public function ChildSprite()
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0,0,100,100);
graphics.endFill();
addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:MouseEvent):void
{
trace("clickHandler detected an event of type: " + event.type);
trace("the this keyword refers to: " + this);
}
}

c SWF- , Flash Player


AIR :
clickHandler detected an event of type: click
the this keyword refers to: [object ChildSprite]

, this ChildSprite child.


ActionScript 2.0. ActionScript 2.0, ,
UIEventDispatcher.addEventListener(),
, ,
. ,
ActionScript 2.0, this ,
, ChildSprite.
, ,
, .
ActionScript 2.0 mx.util.Delegate,
. , ActionScript 3.0
addEventListener(). this
ChildSprite child, ChildSprite.

23.11.2012.

147

ACTIONSCRIPT 3.0

,
, ,
, .
ActionScript 2.0. ,
ActionScript 3.0. , this
.
ClickExample ,
myListenerObj:
package
{
import flash.display.Sprite;
public class ClickExample extends Sprite
{
public function ClickExample()
{
var child:ChildSprite = new ChildSprite();
addChild(child);
}
}
}
import flash.display.Sprite;
import flash.events.MouseEvent;
class ChildSprite extends Sprite
{
public function ChildSprite()
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0,0,100,100);
graphics.endFill();
addEventListener(MouseEvent.CLICK, myListenerObj.clickHandler);
}
}
var myListenerObj:Object = new Object();
myListenerObj.clickHandler = function (event:MouseEvent):void
{
trace("clickHandler detected an event of type: " + event.type);
trace("the this keyword refers to: " + this);
}

:
clickHandler detected an event of type: click
the this keyword refers to: [object global]

, this myListenerObj
[object Object], .
addEventListener() Flash Player AIR
. , listener
, . Flash Player AIR
myListenerObj.

23.11.2012.

148

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
IEventDispatcher.
IEventDispatcher EventTarget DOM ActionScript 3.0.
, IEventDispatcher ( ) ,
,
. IEventDispatcher
, :
package flash.events
{
public interface IEventDispatcher
{
function addEventListener(eventName:String,
listener:Object,
useCapture:Boolean=false,
priority:Integer=0,
useWeakReference:Boolean=false):Boolean;
function removeEventListener(eventName:String,
listener:Object,
useCapture:Boolean=false):Boolean;
function dispatchEvent(eventObject:Event):Boolean;
function hasEventListener(eventName:String):Boolean;
function willTrigger(eventName:String):Boolean;
}
}

Flash Player API IEventDispatcher EventDispatcher,


, .
, , DisplayObject EventDispatcher. ,
IEventDispatcher.

addEventListener() IEventDispatcher.
.
type listener. type . listener
, . listener
, .
listener . , clickHandler()
addEventListener():
addEventListener(MouseEvent.CLICK, clickHandler)

23.11.2012.

149

ACTIONSCRIPT 3.0

useCapture addEventListener() ,
. useCapture true,
. useCapture
false,
. ,
addEventListener(). useCapture true,
useCapture false.
priority addEventListener() DOM
3. ActionScript 3.0
. addEventListener()
, priority.
0, . ,
.
. ,
.
useWeakReference ,
. true ,
, . Flash Player AIR
, , .
, . .
, , ,
.

removeEventListener()
. .
eventName listener addEventListener(). ,
, addEventListener().
useCapture true, false.
, removeEventListener().
useCapture true,
, false.

dispatchEvent()
. , ,
, Event .
target ,
dispatchEvent().

IEventDispatcher
. hasEventListener() true,
.
willTrigger() true,
. willTrigger()
, .

23.11.2012.

150

ACTIONSCRIPT 3.0

Error
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 ,
(, ).
, Flash Player AIR .
, Flash Player AIR
. , Flash Player
,
URL-:

ErrorEvent text,
, Flash Player AIR. StatusEvent NetStatusEvent
. level (StatusEvent.level
NetStatusEvent.info.level). level "error",
.
SWF-.
-
,
Adobe Flash Builder. Flash Player AIR .

:
Flash Player 9 , Adobe AIR 1.0
,
, , .
SimpleClock 1.
ActionScript 3.0, :

;
;
.

23.11.2012.

151

152

ACTIONSCRIPT 3.0

Flash Professional
www.adobe.com/go/learn_programmingAS3samples_flash_ru. Flex
http://www.adobe.com/go/as3examples_ru.
Samples/AlarmClock. :
File

AlarmClockApp.mxml

Flash (FLA) Flex (MXML).

AlarmClockApp.fla
com/example/programmingas3/clock/AlarmClock.as

, SimpleClock,
.

com/example/programmingas3/clock/AlarmEvent.as

( flash.events.Event),
alarm AlarmClock.

com/example/programmingas3/clock/AnalogClockFace.as

, ,
(.
SimpleClock).

com/example/programmingas3/clock/SimpleClock.as


(.
SimpleClock).


Flash Player 9 , Adobe AIR 1.0
,
, SimpleClock,
: 6. AlarmClock
SimpleClock . ,
, .
, . AlarmClock
Alarm, , .
, AlarmClock Timer,
. AlarmClock, Timer (
AlarmClock) .
ActionScript,
.


Flash Player 9 , Adobe AIR 1.0
, , AlarmClock,
. Timer (flash.utils.Timer)
, .
AlarmClock Timer, .

23.11.2012.

ACTIONSCRIPT 3.0

import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* The Timer that will be used for the alarm.
*/
public var alarmTimer:Timer;
...
/**
* Instantiates a new AlarmClock of a given size.
*/
public override function initClock(faceSize:Number = 200):void
{
super.initClock(faceSize);
alarmTimer = new Timer(0, 1);
alarmTimer.addEventListener(TimerEvent.TIMER, onAlarm);
}

Timer, AlarmClock, alarmTimer. initClock(),


AlarmClock,
alarmTimer. -, ,
Timer 0 timer .
alarmTimer addEventListener() , ,
timer. Timer timer
. AlarmClock
timer, . addEventListener() AlarmClock
alarmTimer. , AlarmClock
timer ( TimerEvent.TIMER)
, onAlarm() AlarmClock .
, setAlarm() AlarmClock :

23.11.2012.

153

ACTIONSCRIPT 3.0

/**
* Sets the time at which the alarm should go off.
* @param hour The hour portion of the alarm time.
* @param minutes The minutes portion of the alarm time.
* @param message The message to display when the alarm goes off.
* @return The time at which the alarm will go off.
*/
public function setAlarm(hour:Number = 0, minutes:Number = 0, message:String = "Alarm!"):Date
{
this.alarmMessage = message;
var now:Date = new Date();
// Create this time on today's date.
alarmTime = new Date(now.fullYear, now.month, now.date, hour, minutes);
// Determine if the specified time has already passed today.
if (alarmTime <= now)
{
alarmTime.setTime(alarmTime.time + MILLISECONDS_PER_DAY);
}
// Stop the alarm timer if it's currently set.
alarmTimer.reset();
// Calculate how many milliseconds should pass before the alarm should
// go off (the difference between the alarm time and now) and set that
// value as the delay for the alarm timer.
alarmTimer.delay = Math.max(1000, alarmTime.time - now.time);
alarmTimer.start();
return alarmTime;
}

, Date
(alarmTime), .
,
alarmTimer. -, reset(), ,
. ( now)
alarmTime, , ,
. Timer timer , delay
alarmTimer .
start(), .
, , alarmTimer timer.
AlarmClock onAlarm() ,
timer, onAlarm().
/**
* Called when the timer event is dispatched.
*/
public function onAlarm(event:TimerEvent):void
{
trace("Alarm!");
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);
}

23.11.2012.

154

ACTIONSCRIPT 3.0

, ,
( ).
timer Timer, TimerEvent
(flash.events.TimerEvent), Event. Timer
, TimerEvent .


Flash Player 9 , Adobe AIR 1.0
Timer, AlarmClock ,
. ,
ActionScript, flash.events.IEventDispatcher. ,
flash.events.EventDispatcher,
IEventDispatcher ( EventDispatcher). ,
AlarmClock SimpleClock, ( )
EventDispatcher. , AlarmClock
.
, alarm AlarmClock
addEventListener(), AlarmClock EventDispatcher.
AlarmClock alarm,
dispatchEvent(), EventDispatcher.
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);

onAlarm() AlarmClock ( ).
dispatchEvent() AlarmClock,
, alarm AlarmClock.
, dispatchEvent(), ,
. AlarmEvent: Event,
.


Flash Player 9 , Adobe AIR 1.0

. Event.
.
( Event)
. AlarmEvent
alarm AlarmClock. AlarmEvent
alarm,
:

23.11.2012.

155

ACTIONSCRIPT 3.0

import flash.events.Event;
/**
* This custom Event class adds a message property to a basic Event.
*/
public class AlarmEvent extends Event
{
/**
* The name of the new AlarmEvent type.
*/
public static const ALARM:String = "alarm";
/**
* A text message that can be passed to an event handler
* with this event object.
*/
public var message:String;
/**
*Constructor.
*@param message The text to display when the alarm goes off.
*/
public function AlarmEvent(message:String = "ALARM!")
{
super(ALARM);
this.message = message;
}
...
}

, ,
Event, .
AlarmEvent message,
, ; message
AlarmEvent. AlarmEvent ALARM,
, (alarm) addEventListener()
AlarmClock.
Event
clone() ActionScript.
toString(),
toString().

23.11.2012.

156

ACTIONSCRIPT 3.0

/**
* Creates and returns a copy of the current instance.
* @return A copy of the current instance.
*/
public override function clone():Event
{
return new AlarmEvent(message);
}
/**
* Returns a String containing all the properties of the current
* instance.
* @return A string representation of the current instance.
*/
public override function toString():String
{
return formatToString("AlarmEvent", "type", "bubbles", "cancelable", "eventPhase",
"message");
}

clone() Event,
. toString()
formatToString() ( Event)
, .

23.11.2012.

157

158

9.
Flash Player 9 , Adobe AIR 1.0
ApplicationDomain ActionScript 3.0.
SWF- .
, .
,
.
SWF-,
ActionScript 3.0, API- Loader. ( ,
SWF-, ActionScript 1.0
ActionScript 2.0.) ActionScript 3.0 .
SWF-, , Loader,
applicationDomain LoaderContext ApplicationDomain.currentDomain.
SWF- , .
, SWF- ,
,
SWF-.
, Greeter.swf,
welcome():

23.11.2012.

ACTIONSCRIPT 3.0

package
{
import
import
import
import
import
import

flash.display.Loader;
flash.display.Sprite;
flash.events.*;
flash.net.URLRequest;
flash.system.ApplicationDomain;
flash.system.LoaderContext;

public class ApplicationDomainExample extends Sprite


{
private var ldr:Loader;
public function ApplicationDomainExample()
{
ldr = new Loader();
var req:URLRequest = new URLRequest("Greeter.swf");
var ldrContext:LoaderContext = new LoaderContext(false,
ApplicationDomain.currentDomain);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
ldr.load(req, ldrContext);
}
private function completeHandler(event:Event):void
{
var myGreeter:Class = ApplicationDomain.currentDomain.getDefinition("Greeter") as
Class;
var myGreeter:Greeter = Greeter(event.target.content);
var message:String = myGreeter.welcome("Tommy");
trace(message); // Hello, Tommy
}
}
}

. ApplicationDomain c ActionScript 3.0


Adobe Flash Platform.
.

SWF- .
, .
, , ,
Flash Player.

, , .
.
, .
.
, SWF-
, domain1.com. ,
.
SWF- .

23.11.2012.

159

160

ACTIONSCRIPT 3.0

: domain1.com

1
1.swf

mx.core.Application
1.swf

Loader

Loader

Loader

Loader

3
3.swf

2
mx.core.Application

2.swf

. . B. C

application1.swf. Loader,
SWF-. Application domain
1 ( 1). , B C
SWF- .
SWF- .

Application domain 2 . application2.swf


Application domain 2, , ,
application1.swf.
,
, . , ,
.
, ,
SWF- .
var appDomainA:ApplicationDomain = new ApplicationDomain();
var contextA:LoaderContext = new LoaderContext(false, appDomainA);
var loaderA:Loader = new Loader();
loaderA.load(new URLRequest("application2.swf"), contextA);

module1.swf (Application domain 1).


.
. SWF-
(RSL). RSL
.
SWF-, .

23.11.2012.

ACTIONSCRIPT 3.0

var appDomainB:ApplicationDomain = ApplicationDomain.currentDomain;


var contextB:LoaderContext = new LoaderContext(false, appDomainB);
var loaderB:Loader = new Loader();
loaderB.load(new URLRequest("module1.swf"), contextB);

. module3.swf ,
.
- (RIA),
.
,
,
.
, SWF-.

.
SWF-
.
var appDomainC:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
var contextC:LoaderContext = new LoaderContext(false, appDomainC);
var loaderC:Loader = new Loader();
loaderC.load(new URLRequest("module3.swf"), contextC);

23.11.2012.

161

162

10.

Flash Player 9 , Adobe AIR 1.0
Adobe ActionScript 3.0
. , , ,
, ,
, , API-
ActionScript. , ,
flash.display.
. Adobe AIR HTML
HTMLLoader. HTMLLoader HTML DOM .
DOM
ActionScript. API-
DOM, HTMLLoader.

23.11.2012.

ACTIONSCRIPT 3.0

Flash Player 9 , Adobe AIR 1.0


, ActionScript 3.0, ,
. . .
.

Stage


SWF-

, :


.
, .
:
SWF- ActionScript, SWF-.
SWF- Flash Player Adobe AIR .
( )
. SWF- Sprite (
. 168).
stage DisplayObject.
. 177.

23.11.2012.

163

ACTIONSCRIPT 3.0

ActionScript 3.0
. flash.display DisplayObject, ,
. ,
, . .
168.


,
, .
DisplayObjectContainer DisplayObject. DisplayObjectContainer
. ,
DisplayObjectContainer, Sprite
:
A

A. SimpleButton. up ( ), down (
) over ( ). . Bitmap. Bitmap JPEG
Loader. . Shape. ,
ActionScript. Shape . . TextField.

DisplayObjectContainer
. ,
.
DisplayObject,
DisplayObject. , Shape Video
, DisplayObject .

,
ActionScript:
, ( , ) . ,
, - 60 %, 60 % 40 %.
, (

) .
.

23.11.2012.

164

ACTIONSCRIPT 3.0

, , ,
, .
.
.
, Flash Player AIR

. ,
, ,
. , (,
).
, Flash Player AIR.
.
DisplayObject.
,

() .
SWF- , SWF-

, SWF-. , SWF-,
Flash, . ,
. SWF- ,
.
(, , ).

, .
,
.
,

SWF-.
, : , ,
, .
, ,
(, , , ).

23.11.2012.

165

166

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
flash.display ActionScript 3.0 ,
Flash Player AIR. ,
.
DisplayObject

AVM1Movie

Bitmap

InteractiveObject

DisplayObjectContainer SimpleButton

Loader

Sprite

MorphShape

Shape

StaticText

Video

TextField

Stage

MovieClip

, . ,
, StaticText, TextField Video, flash.display.
DisplayObject.
, DisplayObject, .
. DisplayObject 171.
, flash.display.

Bitmap Bitmap ,
ActionScript.
Loader. GIF-, JPG- PNG-. ,
BitmapData , Bitmap,
. BitmapData ,
ActionScript. .
215 260.

Loader Loader (SWF- ).


.
214.

Shape Shape (, , ,
..) . API 238.

SimpleButton SimpleButton ActionScript ,


Flash. SimpleButton 4 :
, , ( ,
).

23.11.2012.

ACTIONSCRIPT 3.0

Sprite Sprite , .
Sprite DisplayObjectContainer. .
172 API
238.

MovieClip MovieClip ,
ActionScript Flash. MovieClip
Sprite, , .
. 347.
, flash.display, DisplayObject.

TextField, flash.text, .
. 400.

TextLine, flash.text.engine, ,
, Flash Text Engine Text
Layout Framework. . Flash Text Engine
427 Text Layout Framework 457.

Video, flash.media, ,
. . 507.
flash.display, DisplayObject.
.
, .

AVM1Movie AVM1Movie SWF-,


ActionScript 1.0 2.0.

DisplayObjectContainer Loader, Stage, Sprite MovieClip


DisplayObjectContainer. .
172.

InteractiveObject InteractiveObject ,
. SimpleButton, TextField, Loader, Sprite, Stage MovieClip
InteractiveObject.
. 597.

MorphShape Flash.
ActionScript , .

Stage Stage DisplayObjectContainer.


Stage, .
, stage DisplayObject.
. 177.
, StaticText flash.text DisplayObject.
. Flash.
,
, .
, , .

StageVideo StageVideo ,
. , Flash Player 10.2 AIR 2.5 ( AIR for TV).
. StageVideo
548.

23.11.2012.

167

ACTIONSCRIPT 3.0

StageWebView StageWebView HTML-. ,


AIR 2.5. . StageWebView 1103.
fl.display , flash.display.Loader LoaderInfo.
flash.display Flash Professional
(CS5.5 ). , TLF
RSL. .
ProLoader ProLoaderInfo 218.

fl.display.ProLoader flash.display.Loader
fl.display.ProLoaderInfo flash.display.LoaderInfo

Flash Player 9 , Adobe AIR 1.0


ActionScript 3.0 . ActionScript 1.0
2.0 MovieClip.
:

;


,


Flash Player 9 , Adobe AIR 1.0
ActionScript 1.0 2.0 MovieClip. ActionScript 3.0
, .
ActionScript 3.0 ,
MovieClip, .
, MovieClip ,
Shape . , ,
. ActionScript 3.0 Shape
. Shape , MovieClip. Flash
Player AIR MovieClip.
.

23.11.2012.

168

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
ActionScript 1.0 2.0 ,
getNextHighestDepth().
ActionScript 3.0 DisplayObjectContainer,
.
ActionScript 3.0
DisplayObjectContainer
. ,
.
ActionScript 3.0
. DisplayObjectContainer numChildren,
.
, ,
0 (numChildren - 1).
MovieClip ActionScript 1.0 2.0.
ActionScript 3.0 ;
.
ActionScript 1.0 2.0.
ActionScript 1.0 2.0
, . ActionScript 3.0
,
.
.
ActionScript 3.0
getChildByName() DisplayObjectContainer.


Flash Player 9 , Adobe AIR 1.0
ActionScript 1.0 2.0 (, ,
Flash) . ActionScript 3.0 (
, ActionScript, , Flash.
. 175.

,
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 ,
. , .
addChild() addChildAt()
DisplayObjectContainer, .

23.11.2012.

169

ACTIONSCRIPT 3.0

, ,
(, , ,
). ,
.
, , . ,
,
.


Flash Player 9 , Adobe AIR 1.0
ActionScript 1.0 2.0 MovieClip SWF-,
. ActionScript 3.0 DisplayObject
, Shape Bitmap. ActionScript 3.0
,
.
, ActionScript 2.0, CustomCircle,
MovieClip ,
. MovieClip (,
totalFrames), . ActionScript 3.0 CustomCircle,
Shape,
, MovieClip. CustomCircle:
import flash.display.*;
public class CustomCircle extends Shape
{
var xPos:Number;
var yPos:Number;
var radius:Number;
var color:uint;
public function CustomCircle(xInput:Number,
yInput:Number,
rInput:Number,
colorInput:uint)
{
xPos = xInput;
yPos = yInput;
radius = rInput;
color = colorInput;
this.graphics.beginFill(color);
this.graphics.drawCircle(xPos, yPos, radius);
}
}

23.11.2012.

170

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, , ,
, ,
ActionScript 3.0.

DisplayObject
Flash Player 9 , Adobe AIR 1.0
DisplayObject
DisplayObject. ,
. , x y,
.
DisplayObject DisplayObject.
(, DisplayObject, , Sprite),
new. ,
, ,
(, Shape Sprite).
. DisplayObject c ActionScript 3.0
Adobe Flash Platform.


Flash Player 9 , Adobe AIR 1.0
( ) ,
,
. , myText TextField ,
. this
, .
import flash.display.*;
import flash.text.TextField;
var myText:TextField = new TextField();
myText.text = "Buenos dias.";
this.addChild(myText);


Stage. SWF-, (,
HTML), .
, Sprite.
, ActionScript (,
MXML Flex MXML Flash Professional),
. ActionScript,
. , button1,
( ActionScript):
button1.width = 200;

23.11.2012.

171

172

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
DisplayObjectContainer ,
, DisplayObjectContainer ,
.
,
. ,
(pictureScreen),
( PictureFrame):
A

. , pictureScreen . ,
pictureScreen

, ,
. addChild() addChildAt()
. , myTextField
:
var myTextField:TextField = new TextField();
myTextField.text = "hello";
this.root.addChild(myTextField);

23.11.2012.

ACTIONSCRIPT 3.0

this.root MovieClip, .
.
addChildAt()
. , ,
, ( ). ,
. Ball.


addChildAt(). , :
ball_A = new Ball(0xFFCC00, "a");
ball_A.name = "ball_A";
ball_A.x = 20;
ball_A.y = 20;
container.addChild(ball_A);
ball_B = new Ball(0xFFCC00, "b");
ball_B.name = "ball_B";
ball_B.x = 70;
ball_B.y = 20;
container.addChild(ball_B);
ball_C = new Ball(0xFFCC00, "c");
ball_C.name = "ball_C";
ball_C.x = 40;
ball_C.y = 60;
container.addChildAt(ball_C, 1);

container DisplayObjectContainer
. .

, .
, , ball_A ,
:
container.addChild(ball_A);

23.11.2012.

173

ACTIONSCRIPT 3.0

ball_A container
. .
getChildAt() ,
. getChildAt()
. ,
container DisplayObjectContainer:
trace(container.getChildAt(0).name); // ball_A
trace(container.getChildAt(1).name); // ball_C
trace(container.getChildAt(2).name); // ball_B


. ,
, , ,
2 container DisplayObjectContainer, 1 ,
:
container.removeChild(ball_C);
trace(container.getChildAt(0).name); // ball_A
trace(container.getChildAt(1).name); // ball_B

removeChild() removeChildAt() .
.
. , delete.
,
. , ,
tf1 ( Sprite,
DisplayObjectContainer):
tf1:TextField = new TextField();
tf2:TextField = new TextField();
tf1.name = "text 1";
tf2.name = "text 2";
container1:Sprite = new Sprite();
container2:Sprite = new Sprite();
container1.addChild(tf1);
container1.addChild(tf2);
container2.addChild(tf1);
trace(container1.numChildren); // 1
trace(container1.getChildAt(0).name); // text 2
trace(container2.numChildren); // 1
trace(container2.getChildAt(0).name); // text 1

, ,
,
.
DisplayObjectContainer
, .

contains(): , DisplayObjectContainer.

getChildByName(): .

23.11.2012.

174

ACTIONSCRIPT 3.0

getChildIndex(): .

setChildIndex(): .

removeChildren(): .

swapChildren(): , .

swapChildrenAt(): ,

.
. c ActionScript 3.0
Adobe Flash Platform.
, , (
, ),
, .


Flash Player 9 , Adobe AIR 1.0
, .
, . ,
,
.

Stage


SWF-

23.11.2012.

175

ACTIONSCRIPT 3.0

DisplayObjectContainer
. , ,
(title pict) container (
Sprite, DisplayObjectContainer):
var container:Sprite = new Sprite();
var title:TextField = new TextField();
title.text = "Hello";
var pict:Loader = new Loader();
var url:URLRequest = new URLRequest("banana.jpg");
pict.load(url);
pict.name = "banana loader";
container.addChild(title);
container.addChild(pict);

getChildAt() ,
:
trace(container.getChildAt(0) is TextField); // true

.
, , Flash Player AIR
(, "instance1").
getChildByName() "banana loader":
trace(container.getChildByName("banana loader") is Loader); // true

getChildByName(), getChildAt(),
.

,
. , pict
Loader pict ,
. ,
pict.getChildAt(0). , container.getChildAt(0).getChildAt(0) (
container.getChildAt(0) == pict).
trace(),
:
function traceDisplayList(container:DisplayObjectContainer,indentString:String = ""):void
{
var child:DisplayObject;
for (var i:uint=0; i < container.numChildren; i++)
{
child = container.getChildAt(i);
trace(indentString, child, child.name);
if (container.getChildAt(i) is DisplayObjectContainer)
{
traceDisplayList(DisplayObjectContainer(child), indentString + "")
}
}
}

23.11.2012.

176

ACTIONSCRIPT 3.0

Adobe Flex
Flex, ,
,
DisplayObjectContainer. , Container mx.core addChild()
DisplayObjectContainer ( Container).
addChild() ,
Container Flex.
, mx.core.UIComponent.


Flash Player 9 , Adobe AIR 1.0
Stage DisplayObject.
Flash Player AIR . , Stage
x y, .
x y . Stage
, .
. Stage ,
, SWF-.
. 1146.


Flash Player 9 , Adobe AIR 1.0
framerate Stage SWF-,
. . c ActionScript 3.0
Adobe Flash Platform.


Flash Player 9 , Adobe AIR 1.0
, Flash Player AIR,
. scaleMode Stage
. 4 ,
flash.display.StageScaleMode:

StageScaleMode.EXACT_FIT SWF

.
, ,
.

StageScaleMode.SHOW_ALL SWF
.
, letterbox, ,
.

23.11.2012.

177

ACTIONSCRIPT 3.0

StageScaleMode.NO_BORDER SWF

.
,
.

StageScaleMode.NO_SCALE SWF.
, . ,
.

StageScaleMode.NO_SCALE Width Height


Stage
. stageWidth stageHeight
SWF-. , scaleMode
StageScaleMode.NO_SCALE, SWF- , resize Stage,
.
, scaleMode StageScaleMode.NO_SCALE,
, .
, SWF-, ,
.
.
.
// mainContent is a display object containing the main content;
// it is positioned at the top-left corner of the Stage, and
// it should resize when the SWF resizes.
//
//
//
//

controlBar is a display object (e.g. a Sprite) containing several


buttons; it should stay positioned at the bottom-left corner of the
Stage (below mainContent) and it should not resize when the SWF
resizes.

import
import
import
import

flash.display.Stage;
flash.display.StageAlign;
flash.display.StageScaleMode;
flash.events.Event;

var swfStage:Stage = mainContent.stage;


swfStage.scaleMode = StageScaleMode.NO_SCALE;
swfStage.align = StageAlign.TOP_LEFT;
swfStage.addEventListener(Event.RESIZE, resizeDisplay);
function resizeDisplay(event:Event):void
{
var swfWidth:int = swfStage.stageWidth;
var swfHeight:int = swfStage.stageHeight;
// Resize the main content area
var newContentHeight:Number = swfHeight - controlBar.height;
mainContent.height = newContentHeight;
mainContent.scaleX = mainContent.scaleY;
// Reposition the control bar.
controlBar.y = newContentHeight;
}

23.11.2012.

178

ACTIONSCRIPT 3.0

AIR
scaleMode Stage ,
. AIR noScale.
.
. , .
, , .
,
. AIR
,
, .
AIR
SWF-. NativeWindow
AIR 72:1.
, 72x72 , 10x10, ,
10x10 . 144x144
, 10x10 20x20 .
scaleMode, noScale ,
72
. ,
client.
if(newWindow.stage.scaleMode != StageScaleMode.NO_SCALE){
client.scaleX = 72/newWindow.stage.stageWidth;
client.scaleY = 72/newWindow.stage.stageHeight;
}

. Flex HTML scaleMode Stage


noScale. scaleMode ,
.


Flash Player 9 , Adobe AIR 1.0
-
. Stage displayState
SWF-. displayState ,
flash.display.StageDisplayState. ,
displayState StageDisplayState.FULL_SCREEN:
stage.displayState = StageDisplayState.FULL_SCREEN;

( Flash Player 11.3),


displayState StageDisplayState.FULL_SCREEN_INTERACTIVE:
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;

Flash Player ActionScript


( ) . AIR,
,
.

23.11.2012.

179

ACTIONSCRIPT 3.0

, displayState
StageDisplayState.NORMAL.
stage.displayState = StageDisplayState.NORMAL;

,
: Esc ( ), Control-W (Windows),
Command-W (Mac) Alt-F4 (Windows).
Flash Player
SWF-, HTML-, HTML,
Flash Player, param, embed allowFullScreen
true, :
<object>
...
<param name="allowFullScreen" value="true" />
<embed ... allowFullScreen="true" />
</object>

Flash >
HTML Flash .
Flex , HTML <object> <embed>,
.
- SWF- JavaScript,
allowFullScreen param JavaScript. ,
HTML- AC_FL_RunContent() (
HTML, Flash Professional Flash Builder),
allowFullScreen :
AC_FL_RunContent(
...
'allowFullScreen','true',
...
); //end AC code

SWF-, Flash Player.


. (wmode HTML) (opaque)
(transparent), .
Flash Player
. 1120.
Flash Player 11.3

Flash Player 11.3


, ( Esc,
).
(,
WASD ).

23.11.2012.

180

ACTIONSCRIPT 3.0

SWF-, HTML-,
HTML, Flash Player, param, embed
allowFullScreenInteractive true, :
<object>
...
<param name="allowFullScreenInteractive" value="true" />
<embed ... allowFullScreenInteractive="true" />
</object>

Flash >
HTML Flash .
Flash Builder Flex , HTML <object> <embed>,
.
- SWF- JavaScript,
allowFullScreenInteractive param JavaScript.
, HTML- AC_FL_RunContent() (
HTML, Flash Professional Flash Builder),
allowFullScreenInteractive :
AC_FL_RunContent(
...
'allowFullScreenInteractive','true',
...
); //end AC code

SWF-, Flash Player.



Stage.fullScreenHeight Stage.fullScreenWidth ,
, .
,
, .
, Stage.displayState
StageDisplayState.FULL_SCREEN, .
, SWF . Flash Player AIR ,
, SWF-,
. fullScreenHeight fullScreenWidth ,
. .
Stage.fullScreenHeight Stage.fullScreenWidth c ActionScript 3.0 Adobe
Flash Platform.
, .
scaleMode Stage. scaleMode
StageScaleMode.NO_SCALE, stageWidth stageHeight ,
, SWF- ( ).
HTML .
fullScreen Stage , , ,
. , ,

:

23.11.2012.

181

ACTIONSCRIPT 3.0

import flash.events.FullScreenEvent;
function fullScreenRedraw(event:FullScreenEvent):void
{
if (event.fullScreen)
{
// Remove input text fields.
// Add a button that closes full-screen mode.
}
else
{
// Re-add input text fields.
// Remove the button that closes full-screen mode.
}
}
mySprite.stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw);

, fullScreen
flash.events.FullScreenEvent, fullScreen, ,
(true) (false).

Flash Player ActionScript,
, TextField,
. (, ) :

, , ,
, : Esc (Windows Mac), Control-W
(Windows), Command-W (Mac), Alt-F4
SWF, Flash Player
AIR. AIR ,
.

,
.
Stage.mouseLock, . ,
.
.
.
.

:

Escape ( ), Control-W
(Windows), Command-W (Mac) Alt-F4 (Windows).

.
,
.

23.11.2012.

182

ACTIONSCRIPT 3.0

, .
, , mouseMove, MouseEvent
. ,
MouseEvent.localX MouseEvent.localY. ,
MouseEvent.movementX MouseEvent.movementY.
movementX movementY ,
, .

fullScreenSourceRect Stage , Flash Player
AIR , .
Flash Player AIR
, ,
.
,
. ActionScript 3.0
.
import flash.geom.*;
{
stage.fullScreenSourceRect = new Rectangle(0,0,320,240);
stage.displayState = StageDisplayState.FULL_SCREEN;
}

, displayState
, Flash Player AIR .
ActionScript . Flash Player AIR
Esc
. 260 30 ,
Flash Player.
fullScreenSourceRect , Flash Player AIR
. ,
, displayState .
, fullScreenSourceRect .
stage.fullScreenSourceRect = new Rectangle(0,0,320,240);

, fullScreenSourceRect null.
stage.fullScreenSourceRect = null;

Flash Player,
Flash Player. ,
(Windows) Control (Mac)
Flash Player . , ,
.

23.11.2012.

183

ACTIONSCRIPT 3.0

:
Flash Player 10 :
,
Flash. AIR.
Flash Player.
,
.
,
.
.
, YUV-, ,
YUV-
, , RGB (, ,
), .
. ,
.
, .
.
( , , )
, . Adobe
SWF- HTML-, . ,
. Flash
, , .
SWF- 60,
. 50 55 ,
.
Microsoft DirectX 9 128 Windows OpenGL
Apple Macintosh, Mac OS X 10.2 .
Microsoft DirectX 9 Pixel Shader 2.0 Windows
128 . Mac OS X Linux
OpenGL 1.5 OpenGL ( ,
, , , ).
(direct gpu) SWF-
Flash Flash.
, default, transparent opaque ,
HTML.


Flash Player 9 , Adobe AIR 1.0
DisplayObject EventDispatcher. ,
( 134).
addEventListener(),
EventDispatcher, , ,
.

23.11.2012.

184

ACTIONSCRIPT 3.0

Flash Player AIR ,


, . ,
child1, Flash Player
child1.
, :
Stage

arent Node

Child1 Node

Child2 Node

. 134.
,
, ( )
. ,
, ,
. .
149.

DisplayObject
Flash Player 9 , Adobe AIR 1.0
,
, .
, .
, ,
:

, (
, ),
DisplayObject InteractiveObject , :

Bitmap .
TextField .
Video .
Shape , . ,
,
, , Shape
Sprite MovieClip.

23.11.2012.

185

ACTIONSCRIPT 3.0

MorphShape, StaticText SimpleButton , Flash.


( ,
, ,
Flash.)

, ,
Stage.

SWF- ,
Loader.
Loader.
:

Bitmap.
SWF-, ActionScript 3.0, Sprite MovieClip (
, ).

SWF-, ActionScript 1.0 ActionScript 2.0,


AVM1Movie.

,
( ActionScript),
DisplayObjectContainer:

Sprite ( ActionScript
,
ActionScript).

MovieClip ( , ,
Flash).

, Flash,
DisplayObjectContainer :

MovieClip ( )
Sprite ( )


Flash Player 9 , Adobe AIR 1.0
, , ,
, , . ,
, , ,
, .
(DisplayObject),
TextField, Video, Shape .
.

23.11.2012.

186

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, ,
. , x y .
myShape.x = 17;
myShape.y = 212;


( x y). (
0,0, x y) .
x , ,
y , ( ).
, myShape 17
x (17 ) 212 y (212
).
ActionScript, x y
0, .


, x y
0,0 . Shape (,
), Sprite, x y 0
,
. ,
globalToLocal() ,
( ) ( ). , :

23.11.2012.

187

ACTIONSCRIPT 3.0

// Position the shape at the top-left corner of the Stage,


// regardless of where its parent is located.
// Create a Sprite, positioned at x:200 and y:200.
var mySprite:Sprite = new Sprite();
mySprite.x = 200;
mySprite.y = 200;
this.addChild(mySprite);
// Draw a dot at the Sprite's 0,0 coordinate, for reference.
mySprite.graphics.lineStyle(1, 0x000000);
mySprite.graphics.beginFill(0x000000);
mySprite.graphics.moveTo(0, 0);
mySprite.graphics.lineTo(1, 0);
mySprite.graphics.lineTo(1, 1);
mySprite.graphics.lineTo(0, 1);
mySprite.graphics.endFill();
// Create the circle Shape instance.
var circle:Shape = new Shape();
mySprite.addChild(circle);
// Draw a circle with radius 50 and center point at x:50, y:50 in the Shape.
circle.graphics.lineStyle(1, 0x000000);
circle.graphics.beginFill(0xff0000);
circle.graphics.drawCircle(50, 50, 50);
circle.graphics.endFill();
// Move the Shape so its top-left corner is at the Stage's 0, 0 coordinate.
var stagePoint:Point = new Point(0, 0);
var targetPoint:Point = mySprite.globalToLocal(stagePoint);
circle.x = targetPoint.x;
circle.y = targetPoint.y;

, localToGlobal() DisplayObject,
.


,
ActionScript. .
, , ,
.
. Flash Player 11.3 AIR 3.3 :
MouseEvent.RELEASE_OUTSIDE ,
Sprite.
startDrag(). , .
startDrag() ,
. , stopDrag(). Sprite ,
Sprite .

23.11.2012.

188

ACTIONSCRIPT 3.0

// This code creates a mouse drag interaction using the startDrag()


// technique.
// square is a MovieClip or Sprite instance).
import flash.events.MouseEvent;
// This function is called when the mouse button is pressed.
function startDragging(event:MouseEvent):void
{
square.startDrag();
}
// This function is called when the mouse button is released.
function stopDragging(event:MouseEvent):void
{
square.stopDrag();
}
square.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
square.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

: startDrag()
. , startDrag()
, .
, startDragging() , ,
circle, square.startDrag():
function startDragging(event:MouseEvent):void
{
square.startDrag();
circle.startDrag();
}

- , startDrag() ,
stopDrag() .
.
,
, startDrag() ,
, .
, mouseMove .
, , ,
x y.
. ,
, . ,
:

23.11.2012.

189

ACTIONSCRIPT 3.0

// This code moves display objects using the mouse-following


// technique.
// circle is a DisplayObject (e.g. a MovieClip or Sprite instance).
import flash.events.MouseEvent;
var offsetX:Number;
var offsetY:Number;
// This function is called when the mouse button is pressed.
function startDragging(event:MouseEvent):void
{
// Record the difference (offset) between where
// the cursor was when the mouse button was pressed and the x, y
// coordinate of the circle when the mouse button was pressed.
offsetX = event.stageX - circle.x;
offsetY = event.stageY - circle.y;
// tell Flash Player to start listening for the mouseMove event
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCircle);
}
// This function is called when the mouse button is released.
function stopDragging(event:MouseEvent):void
{
// Tell Flash Player to stop listening for the mouseMove event.
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCircle);
}
// This function is called every time the mouse moves,
// as long as the mouse button is pressed down.
function dragCircle(event:MouseEvent):void
{
// Move the circle to the location of the cursor, maintaining
// the offset between the cursor's location and the
// location of the dragged object.
circle.x = event.stageX - offsetX;
circle.y = event.stageY - offsetY;
// Instruct Flash Player to refresh the screen after this event.
event.updateAfterEvent();
}
circle.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
circle.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

, ,
. ,
. , , ,
. , ,
, , . .
, ,
.

23.11.2012.

190

ACTIONSCRIPT 3.0

( )
, . ,
, . (
.)
//
//
//
//

This code creates a drag-and-drop interaction using the mouse-following


technique.
circle and square are DisplayObjects (e.g. MovieClip or Sprite
instances).

import flash.display.DisplayObject;
import flash.events.MouseEvent;
var offsetX:Number;
var offsetY:Number;
var draggedObject:DisplayObject;
// This function is called when the mouse button is pressed.
function startDragging(event:MouseEvent):void
{
// remember which object is being dragged
draggedObject = DisplayObject(event.target);
// Record the difference (offset) between where the cursor was when
// the mouse button was pressed and the x, y coordinate of the
// dragged object when the mouse button was pressed.
offsetX = event.stageX - draggedObject.x;
offsetY = event.stageY - draggedObject.y;
// move the selected object to the top of the display list
stage.addChild(draggedObject);
// Tell Flash Player to start listening for the mouseMove event.
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragObject);
}
// This function is called when the mouse button is released.
function stopDragging(event:MouseEvent):void
{
// Tell Flash Player to stop listening for the mouseMove event.
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragObject);
}

23.11.2012.

191

ACTIONSCRIPT 3.0

// This function is called every time the mouse moves,


// as long as the mouse button is pressed down.
function dragObject(event:MouseEvent):void
{
// Move the dragged object to the location of the cursor, maintaining
// the offset between the cursor's location and the location
// of the dragged object.
draggedObject.x = event.stageX - offsetX;
draggedObject.y = event.stageY - offsetY;
// Instruct Flash Player to refresh the screen after this event.
event.updateAfterEvent();
}
circle.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
circle.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
square.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
square.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

(, ,
,
, , (, ,
) .
, , ,
( ) .
ActionScript .
288.


Flash Player 9 , Adobe AIR 1.0
, ,
, scrollRect
. , scrollRect , ,
, .
scrollRect Rectangle. ,
.
, Rectangle
scrollRect . scrollRect
Rectangle. (,
x Rectangle, , y,
). Rectangle scrollRect,
.
, TextField bigText,
, SWF-. (up down)
, TextField
y RectanglescrollRect.

23.11.2012.

192

ACTIONSCRIPT 3.0

import flash.events.MouseEvent;
import flash.geom.Rectangle;
// Define the initial viewable area of the TextField instance:
// left: 0, top: 0, width: TextField's width, height: 350 pixels.
bigText.scrollRect = new Rectangle(0, 0, bigText.width, 350);
// Cache the TextField as a bitmap to improve performance.
bigText.cacheAsBitmap = true;
// called when the "up" button is clicked
function scrollUp(event:MouseEvent):void
{
// Get access to the current scroll rectangle.
var rect:Rectangle = bigText.scrollRect;
// Decrease the y value of the rectangle by 20, effectively
// shifting the rectangle down by 20 pixels.
rect.y -= 20;
// Reassign the rectangle to the TextField to "apply" the change.
bigText.scrollRect = rect;
}
// called when the "down" button is clicked
function scrollDown(event:MouseEvent):void
{
// Get access to the current scroll rectangle.
var rect:Rectangle = bigText.scrollRect;
// Increase the y value of the rectangle by 20, effectively
// shifting the rectangle up by 20 pixels.
rect.y += 20;
// Reassign the rectangle to the TextField to "apply" the change.
bigText.scrollRect = rect;
}
up.addEventListener(MouseEvent.CLICK, scrollUp);
down.addEventListener(MouseEvent.CLICK, scrollDown);

, scrollRect ,
Flash Player AIR
cacheAsBitmap. Flash Player AIR
.
, . .
196.


Flash Player 9 , Adobe AIR 1.0
:
(width height), (scaleX scaleY).
width height,
. , .
, :

23.11.2012.

193

ACTIONSCRIPT 3.0

// Resize a display object.


square.width = 420;
square.height = 420;
// Determine the radius of a circle display object.
var radius:Number = circle.width / 2;

height width .
, .
, .
.
, , , ,
, , ,
.
width height Flash Player AIR
scaleX scaleY .

. TextField .
, ,
scaleX scaleY .
scaleX scaleY TextField width height ( )
, .
.
scaleX scaleY .
, width ,
, scaleX .5, 50 .
scaleY 2, 200 .
// circle is a display object whose width and height are 150 pixels.
// At original size, scaleX and scaleY are 1 (100%).
trace(circle.scaleX); // output: 1
trace(circle.scaleY); // output: 1
// When you change the width and height properties,
// Flash Player changes the scaleX and scaleY properties accordingly.
circle.width = 100;
circle.height = 75;
trace(circle.scaleX); // output: 0.6622516556291391
trace(circle.scaleY); // output: 0.4966887417218543

. , (height) ,
(width), ,
. ,
scaleX scaleY,
width height. , width square,
(scaleY), ,
.
// Change the width directly.
square.width = 150;
// Change the vertical scale to match the horizontal scale,
// to keep the size proportional.
square.scaleY = square.scaleX;

23.11.2012.

194

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
(, )
, .
, , , .
,
.
. . -
.

,
( ) ().
.

, ,
(Scale-9).
9 ( 33, -).
: .
, (, ),
.
, ,
, .
, .

,
, , ,
, , .

23.11.2012.

195

ACTIONSCRIPT 3.0

ActionScript scale9Grid

Scale-9. Rectangle scale9Grid
:
myButton.scale9Grid = new Rectangle(32, 27, 71, 64);

Rectangle 4 : x, y, .
(x: 32, y: 27)
myButton. 71 , 64 (
(x:103), (y:92) ).

, , Rectangle,
Scale-9.
Flash Player AIR Rectangle, :


, .

. myButton.width = 131;myButton.height = 106; . myButton.width = 73;myButton.height = 69; B. myButton.width = 54;myButton.height


= 141;


Flash Player 9 , Adobe AIR 1.0
Flash
, .
( Shape), Flash Player
AIR . Flash Player AIR
Shape .
, SWF. .
, SWF-. ,
SWF-,
.

23.11.2012.

196

ACTIONSCRIPT 3.0

. . . ,
, , SWF.
cacheAsBitmap true ,
. Flash Player AIR
, ,
.
. .
. .
199.
opaqueBackground scrollRect DisplayObject
cacheAsBitmap. ,
opaqueBackground scrollRect ,
. opaqueBackground scrollRect
, cacheAsBitmap true.
.
192. .
200.
-, cacheAsBitmap true,
. 205.


Flash Player 9 , Adobe AIR 1.0
,
(, ).
, . ,
, SWF-.
,
. ,
, .
,
, opaqueBackground.

.
.

,
.

: ,
(, , trace bitmap,
, Adobe Illustrator). .
, .
, opaqueBackground
true. ,
.

23.11.2012.

197

ACTIONSCRIPT 3.0

: ,
. ,
( scrollRect).
.
. ,
.

: .
(, -).
( cacheAsBitmap true),
. , ,
.

-: -
cacheAsBitmap true. .
205.

.
, cacheAsBitmap
true , false.
, cacheAsBitmap
.


SWF-.
.

( ) , .
, . ,
, .
,
. , Sprite 250x250
, 250 1 (
) Sprite.

.
, (. ),
.

, , ,
( ). ,
.
MovieClip Video. ,
, ,
SWF-.

, ,
Flash Player AIR ( ). ,
(, ).

23.11.2012.

198

ACTIONSCRIPT 3.0

, . ,
, alpha, ,

. ,
,
,
.

.


Flash Player 9 , Adobe AIR 1.0
, cacheAsBitmap
true.
mySprite.cacheAsBitmap = true;

cacheAsBitmap true ,
. SWF- ,
.
( ) , cacheAsBitmap
true, .

2880 .
( ).

Adobe AIR 2.0 ( )
AIR cacheAsBitmapMatrix
, cacheAsBitmap.
.
mySprite.cacheAsBitmap = true;
mySprite.cacheAsBitmapMatrix = new Matrix();

,
.





( 0 100 % )
.

23.11.2012.

199

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
. , SWF- ,
, opaqueBackground
( ). (
). ,
.
cacheAsBitmap true, opaqueBackground
, opaqueBackground
. cacheAsBitmap true,
opaqueBackground .
.

:
myShape.cacheAsBitmap = true;
myShape.opaqueBackground = 0xFF0000;

Shape myShape (0xFF0000). ,


Shape .

(, Shape).

,
. . , SWF-
opaqueBackground, , 0xFFFFFF
.


Flash Player 9 , Adobe AIR 1.0
( )
( ),
, .
.
.

23.11.2012.

200

ACTIONSCRIPT 3.0

blendMode,
. BlendMode. ,
( ),
.

BlendMode.ADD ("add"):
.

BlendMode.ALPHA ("alpha"): .
( .)

BlendMode.DARKEN ("darken"): . (

.)

BlendMode.DIFFERENCE ("difference"): .

BlendMode.ERASE ("erase"): , ()
- . (
.)

BlendMode.HARDLIGHT ("hardlight"): . (

.)

BlendMode.INVERT ("invert"): .

BlendMode.LAYER ("layer"):

. (
.)

BlendMode.LIGHTEN ("lighten"): . (
.)

BlendMode.MULTIPLY ("multiply"): .

BlendMode.NORMAL ("normal"): , ,
.

BlendMode.OVERLAY ("overlay"): . (
.)

BlendMode.SCREEN ("screen"): .

BlendMode.SHADER ("shader"): , , Pixel Bender

. .
Pixel Bender 323. (
.)

BlendMode.SUBTRACT ("subtract"):

23.11.2012.

201

ACTIONSCRIPT 3.0

DisplayObject
Flash Player 9 , Adobe AIR 1.0
ColorTransform
(flash.geom.ColorTransform). transform,
Transform ,
(, , . .)
Transform colorTransform,
ColorTransform
. ,
:
var colorInfo:ColorTransform = myDisplayObject.transform.colorTransform;

ColorTransform , ,
, ,
. ,
ColorTransform transform.colorTransform.
var colorInfo:ColorTransform = myDisplayObject.transform.colorTransform;
// Make some color transformations here.
// Commit the change.
myDisplayObject.transform.colorTransform = colorInfo;


Flash Player 9 , Adobe AIR 1.0
color ColorTransform
RGB (, , ). color
square , blueBtn:
// square is a display object on the Stage.
// blueBtn, redBtn, greenBtn, and blackBtn are buttons on the Stage.
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
// Get access to the ColorTransform instance associated with square.
var colorInfo:ColorTransform = square.transform.colorTransform;
// This function is called when blueBtn is clicked.
function makeBlue(event:MouseEvent):void
{
// Set the color of the ColorTransform object.
colorInfo.color = 0x003399;
// apply the change to the display object
square.transform.colorTransform = colorInfo;
}
blueBtn.addEventListener(MouseEvent.CLICK, makeBlue);

23.11.2012.

202

ACTIONSCRIPT 3.0

, color
, , . ,
, ,
color ColorTransform
( ) (
).


Flash Player 9 , Adobe AIR 1.0
, (, ),
. ,
. ColorTransform
, .
redMultiplier, greenMultiplier, blueMultiplier alphaMultiplier
( ),
. (redOffset, greenOffset, blueOffset alphaOffset)

.
,
Flash. ,
.
JPEG ,
X Y. -
, , , ,
. ,

.

23.11.2012.

203

ACTIONSCRIPT 3.0

import
import
import
import
import

flash.display.Loader;
flash.events.MouseEvent;
flash.geom.Transform;
flash.geom.ColorTransform;
flash.net.URLRequest;

// Load an image onto the Stage.


var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("http://www.helpexamples.com/flash/images/image1.jpg");
loader.load(url);
this.addChild(loader);
// This function is called when the mouse moves over the loaded image.
function adjustColor(event:MouseEvent):void
{
// Access the ColorTransform object for the Loader (containing the image)
var colorTransformer:ColorTransform = loader.transform.colorTransform;
// Set the red and green multipliers according to the mouse position.
// The red value ranges from 0% (no red) when the cursor is at the left
// to 100% red (normal image appearance) when the cursor is at the right.
// The same applies to the green channel, except it's controlled by the
// position of the mouse in the y axis.
colorTransformer.redMultiplier = (loader.mouseX / loader.width) * 1;
colorTransformer.greenMultiplier = (loader.mouseY / loader.height) * 1;
// Apply the changes to the display object.
loader.transform.colorTransform = colorTransformer;
}
loader.addEventListener(MouseEvent.MOUSE_MOVE, adjustColor);


Flash Player 9 , Adobe AIR 1.0
rotation. ,
, . , (
), . , ,
square 45 ( ):
square.rotation = 45;

,
226.

23.11.2012.

204

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
, , ,
. alpha DisplayObject ( ,
) . alpha 0 1, 0
, 1 . ,
, myBall (50 %) :
function fadeBall(event:MouseEvent):void
{
myBall.alpha = .5;
}
myBall.addEventListener(MouseEvent.CLICK, fadeBall);

, ,
ColorTransform. . DisplayObject
202.


Flash Player 9 , Adobe AIR 1.0
, ,
.


, ,
mask :
// Make the object maskSprite be a mask for the object mySprite.
mySprite.mask = maskSprite;

,
. , Shape,
100100 , Sprite, 25 .
, ,
. , .

23.11.2012.

205

ACTIONSCRIPT 3.0

// This code assumes it's being run within a display object container
// such as a MovieClip or Sprite instance.
import flash.display.Shape;
// Draw a square and add it to the display list.
var square:Shape = new Shape();
square.graphics.lineStyle(1, 0x000000);
square.graphics.beginFill(0xff0000);
square.graphics.drawRect(0, 0, 100, 100);
square.graphics.endFill();
this.addChild(square);
// Draw a circle and add it to the display list.
var circle:Sprite = new Sprite();
circle.graphics.lineStyle(1, 0x000000);
circle.graphics.beginFill(0x0000ff);
circle.graphics.drawCircle(25, 25, 25);
circle.graphics.endFill();
this.addChild(circle);
function maskSquare(event:MouseEvent):void
{
square.mask = circle;
circle.removeEventListener(MouseEvent.CLICK, maskSquare);
}
circle.addEventListener(MouseEvent.CLICK, maskSquare);

, , ,
. .
. ,
,
(,
), . z ( ) ,
. .
MovieClip ,
. , .
, mask null:
// remove the mask from mySprite
mySprite.mask = null;

. alpha
. , , ;
.

23.11.2012.

206

ACTIONSCRIPT 3.0

AIR 2
cacheAsBitmap
cacheAsBitmapMatrix, . ,
,
, .
,
, .


, .
, ,
. ,
,
SWF- , .

-
- , ,
, .
// maskShape is a Shape instance which includes a gradient fill.
mySprite.cacheAsBitmap = true;
maskShape.cacheAsBitmap = true;
mySprite.mask = maskShape;

, -
, .
. (
, Loader, ) .
(, , )
; -.
. ,
.

23.11.2012.

207

ACTIONSCRIPT 3.0

// This code assumes it's being run within a display object container
// such as a MovieClip or Sprite instance.
import
import
import
import
import

flash.display.GradientType;
flash.display.Loader;
flash.display.Sprite;
flash.geom.Matrix;
flash.net.URLRequest;

// Load an image and add it to the display list.


var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("http://www.helpexamples.com/flash/images/image1.jpg");
loader.load(url);
this.addChild(loader);
// Create a Sprite.
var oval:Sprite = new Sprite();
// Draw a gradient oval.
var colors:Array = [0x000000, 0x000000];
var alphas:Array = [1, 0];
var ratios:Array = [0, 255];
var matrix:Matrix = new Matrix();
matrix.createGradientBox(200, 100, 0, -100, -50);
oval.graphics.beginGradientFill(GradientType.RADIAL,
colors,
alphas,
ratios,
matrix);
oval.graphics.drawEllipse(-100, -50, 200, 100);
oval.graphics.endFill();
// add the Sprite to the display list
this.addChild(oval);
// Set cacheAsBitmap = true for both display objects.
loader.cacheAsBitmap = true;
oval.cacheAsBitmap = true;
// Set the oval as the mask for the loader (and its child, the loaded image)
loader.mask = oval;
// Make the oval draggable.
oval.startDrag(true);


Flash Player 9 , Adobe AIR 1.0
.
.
.

23.11.2012.

208

ACTIONSCRIPT 3.0

, ,
. ActionScript
. .
, ActionScript,
.
, , (, ).
ActionScript ,
. , ,
, .
, .

SWF- ( , ),
AIR Flash Player.
enterFrame, SWF- (
). , ,
enterFrame .
, enterFrame
. ( )
, .
. Timer.
Timer
. , Timer.
( ).
Timer . 4.
Sprite circle.
, .
circle ( alpha ) ,
:

23.11.2012.

209

ACTIONSCRIPT 3.0

import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
// draw a circle and add it to the display list
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0x990000);
circle.graphics.drawCircle(50, 50, 50);
circle.graphics.endFill();
addChild(circle);
// When this animation starts, this function is called every frame.
// The change made by this function (updated to the screen every
// frame) is what causes the animation to occur.
function fadeCircle(event:Event):void
{
circle.alpha -= .05;
if (circle.alpha <= 0)
{
circle.removeEventListener(Event.ENTER_FRAME, fadeCircle);
}
}
function startAnimation(event:MouseEvent):void
{
circle.addEventListener(Event.ENTER_FRAME, fadeCircle);
}
circle.addEventListener(MouseEvent.CLICK, startAnimation);

, fadeCircle()
enterFrame. , . circle
alpha. alpha 0,05 (5 %),
. , alpha 0 (circle ),
fadeCircle(), , , .
, ,
. alpha ,
enterFrame, . ,

circle.alpha -= .05;

circle.x += 5;

x, . ,
, , ( ,
enterFrame) x.

23.11.2012.

210

ACTIONSCRIPT 3.0


AIR 2.0
,
, .
, ,
, .
,
, .
AIR .

. ,
, , resize
, , .
,
,
AIR.

. , ,
.


.
. .
: , .
StageOrientation ,
.
Stage , :

Stage.deviceOrientation
.
. deviceOrientation
. ,
.

Stage.orientation .
, ,
. ,
, orientation, ,
deviceOrientation. , deviceRotation
, orientation .

:
var aspect:String = this.stage.stageWidth >= this.stage.stageHeight ?
StageAspectRatio.LANDSCAPE : StageAspectRatio.PORTRAIT;

23.11.2012.

211

ACTIONSCRIPT 3.0


,
, .
.
.

autoOrients true false. ,
AIR <autoOrients>. ( , AIR 2.6
autoOrients
).

, AIR
.


scaleMode align Stage.
scaleMode .
,
(
).
scaleMode
.


.
.

23.11.2012.

212

ACTIONSCRIPT 3.0


Stage , ,
. resize orientationChange ,
.
resize ,
. resize,
. resize ,
noScale.
orientationChange .
orientationChange , .
.
orientationChanging resize orientationChange.
, .


AIR 2.6
setOrientation()
setAspectRatio() Stage.

setOrientation()
Stage. ,
StageOrientation.
this.stage.setOrientation( StageOrientation.ROTATED_RIGHT );

. , Android
2.2
.
supportedOrientations ,
setOrientation():
var orientations:Vector.<String> = this.stage.supportedOrientations;
for each( var orientation:String in orientations )
{
trace( orientation );
}


,
. AIR
setAspectRatio() Stage.
this.stage.setAspectRatio( StageAspectRatio.LANDSCAPE );

.
. ,
(AIR 3.2 ),
.

23.11.2012.

213

ACTIONSCRIPT 3.0

(AIR 3.3 ) AIR 3.3 (SWF 16)


StageAspectRatio.ANY. Stage.autoOrients true
setAspectRatio(StageAspectRatio.ANY),
(-, -, -). ,
AIR 3.3 , ,
.
: .
,
. deviceOrientation
, .
function refreshOrientation( theStage:Stage ):void
{
switch ( theStage.deviceOrientation )
{
case StageOrientation.DEFAULT:
theStage.setOrientation( StageOrientation.DEFAULT );
break;
case StageOrientation.ROTATED_RIGHT:
theStage.setOrientation( StageOrientation.ROTATED_LEFT );
break;
case StageOrientation.ROTATED_LEFT:
theStage.setOrientation( StageOrientation.ROTATED_RIGHT );
break;
case StageOrientation.UPSIDE_DOWN:
theStage.setOrientation( StageOrientation.UPSIDE_DOWN );
break;
default:
//No change
}
}

. orientationChange,
Stage, .
, setOrientation() .


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 :

SWF-, ActionScript 3.0 Sprite, MovieClip


, Sprite. AIR iOS
SWF-, - ActionScript. , SWF-,
, , SWF-,
.

JPG, PNG GIF.


AVM1 SWF SWF-, ActionScript 1.0 2.0. (
AIR )

23.11.2012.

214

ACTIONSCRIPT 3.0

Loader.


Flash Player 9 , Adobe AIR 1.0
Loader SWF- . Loader
DisplayObjectContainer. Loader
, SWF- .
Loader ( )
:
var pictLdr:Loader = new Loader();
var pictURL:String = "banana.jpg"
var pictURLReq:URLRequest = new URLRequest(pictURL);
pictLdr.load(pictURLReq);
this.addChild(pictLdr);

SWF-
(, container DisplayObjectContainer):
import flash.display.*;
import flash.net.URLRequest;
import flash.events.Event;
var container:Sprite = new Sprite();
addChild(container);
var pictLdr:Loader = new Loader();
var pictURL:String = "banana.jpg"
var pictURLReq:URLRequest = new URLRequest(pictURL);
pictLdr.load(pictURLReq);
pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
function imgLoaded(event:Event):void
{
container.addChild(pictLdr.content);
}


Flash Player 9 , Adobe AIR 1.0
LoaderInfo. LoaderInfo
, URL- ,
, . LoaderInfo
, .

23.11.2012.

215

216

ACTIONSCRIPT 3.0

LoaderInfo (
SWF-, Loader , Loader):

LoaderInfo

loaderInfo

SWF-

Loader

contentLoaderInfo
LoaderInfo

loaderInfo

LoaderInfo Loader
. , LoaderInfo
contentLoaderInfo Loader. LoaderInfo
loaderInfo
. loaderInfo
LoaderInfo, contentLoaderInfo Loader. , LoaderInfo
Loader.
,
LoaderInfo , :
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
var ldr:Loader = new Loader();
var urlReq:URLRequest = new URLRequest("Circle.swf");
ldr.load(urlReq);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
addChild(ldr);
function loaded(event:Event):void
{
var content:Sprite = event.target.content;
content.scaleX = 2;
}

. 134.


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR load() loadBytes() Loader
context. LoaderContext.

23.11.2012.

ACTIONSCRIPT 3.0

LoaderContext ,
.

checkPolicyFile: ( SWF-).

true, Loader
(. - ( ) 1131).
, , SWF, Loader. Loader, ActionScript
SWF- Loader . ,
BitmapData.draw() .
, SWF- , Loader,
Security.allowDomain(), .

securityDomain: SWF- ( ).
SWF- , ,
Loader. , Flash Player .
, SWF- , ,
SWF .
flash.system.SecurityDomain.currentDomain.

applicationDomain: SWF-,
ActionScript 3.0 ( SWF-, ActionScript 1.0 2.0).
, , Loader,
applicationDomain flash.system.ApplicationDomain.currentDomain.
SWF- , .
, SWF-,
, .
. 158.

:
var context:LoaderContext = new LoaderContext();
context.checkPolicyFile = true;
var urlReq:URLRequest = new URLRequest("http://www.[your_domain_here].com/photo11.jpg");
var ldr:Loader = new Loader();
ldr.load(urlReq, context);

SWF-
, Loader. ,
SWF- , Loader:
var context:LoaderContext = new LoaderContext();
context.securityDomain = SecurityDomain.currentDomain;
context.applicationDomain = ApplicationDomain.currentDomain;
var urlReq:URLRequest = new URLRequest("http://www.[your_domain_here].com/library.swf");
var ldr:Loader = new Loader();
ldr.load(urlReq, context);

. LoaderContext c ActionScript 3.0


Adobe Flash Platform.

23.11.2012.

217

ACTIONSCRIPT 3.0

ProLoader ProLoaderInfo
Flash Player 9 , Adobe AIR 1.0 Flash
Professional CS5.5
Flash Professional CS5.5 fl.display.ProLoader fl.display.ProLoaderInfo,
(RSL).
flash.display.Loader flash.display.LoaderInfo,
.
, ProLoader SWF, Text Layout Framework (TLF)
RSL. SWF,
SWF SWZ, TLF, SWF.
, SWF,
. ProLoader , ,
SWF. , ProLoader,
ActionScript. , ProLoader
SWF.
Flash Professional CS5.5
Loader ProLoader. Flash
Player 10.2 , ProLoader
ActionScript. ProLoader
Flash Player, ActionScript 3.0.
ProLoader Flash Player 10.2 .
ProLoader TLF Flash Professional CS5.5 . ProLoader
, Flash Professional.
. SWF, Flash Professional CS5.5 ,
fl.display.ProLoader fl.display.ProLoaderInfo
flash.display.Loader flash.display.LoaderInfo.
, ProLoader
ProLoader , Loader.
RSL TLF. ,
SWF, Loader SWF. :


. ProLoader SWF-
SWF-. SWF
SWF.

SWF .
, added, removed, addedToStage removedFromStage.
Flash Player 10.2 , ProLoader
.
ProLoader Loader
ProLoader Loader,
.
.

23.11.2012.

218

ACTIONSCRIPT 3.0

import flash.display.Loader;
import flash.events.Event;
var l:Loader = new Loader();
addChild(l);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
l.load("my.swf");
function loadComplete(e:Event) {
trace('load complete!');
}

ProLoader :
import fl.display.ProLoader;
import flash.events.Event;
var l:ProLoader = new ProLoader();
addChild(l);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
l.load("my.swf");
function loadComplete(e:Event) {
trace('load complete!');
}

: SpriteArranger
Flash Player 9 , Adobe AIR 1.0
SpriteArranger Geometric Shapes,
ActionScript 3.0.
SpriteArranger ,
:







www.adobe.com/go/learn_programmingAS3samples_flash_ru. SpriteArranger
Examples/SpriteArranger. .

23.11.2012.

219

220

ACTIONSCRIPT 3.0

File

SpriteArranger.mxml

Flash (FLA) Flex


(MXML).

SpriteArranger.fla
com/example/programmingas3/SpriteArranger/CircleSprite.as

, Sprite,
.

com/example/programmingas3/SpriteArranger/DrawingCanvas.as

, ,
,
GeometricSprite.

com/example/programmingas3/SpriteArranger/SquareSprite.as

, Sprite,
.

com/example/programmingas3/SpriteArranger/TriangleSprite.as

, Sprite,
.

com/example/programmingas3/SpriteArranger/GeometricSprite.as

, Sprite

.
CircleSprite, SquareSprite
TriangleSprite.

com/example/programmingas3/geometricshapes/IGeometricShape.as

, ,

.

com/example/programmingas3/geometricshapes/IPolygon.as

, ,


.

com/example/programmingas3/geometricshapes/RegularPolygon.as


,
.

com/example/programmingas3/geometricshapes/Circle.as

,
.

com/example/programmingas3/geometricshapes/EquilateralTriangle.as

RegularPolygon,
.

com/example/programmingas3/geometricshapes/Square.as

RegularPolygon,

.

com/example/programmingas3/geometricshapes/GeometricShapeFactory.as

,
.

SpriteArranger
Flash Player 9 , Adobe AIR 1.0
SpriteArranger
.
DrawingCanvas ,
.
GeometricSprite.

23.11.2012.

ACTIONSCRIPT 3.0

DrawingCanvas
Flex , Container,
, mx.core.UIComponent.
DrawingCanvas mx.containers.VBox (. MXML,
SpriteArranger.mxml). DrawingCanvas
:
public class DrawingCanvas extends UIComponent

UIComponent DisplayObject, DisplayObjectContainer Sprite,


DrawingCanvas .
DrawingCanvas Sprite,
DrawingCanvas :
public class DrawingCanvas extends Sprite

Sprite DisplayObjectContainer DisplayObject,


DrawingCanvas .
DrawingCanvas() Rectangle (bounds), ,
. initCanvas()
:
this.bounds = new Rectangle(0, 0, w, h);
initCanvas(fillColor, lineColor);

, initCanvas()
DrawingCanvas, :
this.lineColor = lineColor;
this.fillColor = fillColor;
this.width = 500;
this.height = 200;

initCanvas() drawBounds(),
graphics DrawingCanvas. graphics Shape.
this.graphics.clear();
this.graphics.lineStyle(1.0, this.lineColor, 1.0);
this.graphics.beginFill(this.fillColor, 1.0);
this.graphics.drawRect(bounds.left - 1,
bounds.top - 1,
bounds.width + 2,
bounds.height + 2);
this.graphics.endFill();


DrawingCanvas:

addShape() describeChildren(),
222;

moveToBack(), moveDown(), moveToFront() moveUp(),


225;

onMouseUp(),
224.

23.11.2012.

221

ACTIONSCRIPT 3.0

GeometricSprite
, ,
GeometricSprite:

CircleSprite
SquareSprite
TriangleSprite
GeometricSprite flash.display.Sprite:
public class GeometricSprite extends Sprite

GeometricSprite , GeometricSprite.
, . :
this.size = size;
this.lineColor = lColor;
this.fillColor = fColor;

geometricShape GeometricSprite IGeometricShape,


, . ,
IGeometricShape, GeometricShapes,
ActionScript 3.0.
GeometricSprite drawShape(),
GeometricSprite. .
.
GeometricSprite :

onMouseDown() onMouseUp(),
224;

showSelected() hideSelected(),
224.


Flash Player 9 , Adobe AIR 1.0
, addShape()
DrawingCanvas. GeometricSprite
GeometricSprite, :

23.11.2012.

222

ACTIONSCRIPT 3.0

public function addShape(shapeName:String, len:Number):void


{
var newShape:GeometricSprite;
switch (shapeName)
{
case "Triangle":
newShape = new TriangleSprite(len);
break;
case "Square":
newShape = new SquareSprite(len);
break;
case "Circle":
newShape = new CircleSprite(len);
break;
}
newShape.alpha = 0.8;
this.addChild(newShape);
}

drawShape(), graphics
( Sprite) . ,
drawShape() CircleSprite :
this.graphics.clear();
this.graphics.lineStyle(1.0, this.lineColor, 1.0);
this.graphics.beginFill(this.fillColor, 1.0);
var radius:Number = this.size / 2;
this.graphics.drawCircle(radius, radius, radius);

addShape() alpha (
DisplayObject) , ,
.
addChild()
DrawingCanvas, . ,
.
(selectedSpriteTxt outputTxt).
GeometricSprite,
. GeometricSprite
toString():
public override function toString():String
{
return this.shapeType + " of size " + this.size + " at " + this.x + ", " + this.y;
}

shapeType
GeometricSprite. , toString()
CircleSprite, DrawingCanvas:
Circle of size 50 at 0, 0

23.11.2012.

223

ACTIONSCRIPT 3.0

describeChildren() DrawingCanvas
. numChildren ( DisplayObjectContainer)
, for.
:
var desc:String = "";
var child:DisplayObject;
for (var i:int=0; i < this.numChildren; i++)
{
child = this.getChildAt(i);
desc += i + ": " + child + '\n';
}

text outputTxt.


Flash Player 9 , Adobe AIR 1.0
GeometricSprite,
onMouseDown(). ,
GeometricSprite:
this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);

onMouseDown() showSelected() GeometricSprite.


, Shape selectionIndicator
graphics Shape :
this.selectionIndicator = new Shape();
this.selectionIndicator.graphics.lineStyle(1.0, 0xFF0000, 1.0);
this.selectionIndicator.graphics.drawRect(-1, -1, this.size + 1, this.size + 1);
this.addChild(this.selectionIndicator);

onMouseDown() , selectionIndicator
visible ( DisplayObject) :
this.selectionIndicator.visible = true;

hideSelected() selectionIndicator
visible false.
onMouseDown() startDrag() (
Sprite), :
var boundsRect:Rectangle = this.parent.getRect(this.parent);
boundsRect.width -= this.size;
boundsRect.height -= this.size;
this.startDrag(false, boundsRect);

,
boundsRect.
, mouseUp.
DrawingCanvas :
this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);

23.11.2012.

224

ACTIONSCRIPT 3.0

DrawingCanvas, GeometricSprite.
, GeometricSprite
( GeometricSprite), .
(mouse up)
, . DrawingCanvas
.
onMouseUp() onMouseUp() GeometricSprite,
stopDrag() GeometricSprite.


Flash Player 9 , Adobe AIR 1.0
Move Back ( ), Move Down
( ), Move Up ( ) Move to Front ( ).
,
DrawingCanvas: moveToBack(), moveDown(), moveUp() moveToFront(). , moveToBack()
:
public function moveToBack(shape:GeometricSprite):void
{
var index:int = this.getChildIndex(shape);
if (index > 0)
{
this.setChildIndex(shape, 0);
}
}

setChildIndex() ( DisplayObjectContainer)
0
DrawingCanvas (this).
moveDown() , ,
1 DrawingCanvas:
public function moveDown(shape:GeometricSprite):void
{
var index:int = this.getChildIndex(shape);
if (index > 0)
{
this.setChildIndex(shape, index - 1);
}
}

moveUp() moveToFront() moveToBack() moveDown().

23.11.2012.

225

226

11.
Flash Player 9 , Adobe AIR 1.0
flash.geom , , ,
. ,
.


flash.geom


Flash Player 9 , Adobe AIR 1.0
flash.geom , , ,
. ,
, , .
,
. () (Y) .
x y,
.
, Stage, .

, . 0, 0 (
X Y), .
, .
X .
X.
, Flash Y
. Y.
,
X .
Y 0 .

Point.
Rectangle. Matrix
. , ,
,
.
. 186.

23.11.2012.

ACTIONSCRIPT 3.0


.
, (, 5, 12 17, -23).

x- y- .
, ,
.
, X Y.

0, 0.
. ,

ActionScript, , X Y ( ).
( 0, 0) .
.

.
.
, : , ,
, .
X , ActionScript.
Y , ActionScript.

Point
Flash Player 9 , Adobe AIR 1.0
Point .
, x , y .
Point x y :
import flash.geom.*;
var pt1:Point = new Point(10, 20); // x == 10; y == 20
var pt2:Point = new Point();
pt2.x = 10;
pt2.y = 20;


Flash Player 9 , Adobe AIR 1.0
Point
distance(). ,
circle1 circle2, :
import flash.geom.*;
var pt1:Point = new Point(circle1.x, circle1.y);
var pt2:Point = new Point(circle2.x, circle2.y);
var distance:Number = Point.distance(pt1, pt2);

23.11.2012.

227

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
. DisplayObject localToGlobal()
() , . ,
circle1
circle2, :
import flash.geom.*;
var pt1:Point = new Point(circle1.x, circle1.y);
pt1 = circle1.localToGlobal(pt1);
var pt2:Point = new Point(circle2.x, circle2.y);
pt2 = circle2.localToGlobal(pt2);
var distance:Number = Point.distance(pt1, pt2);

target
, localToGlobal() DisplayObject:
import flash.geom.*;
var stageCenter:Point = new Point();
stageCenter.x = this.stage.stageWidth / 2;
stageCenter.y = this.stage.stageHeight / 2;
var targetCenter:Point = new Point(target.x, target.y);
targetCenter = target.localToGlobal(targetCenter);
var distance:Number = Point.distance(stageCenter, targetCenter);


Flash Player 9 , Adobe AIR 1.0
polar()
Point. , myDisplayObject 100
60:
import flash.geom.*;
var distance:Number = 100;
var angle:Number = 2 * Math.PI * (90 / 360);
var translatePoint:Point = Point.polar(distance, angle);
myDisplayObject.x += translatePoint.x;
myDisplayObject.y += translatePoint.y;

Point
Flash Player 9 , Adobe AIR 1.0
Point .

23.11.2012.

228

229

ACTIONSCRIPT 3.0

DisplayObjectContainer

areInaccessibleObjectsUnderPoint()getObject
sUnderPoint()

BitmapData

hitTest()


BitmapData, ,
.

BitmapData

applyFilter()


,
.

copyChannel()
merge()
paletteMap()
pixelDissolve()
threshold()

Matrix

deltaTransformPoint()
transformPoint()

Rectangle

bottomRight

,

.
.

size
topLeft

Rectangle
Flash Player 9 , Adobe AIR 1.0
Rectangle . Rectangle
x y, width
height . Rectangle,
Rectangle() :
import flash.geom.Rectangle;
var rx:Number = 0;
var ry:Number = 0;
var rwidth:Number = 100;
var rheight:Number = 50;
var rect1:Rectangle = new Rectangle(rx, ry, rwidth, rheight);

Rectangle
Flash Player 9 , Adobe AIR 1.0
Rectangle.
Rectangle, x y.
Rectangle.

23.11.2012.

ACTIONSCRIPT 3.0

import flash.geom.Rectangle;
var x1:Number = 0;
var y1:Number = 0;
var width1:Number = 100;
var height1:Number = 50;
var rect1:Rectangle = new Rectangle(x1, y1, width1, height1);
trace(rect1) // (x=0, y=0, w=100, h=50)
rect1.x = 20;
rect1.y = 30;
trace(rect1); // (x=20, y=30, w=100, h=50)

, left top Rectangle


. x y left top
. , Rectangle ,
.
import flash.geom.Rectangle;
var x1:Number = 0;
var y1:Number = 0;
var width1:Number = 100;
var height1:Number = 50;
var rect1:Rectangle = new Rectangle(x1, y1, width1, height1);
trace(rect1) // (x=0, y=0, w=100, h=50)
rect1.left = 20;
rect1.top = 30;
trace(rect1); // (x=20, y=30, w=80, h=20)

, , bottom right
Rectangle , .
import flash.geom.Rectangle;
var x1:Number = 0;
var y1:Number = 0;
var width1:Number = 100;
var height1:Number = 50;
var rect1:Rectangle = new Rectangle(x1, y1, width1, height1);
trace(rect1) // (x=0, y=0, w=100, h=50)
rect1.right = 60;
trect1.bottom = 20;
trace(rect1); // (x=0, y=0, w=60, h=20)

Rectangle offset(), :
import flash.geom.Rectangle;
var x1:Number = 0;
var y1:Number = 0;
var width1:Number = 100;
var height1:Number = 50;
var rect1:Rectangle = new Rectangle(x1, y1, width1, height1);
trace(rect1) // (x=0, y=0, w=100, h=50)
rect1.offset(20, 30);
trace(rect1); // (x=20, y=30, w=100, h=50)

offsetPt() , ,
Point x y.

23.11.2012.

230

ACTIONSCRIPT 3.0

Rectangle inflate(),
, dx dy. dx ,
. dy ,
.
import flash.geom.Rectangle;
var x1:Number = 0;
var y1:Number = 0;
var width1:Number = 100;
var height1:Number = 50;
var rect1:Rectangle = new Rectangle(x1, y1, width1, height1);
trace(rect1) // (x=0, y=0, w=100, h=50)
rect1.inflate(6,4);
trace(rect1); // (x=-6, y=-4, w=112, h=58)

inflatePt() , ,
Point dx dy.

Rectangle
Flash Player 9 , Adobe AIR 1.0
, ,
union():
import flash.display.*;
import flash.geom.Rectangle;
var rect1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(rect1); // (x=0, y=0, w=100, h=100)
var rect2:Rectangle = new Rectangle(120, 60, 100, 100);
trace(rect2); // (x=120, y=60, w=100, h=100)
trace(rect1.union(rect2)); // (x=0, y=0, w=220, h=160)

, ,
intersection():
import flash.display.*;
import flash.geom.Rectangle;
var rect1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(rect1); // (x=0, y=0, w=100, h=100)
var rect2:Rectangle = new Rectangle(80, 60, 100, 100);
trace(rect2); // (x=120, y=60, w=100, h=100)
trace(rect1.intersection(rect2)); // (x=80, y=60, w=20, h=40)

intersects() .
intersects()
. , ,
, circle,
. , intersects()
circle , Rectangle target1
target2:

23.11.2012.

231

232

ACTIONSCRIPT 3.0

import flash.display.*;
import flash.geom.Rectangle;
var circle:Shape = new Shape();
circle.graphics.lineStyle(2, 0xFF0000);
circle.graphics.drawCircle(250, 250, 100);
addChild(circle);
var circleBounds:Rectangle = circle.getBounds(stage);
var target1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(circleBounds.intersects(target1)); // false
var target2:Rectangle = new Rectangle(0, 0, 300, 300);
trace(circleBounds.intersects(target2)); // true

intersects()
. getRect() DisplayObject
,
.

Rectangle
Flash Player 9 , Adobe AIR 1.0
Rectangle :

BitmapData

applyFilter(), colorTransform(),
copyChannel(), copyPixels(), draw(),
drawWithQuality(), encode(), fillRect(),
generateFilterRect(), getColorBoundsRect(),
getPixels(), merge(), paletteMap(),
pixelDissolve(), setPixels(), threshold()

,
BitmapData.

DisplayObject

getBounds(), getRect(), scrollRect,


scale9Grid

PrintJob

addPage()


printArea.

Sprite

startDrag()

bounds.

TextField

getCharBoundaries()

Transform

pixelBounds

Matrix
Flash Player 9 , Adobe AIR 1.0
Matrix ,
.
Matrix,
Matrix matrix Transform Transform
transform .
( x y), , .

23.11.2012.

ACTIONSCRIPT 3.0

, , Matrix (a, b, c, d, tx,


ty), createBox(). ,

. , Matrix,
2 3, 45,
10 20 :
var matrix:Matrix = new Matrix();
var scaleX:Number = 2.0;
var scaleY:Number = 3.0;
var rotation:Number = 2 * Math.PI * (45 / 360);
var tx:Number = 10;
var ty:Number = 20;
matrix.createBox(scaleX, scaleY, rotation, tx, ty);

scale(), rotate() translate(),


, Matrix. ,
Matrix. ,
Matrix, 4
60, scale() rotate() :
var matrix:Matrix = new Matrix();
var rotation:Number = 2 * Math.PI * (30 / 360); // 30
var scaleFactor:Number = 2;
matrix.scale(scaleFactor, scaleFactor);
matrix.rotate(rotation);
matrix.scale(scaleX, scaleY);
matrix.rotate(rotation);
myDisplayObject.transform.matrix = matrix;

Matrix b c.
b , c .
myMatrix 2:
var skewMatrix:Matrix = new Matrix();
skewMatrix.b = Math.tan(2);
myMatrix.concat(skewMatrix);

transform . ,

myDisplayObject:
var matrix:Matrix = myDisplayObject.transform.matrix;
var scaleFactor:Number = 2;
var rotation:Number = 2 * Math.PI * (60 / 360); // 60
matrix.scale(scaleFactor, scaleFactor);
matrix.rotate(rotation);
myDisplayObject.transform.matrix = matrix;

Matrix
myDisplayObject ( matrix transformation myDisplayObject).
, Matrix ,
.

23.11.2012.

233

ACTIONSCRIPT 3.0

. ColorTransform flash.geometry.
colorTransform Transform. -
, .
. ColorTransform c ActionScript 3.0 Adobe Flash Platform.

:

Flash Player 9 , Adobe AIR 1.0
DisplayObjectTransformer, ,
Matrix . :





,
.

Transform () .

23.11.2012.

234

235

ACTIONSCRIPT 3.0

, -45 50 %


www.adobe.com/go/learn_programmingAS3samples_flash_ru. DisplayObjectTransformer
Samples/DisplayObjectTransformer. .
File

DisplayObjectTransformer.mxml

Flash (FLA) Flex (MXML)

DisplayObjectTransformer.fla
com/example/programmingas3/geometry/MatrixTransformer.as

,
.

img/

, ,
.

MatrixTransformer
Flash Player 9 , Adobe AIR 1.0
MatrixTransformer ,
Matrix.
transform()
transform() :

sourceMatrix ,

xScale yScale x y

dx dy x y

rotation

skew

skewType ("right" "left")

.
transform() :

skew()

scale()

translate()

23.11.2012.

ACTIONSCRIPT 3.0

rotate()

.
skew()
skew() , b c.
unit
angle .
if (unit ==
{
angle =
}
if (unit ==
{
angle =
}

"degrees")
Math.PI * 2 * angle / 360;
"gradients")
Math.PI * 2 * angle / 100;

skewMatrix .
:
var skewMatrix:Matrix = new Matrix();

skewSide , .
"right", b :
skewMatrix.b = Math.tan(angle);

c:
skewMatrix.c = Math.tan(angle);

,
:
sourceMatrix.concat(skewMatrix);
return sourceMatrix;

scale()
, scale() ,
, scale() Matrix:
if (percent)
{
xScale = xScale / 100;
yScale = yScale / 100;
}
sourceMatrix.scale(xScale, yScale);
return sourceMatrix;

translate()
translate() dx dy
translate() , :
sourceMatrix.translate(dx, dy);
return sourceMatrix;

23.11.2012.

236

ACTIONSCRIPT 3.0

rotate()
rotate() (
), rotate() :
if (unit == "degrees")
{
angle = Math.PI * 2 * angle / 360;
}
if (unit == "gradients")
{
angle = Math.PI * 2 * angle / 100;
}
sourceMatrix.rotate(angle);
return sourceMatrix;

MatrixTransformer.transform()
Flash Player 9 , Adobe AIR 1.0
, .
matrix transform
Matrix.transform(), :
tempMatrix = MatrixTransformer.transform(tempMatrix,
xScaleSlider.value,
yScaleSlider.value,
dxSlider.value,
dySlider.value,
rotationSlider.value,
skewSlider.value,
skewSide );

matrix transform
, :
img.content.transform.matrix = tempMatrix;

23.11.2012.

237

238

12. API
Flash Player 9 , Adobe AIR 1.0

. API
ActionScript , , , .
.
, , ,
,
.


flash.display.Graphics

API-
Flash Player 9 , Adobe AIR 1.0
API , ActionScript, (,
, , ) ActionScript.
flash.display.Graphics. ActionScript
Shape, Sprite MovieClip, graphics,
. ( graphics Graphics.)
,
Graphics, ,
, , .
.
Graphics
, Math
.
Flash ( Flash Player 10, Adobe AIR 1.5 )
API- ,
. Graphics ,
API , API
252 API.

, API-
:
.
, .
, , .

23.11.2012.

ACTIONSCRIPT 3.0
API

, ,
.
, ,
.
,
( ).
. ,

ActionScript, x y ( ).
, .

( )
, .
.

.
, , .
.
X , ActionScript.
Y , ActionScript.

Graphics
Flash Player 9 , Adobe AIR 1.0
Shape, Sprite MovieClip graphics,
Graphics. Graphics , , .

Shape. Shape
, ,
Sprite MovieClip. , ,
, ,
Sprite.
. DisplayObject 185.


Flash Player 9 , Adobe AIR 1.0
, Graphics,
. ActionScript
:

;
;

23.11.2012.

239

ACTIONSCRIPT 3.0
API

, ( );
.


Flash Player 9 , Adobe AIR 1.0
graphics Shape, Sprite MovieClip
( , ).
ActionScript , ,
Adobe Flash Professional , .
lineStyle() lineGradientStyle().
lineStyle().
: , - . ,
myShape 2 ,
(0x990000), 75%:
myShape.graphics.lineStyle(2, 0x990000, .75);

- 1,0 (100%),
. lineStyle()
;
. Graphics.lineStyle() c
ActionScript 3.0 Adobe Flash Platform.
lineGradientStyle(). .
243.
beginFill(),
beginGradientFill(), beginBitmapFill() beginShaderFill(). ,
beginFill(), : () - .
,
(, myShape):
myShape.graphics.beginFill(0x00FF00);


. , , ,
.
.
Graphics , ,
. , .
Graphics , 0, 0 ,
.
moveTo().
.
: lineTo() (
) curveTo() ( ).
moveTo()
.

23.11.2012.

240

ACTIONSCRIPT 3.0
API

, , , endFill().
( , endFill()
), endFill() Flash
,
moveTo(). , endFill() ,
beginFill() ( ) .


Flash Player 9 , Adobe AIR 1.0
lineTo() Graphics ,
, .
, 100, 100, 200, 200
:
myShape.graphics.moveTo(100, 100);
myShape.graphics.lineTo(200, 200);

100 :
var triangleHeight:uint = 100;
var triangle:Shape = new Shape();
// red triangle, starting at point 0, 0
triangle.graphics.beginFill(0xFF0000);
triangle.graphics.moveTo(triangleHeight / 2, 0);
triangle.graphics.lineTo(triangleHeight, triangleHeight);
triangle.graphics.lineTo(0, triangleHeight);
triangle.graphics.lineTo(triangleHeight / 2, 0);
// green triangle, starting at point 200, 0
triangle.graphics.beginFill(0x00FF00);
triangle.graphics.moveTo(200 + triangleHeight / 2, 0);
triangle.graphics.lineTo(200 + triangleHeight, triangleHeight);
triangle.graphics.lineTo(200, triangleHeight);
triangle.graphics.lineTo(200 + triangleHeight / 2, 0);
this.addChild(triangle);


Flash Player 9 , Adobe AIR 1.0
curveTo() . ,
( )
( ). Graphics
. curveTo() : x y
x y . ,
, 100, 100 200, 200.
175, 125, , :
myShape.graphics.moveTo(100, 100);
myShape.graphics.curveTo(175, 125, 200, 200);

23.11.2012.

241

ACTIONSCRIPT 3.0
API

100
. , -
:
var size:uint = 100;
var roundObject:Shape = new Shape();
// red circular shape
roundObject.graphics.beginFill(0xFF0000);
roundObject.graphics.moveTo(size / 2, 0);
roundObject.graphics.curveTo(size, 0, size, size / 2);
roundObject.graphics.curveTo(size, size, size / 2, size);
roundObject.graphics.curveTo(0, size, 0, size / 2);
roundObject.graphics.curveTo(0, 0, size / 2, 0);
// green circular shape
roundObject.graphics.beginFill(0x00FF00);
roundObject.graphics.moveTo(200 + size / 2, 0);
roundObject.graphics.curveTo(200 + size, 0, 200 + size, size / 2);
roundObject.graphics.curveTo(200 + size, size, 200 + size / 2, size);
roundObject.graphics.curveTo(200, size, 200, size / 2);
roundObject.graphics.curveTo(200, 0, 200 + size / 2, 0);
this.addChild(roundObject);


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 ,
, , .
Graphics: drawCircle(), drawEllipse(), drawRect() drawRoundRect().
lineTo() curveTo(). , ,
.
, 100
. drawRect() , , 50% (0,5):
var squareSize:uint = 100;
var square:Shape = new Shape();
square.graphics.beginFill(0xFF0000, 0.5);
square.graphics.drawRect(0, 0, squareSize, squareSize);
square.graphics.beginFill(0x00FF00, 0.5);
square.graphics.drawRect(200, 0, squareSize, squareSize);
square.graphics.beginFill(0x0000FF, 0.5);
square.graphics.drawRect(400, 0, squareSize, squareSize);
square.graphics.endFill();
this.addChild(square);

23.11.2012.

242

ACTIONSCRIPT 3.0
API

Sprite MovieClip , graphics,


, . ,
graphics
Sprite MovieClip. , Sprite
graphics , TextField:
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0xFFCC00);
mySprite.graphics.drawCircle(30, 30, 30);
var label:TextField = new TextField();
label.width = 200;
label.text = "They call me mellow yellow...";
label.x = 20;
label.y = 20;
mySprite.addChild(label);
this.addChild(mySprite);

, TextField ,
.


Flash Player 9 , Adobe AIR 1.0

. lineGradientStyle(),
beginGradientFill().
. : , ,
- . ,
.

.
GradientType.LINEAR GradientType.RADIAL.

, .
.
. , .

-
.


. 0 255. ,
; 0 , 255 .
,
- .
,
.
Matrix. Matrix
createGradientBox() Matrix.

23.11.2012.

243

244

ACTIONSCRIPT 3.0
API

Matrix
Flash Player 9 , Adobe AIR 1.0
beginGradientFill()
lineGradientStyle() flash.display.Graphics.
.
createGradientBox()
Matrix, , . ,
, createGradientBox().
createGradientBox() .

: ( ), .
: ( ), .
: ( ), .
: ( ) .
: ( ) .
, :

GradientType.LINEAR

( ) ratios[0,

SpreadMethod.PAD

InterpolationMethod.LINEAR_RGB

255]

, rotation
createGradientBox():
width = 100;
height = 100;
rotation = 0;
tx = 0;
ty = 0;
width = 100;
height = 100;
rotation = Math.PI/4; // 45
tx = 0;
ty = 0;
width = 100;
height = 100;
rotation = Math.PI/2; // 90
tx = 0;
ty = 0;

( ),
rotation, tx ty createGradientBox():

23.11.2012.

ACTIONSCRIPT 3.0
API

width = 50;
height = 100;
rotation = 0;
tx = 0;
ty = 0;
width = 50;
height = 100;
rotation = 0
tx = 50;
ty = 0;
width = 100;
height = 50;
rotation = Math.PI/2; // 90
tx = 0;
ty = 0;
width = 100;
height = 50;
rotation = Math.PI/2; // 90
tx = 0;
ty = 50;

width, height, tx ty createGradientBox()


radial, :
width = 50;
height = 100;
rotation = 0;
tx = 25;
ty = 0;

23.11.2012.

245

ACTIONSCRIPT 3.0
API

import flash.display.Shape;
import flash.display.GradientType;
import flash.geom.Matrix;
var
var
var
var
var
var
var

type:String = GradientType.RADIAL;
colors:Array = [0x00FF00, 0x000088];
alphas:Array = [1, 1];
ratios:Array = [0, 255];
spreadMethod:String = SpreadMethod.PAD;
interp:String = InterpolationMethod.LINEAR_RGB;
focalPtRatio:Number = 0;

var matrix:Matrix = new Matrix();


var boxWidth:Number = 50;
var boxHeight:Number = 100;
var boxRotation:Number = Math.PI/2; // 90
var tx:Number = 25;
var ty:Number = 0;
matrix.createGradientBox(boxWidth, boxHeight, boxRotation, tx, ty);
var square:Shape = new Shape;
square.graphics.beginGradientFill(type,
colors,
alphas,
ratios,
matrix,
spreadMethod,
interp,
focalPtRatio);
square.graphics.drawRect(0, 0, 100, 100);
addChild(square);

,
, Graphics. Graphics
. Graphics,
drawRect(), ;
.

:
var myShape:Shape = new Shape();
var gradientBoxMatrix:Matrix = new Matrix();
gradientBoxMatrix.createGradientBox(100, 40, 0, 0, 0);
myShape.graphics.beginGradientFill(GradientType.LINEAR, [0xFF0000, 0x00FF00, 0x0000FF], [1,
1, 1], [0, 128, 255], gradientBoxMatrix);
myShape.graphics.drawRect(0, 0, 50, 40);
myShape.graphics.drawRect(0, 50, 100, 40);
myShape.graphics.drawRect(0, 100, 150, 40);
myShape.graphics.endFill();
this.addChild(myShape);

23.11.2012.

246

ACTIONSCRIPT 3.0
API

,
, . drawRect()
50, 100 150 . ,
beginGradientFill(), 100 . ,
, , , 50
, .
lineGradientStyle() beginGradientFill(), ,

lineStyle(). , :
var myShape:Shape = new Shape();
var gradientBoxMatrix:Matrix = new Matrix();
gradientBoxMatrix.createGradientBox(200, 40, 0, 0, 0);
myShape.graphics.lineStyle(5, 0);
myShape.graphics.lineGradientStyle(GradientType.LINEAR, [0xFF0000, 0x00FF00, 0x0000FF], [1,
1, 1], [0, 128, 255], gradientBoxMatrix);
myShape.graphics.drawRect(0, 0, 200, 40);
this.addChild(myShape);

Matrix . Matrix 232.

Math
Flash Player 9 , Adobe AIR 1.0
Graphics , ,
Math.
Math , Math.PI ( 3,14159265...),
, .
, Math.sin(), Math.cos(), Math.tan()
. ,
.
Math , .
Math:
var degrees = 121;
var radians = degrees * Math.PI / 180;
trace(radians) // 2.111848394913139

, Math.sin() Math.cos()
, .

23.11.2012.

247

ACTIONSCRIPT 3.0
API

var
var
var
var
var
var

sinWavePosition = 100;
cosWavePosition = 200;
sinWaveColor:uint = 0xFF0000;
cosWaveColor:uint = 0x00FF00;
waveMultiplier:Number = 10;
waveStretcher:Number = 5;

var i:uint;
for(i = 1; i < stage.stageWidth; i++)
{
var sinPosY:Number = Math.sin(i / waveStretcher) * waveMultiplier;
var cosPosY:Number = Math.cos(i / waveStretcher) * waveMultiplier;
graphics.beginFill(sinWaveColor);
graphics.drawRect(i, sinWavePosition + sinPosY, 2, 2);
graphics.beginFill(cosWaveColor);
graphics.drawRect(i, cosWavePosition + cosPosY, 2, 2);
}

API
Flash Player 9 , Adobe AIR 1.0
API
.
, .
, .
, (
Event.ENTER_FRAME)
.

23.11.2012.

248

ACTIONSCRIPT 3.0
API

stage.frameRate = 31;
var currentDegrees:Number = 0;
var radius:Number = 40;
var satelliteRadius:Number = 6;
var container:Sprite = new Sprite();
container.x = stage.stageWidth / 2;
container.y = stage.stageHeight / 2;
addChild(container);
var satellite:Shape = new Shape();
container.addChild(satellite);
addEventListener(Event.ENTER_FRAME, doEveryFrame);
function doEveryFrame(event:Event):void
{
currentDegrees += 4;
var radians:Number = getRadians(currentDegrees);
var posX:Number = Math.sin(radians) * radius;
var posY:Number = Math.cos(radians) * radius;
satellite.graphics.clear();
satellite.graphics.beginFill(0);
satellite.graphics.drawCircle(posX, posY, satelliteRadius);
}
function getRadians(degrees:Number):Number
{
return degrees * Math.PI / 180;
}

,
: currentDegrees, radius satelliteRadius. ,
radius / totalSatellites. ,
, API
.

API :

Flash Player 9 , Adobe AIR 1.0



, .. , .
:

API ;
, ;
.

23.11.2012.

249

250

ACTIONSCRIPT 3.0
API

,
Event.ENTER_FRAME. ,
, .

satellites.

www.adobe.com/go/learn_programmingAS3samples_flash_ru.
Samples/AlgorithmicVisualGenerator. .
File

AlgorithmicVisualGenerator.fla

Flash Professional
(FLA).

com/example/programmingas3/algorithmic/AlgorithmicVisualGenerator.as

,
,


,
.

com/example/programmingas3/algorithmic/ControlPanel.as

,
.

com/example/programmingas3/algorithmic/Satellite.as

, ,

,
.


Flash Player 9 , Adobe AIR 1.0
.
.
SWF-. SWF-,
doEveryFrame().


Flash Player 9 , Adobe AIR 1.0
, build().
clear(), satellites
. , .. build() ,
, , .
.
,
position, , color,
.
satellites .
doEveryFrame() .

23.11.2012.

ACTIONSCRIPT 3.0
API


Flash Player 9 , Adobe AIR 1.0
doEveryFrame() .
, SWF-.
, .
.
, position,
radius orbitRadius, .
, draw() Satellite
.
, i visibleSatellites.
,
, ,
. , , .
doEveryFrame() visibleSatellites
.


Flash Player 9 , Adobe AIR 1.0
, ControlPanel.
,
, .
changeSetting(). .
, ,
. ,
doEveryFrame() .


Flash Player 9 , Adobe AIR 1.0
,
API . ,
. ,
. .

doEveryFrame() .
doEveryFrame() .
, ; ,
Math.

23.11.2012.

251

ACTIONSCRIPT 3.0
API

API
Flash, .
, .
API ActionScript
.

API
Flash Player 10 , Adobe AIR 1.5
Flash Player 10, Adobe AIR 1.5 Flash
. API-

, . API
.
.
,
.
, Flash Player 10, :
253, 255,
257 drawTriangles() 259.
ActionScript API :

Vector ;
;
;

.

, .

Vector , . Vector
,
. Vector .
28.

.
, .
(, ) (,
).

, . (
) ( ).

23.11.2012.

252

ACTIONSCRIPT 3.0
API

GraphicsStroke: . ,
API- ,
API- .
GraphicsStroke.

Fill , , ,
flash.display.GraphicsBitmapFill flash.display.GraphicsGradientFill,
Graphics.drawGraphicsData(). Fill
- Graphics.beginBitmapFill()
Graphics.beginGradientFill().


Flash Player 10 , Adobe AIR 1.5
(. 239)
(Graphics.lineTo()) (Graphics.curveTo()),
(Graphics.moveTo()) .
API- ActionScript, Graphics.drawPath()
Graphics.drawTriangles(), .
Graphics.lineTo(), Graphics.curveTo()
Graphics.moveTo() Flash .
API Graphics.drawPath()
Graphics.drawTriangles() :

GraphicsPathCommand: GraphicsPathCommand
.
Graphics.drawPath(). ,
. ,
, .

:
. , GraphicsPathCommand
Vector, Vector.
Graphics.drawPath() Graphics.drawTriangles()
.
. ,
Graphics.drawPath() Graphics.moveTo(), Graphics.lineTo()
Graphics.curveTo(). ,
, GraphicsPathCommand. moveTo() 1,
lineTo() 2. Vector<int>
commands. Vector.<Number>
data. GraphicsPathCommand
, data,
.
. Vector Point.
, .
Graphics.drawPath() (
) Graphics:

23.11.2012.

253

ACTIONSCRIPT 3.0
API

package{
import flash.display.*;
public class DrawPathExample extends Sprite {
public function DrawPathExample(){
var square_commands:Vector.<int> = new Vector.<int>(5,true);
square_commands[0] = 1;//moveTo
square_commands[1] = 2;//lineTo
square_commands[2] = 2;
square_commands[3] = 2;
square_commands[4] = 2;
var square_coord:Vector.<Number> = new Vector.<Number>(10,true);
square_coord[0] = 20; //x
square_coord[1] = 10; //y
square_coord[2] = 50;
square_coord[3] = 10;
square_coord[4] = 50;
square_coord[5] = 40;
square_coord[6] = 20;
square_coord[7] = 40;
square_coord[8] = 20;
square_coord[9] = 10;
graphics.beginFill(0x442266);//set the color
graphics.drawPath(square_commands, square_coord);
}
}
}


, .
push():
package{
import flash.display.*;
public class DrawPathExample extends Sprite {
public function DrawPathExample(){
var square_commands:Vector.<int> = new Vector.<int>();
square_commands.push(1, 2, 2, 2, 2);
var square_coord:Vector.<Number> = new Vector.<Number>();
square_coord.push(20,10, 50,10, 50,40, 20,40, 20,10);
graphics.beginFill(0x442266);
graphics.drawPath(square_commands, square_coord);
}
}
}

23.11.2012.

254

ACTIONSCRIPT 3.0
API


Flash Player 10 , Adobe AIR 1.5
API- :
. ( )
( ). ,
, data.
A
0


A. . ( ) .
( )

, Graphics.drawPath() winding.
drawPath(commands:Vector.<int>, data:Vector.<Number>, winding:String = "evenOdd"):void

,
. ( GraphicsPathWinding
GraphicsPathWinding.EVEN_ODD GraphicsPathWinding.NON_ZERO.)
.
- ,
API . -
Graphics.drawPath(). -
.
. , , .
, ( )
, .
,
-. ,
.

23.11.2012.

255

ACTIONSCRIPT 3.0
API


A. - .


Flash Player 10 , Adobe AIR 1.5
, .
+1;
-1. , ,
. ,
. -
. .
.
, . ,
. , .


A. - .


Flash Player 10 , Adobe AIR 1.5
, . ,
. -,
.
. ActionScript
.

23.11.2012.

256

ACTIONSCRIPT 3.0
API

graphics.beginFill(0x60A0FF);
graphics.drawPath( Vector.<int>([1,2,2,2,2]), Vector.<Number>([66,10, 23,127, 122,50, 10,49,
109,127]),
GraphicsPathWinding.NON_ZERO);

,
A. -: 10 . -: 5 . : 5


Flash Player 10 , Adobe AIR 1.5
API- flash.display
IGraphicsData (, ). , IGraphicsData,
API- .
IGraphicsData :

GraphicsBitmapFill
GraphicsEndFill
GraphicsGradientFill
GraphicsPath
GraphicsShaderFill
GraphicsSolidFill
GraphicsStroke
GraphicsTrianglePath
IGraphicsData
(Vector.<IGraphicsData>),
.
, ,
. ActionScript IGraphicsData,
.
. API-
, flash.display.Graphics:

23.11.2012.

257

ACTIONSCRIPT 3.0
API

Graphics

Data

beginBitmapFill()

GraphicsBitmapFill

beginFill()

GraphicsSolidFill

beginGradientFill()

GraphicsGradientFill

beginShaderFill()

GraphicsShaderFill

lineBitmapStyle()

GraphicsStroke + GraphicsBitmapFill

lineGradientStyle()

GraphicsStroke + GraphicsGradientFill

lineShaderStyle()

GraphicsStroke + GraphicsShaderFill

lineStyle()

GraphicsStroke + GraphicsSolidFill

moveTo()

GraphicsPath

lineTo()
curveTo()
drawPath()
drawTriangles()

GraphicsTrianglePath

, GraphicsPath GraphicsPath.moveTo(),
GraphicsPath.lineTo(), GraphicsPath.curveTo(), GraphicsPath.wideLineTo()
GraphicsPath.wideMoveTo(), GraphicsPath.
.
IGraphicsData,
Graphics.drawGraphicsData(). Graphics.drawGraphicsData()
IGraphicsData API .
// stroke object
var stroke:GraphicsStroke = new GraphicsStroke(3);
stroke.joints = JointStyle.MITER;
stroke.fill = new GraphicsSolidFill(0x102020);// solid stroke
// fill object
var fill:GraphicsGradientFill = new GraphicsGradientFill();
fill.colors = [0x0000FF, 0xEEFFEE];
fill.matrix = new Matrix();
fill.matrix.createGradientBox(70,70, Math.PI/2);
// path object
var path:GraphicsPath = new GraphicsPath(new Vector.<int>(), new Vector.<Number>());
path.commands.push(1,2,2);
path.data.push(125,0, 50,100, 175,0);
// combine objects for complete drawing
var drawing:Vector.<IGraphicsData> = new Vector.<IGraphicsData>();
drawing.push(stroke, fill, path);
// draw the drawing
graphics.drawGraphicsData(drawing);

, ,
.

23.11.2012.

258

ACTIONSCRIPT 3.0
API

// draw the drawing multiple times


// change one value to modify each variation
graphics.drawGraphicsData(drawing);
path.data[2] += 200;
graphics.drawGraphicsData(drawing);
path.data[2] -= 150;
graphics.drawGraphicsData(drawing);
path.data[2] += 100;
graphics.drawGraphicsData(drawing);
path.data[2] -= 50;graphicsS.drawGraphicsData(drawing);

IGraphicsData ,
. , Graphics
, IGraphicsData .
. Graphics.clear()
, , .
IGraphicsData,
, .
,
, . ,
, ,
Graphics.lineTo() Graphics.moveTo().

drawTriangles()
Flash Player 10 , Adobe AIR 1.5
, Graphics.drawTriangles(), Flash Player 10 Adobe AIR
1.5, Graphics.drawPath(). Graphics.drawTriangles()
Vector.<Number> .
Graphics.drawTriangles()
ActionScript.
Graphics.drawTriangles() .
391.

23.11.2012.

259

260

13.

Flash Player 9 , Adobe AIR 1.0


ActionScript 3.0
, SWF.

.

(Renaun Erickson). ActionScript

. (Colin Moock) ActionScript 3. 26.


(O'Reilly Media, 2007)

(Mike Jones). Pushbutton


Flash & Math:
Flixel


Flash Player 9 , Adobe AIR 1.0
:
. , ,
(), .
: ,
.
,
, .
RGB, : , .
0 255. , ,
. , -,
: = 255, = 102, = 0.
.
. , .
, . ,
16 ,
48 . 48 ,
16 .
, .
, .
.

23.11.2012.

ACTIONSCRIPT 3.0


.
.
, Adobe BMP, GIF, JPG, PNG TIFF.
BMP
BMP ( )
Microsoft Windows. ,
.
GIF
GIF (. Graphics Interchange Format) 1987
CompuServe 256- ( 8 ).
, . - GIF ,
. GIF
, (). -
.
JPEG
JPEG ( JPG),
(. Joint Photographic Experts Group), ,
24 .
, ,
. JPEG ,
.
.
PNG
PNG (. Portable Network Graphics)
, GIF. PNG
64 , 16 . PNG
, . JPG, PNG
, .. . PNG-
-, 256 .
TIFF
TIFF (Tagged Image File Format)
PNG. TIFF
. ,
. TIFF
, ( CMYK).

GIF PNG (). .

23.11.2012.

261

ACTIONSCRIPT 3.0

GIF , 256
. PNG-, , 256
. , ,
.
ActionScript 3.0 , , BitmapData.
PNG, ActionScript 256 .

, :
(, , ) .
-.
ARGB , ,

, .
(
, ). ,
, ,
.
. ,
, .
, .
, .
.
RGB , ,

Bitmap BitmapData
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 Bitmap,
, BitmapData,
.


flash.display.Bitmap
flash.display.BitmapData

23.11.2012.

262

ACTIONSCRIPT 3.0

Bitmap
Flash Player 9 , Adobe AIR 1.0
DisplayObject, Bitmap ActionScript 3.0,
. , ,
flash.display.Loader Bitmap().
Bitmap GIF, JPEG PNG.
Bitmap BitmapData,
. Bitmap ,
.
.
162


Flash Player 9 , Adobe AIR 1.0
Bitmap
, .
pixelSnapping Bitmap , Bitmap .
, PixelSnapping: ALWAYS, AUTO NEVER.
:
myBitmap.pixelSnapping = PixelSnapping.ALWAYS;

.
smoothing BitmapData.
true, .
.

BitmapData
Flash Player 9 , Adobe AIR 1.0
BitmapData, flash.display,
.
. BitmapData ,
.
BitmapData :
var myBitmap:BitmapData = new BitmapData(width:Number, height:Number, transparent:Boolean,
fillColor:uinit);

width height . AIR 3 Flash


Player 11 BitmapData .
.

23.11.2012.

263

ACTIONSCRIPT 3.0

AIR 1.5 Flash Player 10 BitmapData 8,191


, 16,777,215. (. . BitmapData
8,191 , 2 048 .) Flash Player 9
, AIR 1.1 , 2 880
2 880 .
transparent , - (true) (false).
fillColor 32- , (
true). , BitmapData 50 :
var myBitmap:BitmapData = new BitmapData(150, 150, true, 0x80FF3300);

BitmapData Bitmap
Bitmap . BitmapData
Bitmap, bitmapData Bitmap.
,
addChild() addChildAt() , Bitmap.
.
171.
, BitmapData
Bitmap:
var myBitmapDataObject:BitmapData = new BitmapData(150, 150, false, 0xFF0000);
var myImage:Bitmap = new Bitmap(myBitmapDataObject);
addChild(myImage);


Flash Player 9 , Adobe AIR 1.0
BitmapData , .


Flash Player 9 , Adobe AIR 1.0

, .
getPixel().
getPixel() RGB x, y,
. - , , (-),
getPixel32(). RGB,
getPixel() , getPixel32(), ,
- () .
,
setPixel() setPixel32(). x, y
.

23.11.2012.

264

ACTIONSCRIPT 3.0

, setPixel() .
getPixel() 50, 50 .
import flash.display.Bitmap;
import flash.display.BitmapData;
var myBitmapData:BitmapData = new BitmapData(100, 100, false, 0x009900);
for (var i:uint = 0; i < 100; i++)
{
var red:uint = 0xFF0000;
myBitmapData.setPixel(50, i, red);
myBitmapData.setPixel(i, 50, red);
}
var myBitmapImage:Bitmap = new Bitmap(myBitmapData);
addChild(myBitmapImage);
var pixelValue:uint = myBitmapData.getPixel(50, 50);
trace(pixelValue.toString(16));

, ,
getPixels(). ,
. ( , )
32- .
, ( ) setPixels().
(rect inputByteArray),
(rect) (inputByteArray).
( ) inputByteArray
ByteArray.readUnsignedInt(). -
inputByteArray , , .
, ,
, , (ARGB) 32 .
getPixels() setPixels()
BitmapData .

23.11.2012.

265

ACTIONSCRIPT 3.0

import
import
import
import

flash.display.Bitmap;
flash.display.BitmapData;
flash.utils.ByteArray;
flash.geom.Rectangle;

var bitmapDataObject1:BitmapData = new BitmapData(100, 100, false, 0x006666FF);


var bitmapDataObject2:BitmapData = new BitmapData(100, 100, false, 0x00FF0000);
var rect:Rectangle = new Rectangle(0, 0, 100, 100);
var bytes:ByteArray = bitmapDataObject1.getPixels(rect);
bytes.position = 0;
bitmapDataObject2.setPixels(rect, bytes);
var bitmapImage1:Bitmap = new Bitmap(bitmapDataObject1);
addChild(bitmapImage1);
var bitmapImage2:Bitmap = new Bitmap(bitmapDataObject2);
addChild(bitmapImage2);
bitmapImage2.x = 110;


Flash Player 9 , Adobe AIR 1.0
BitmapData.hitTest()
.
BitmapData.hitTest() .

firstPoint (Point):

BitmapData, .

firstAlphaThreshold (uint): -,
.

secondObject (Object): , .
secondObject Rectangle, Point, Bitmap BitmapData.
, .

secondBitmapDataPoint (Point):

BitmapData. , secondObject
BitmapData. null.

secondAlphaThreshold (uint): , BitmapData.


1. , secondObject BitmapData
BitmapData .

, ActionScript
( ).

. , ActionScript - ,
.
,
( false, true).

23.11.2012.

266

ACTIONSCRIPT 3.0

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;
var bmd1:BitmapData = new BitmapData(100, 100, false, 0x000000FF);
var bmd2:BitmapData = new BitmapData(20, 20, false, 0x00FF3300);
var bm1:Bitmap = new Bitmap(bmd1);
this.addChild(bm1);
// Create a red square.
var redSquare1:Bitmap = new Bitmap(bmd2);
this.addChild(redSquare1);
redSquare1.x = 0;
// Create a second red square.
var redSquare2:Bitmap = new Bitmap(bmd2);
this.addChild(redSquare2);
redSquare2.x = 150;
redSquare2.y = 150;
// Define the
var pt1:Point
// Define the
var pt2:Point
// Define the
var pt3:Point

point
= new
point
= new
point
= new

at the top-left corner of the bitmap.


Point(0, 0);
at the center of redSquare1.
Point(20, 20);
at the center of redSquare2.
Point(160, 160);

trace(bmd1.hitTest(pt1, 0xFF, pt2)); // true


trace(bmd1.hitTest(pt1, 0xFF, pt3)); // false


Flash Player 9 , Adobe AIR 1.0
:
clone(), copyPixels(), copyChannel(), draw() drawWithQuality()( drawWithQuality
Flash Player 11.3 AIR 3.3 ).
, clone() , ,
BitmapData .
BitmapData, .
, () .

23.11.2012.

267

ACTIONSCRIPT 3.0

import flash.display.Bitmap;
import flash.display.BitmapData;
var myParentSquareBitmap:BitmapData = new BitmapData(100, 100, false, 0x00ff3300);
var myClonedChild:BitmapData = myParentSquareBitmap.clone();
var myParentSquareContainer:Bitmap = new Bitmap(myParentSquareBitmap);
this.addChild(myParentSquareContainer);
var myClonedChildContainer:Bitmap = new Bitmap(myClonedChild);
this.addChild(myClonedChildContainer);
myClonedChildContainer.x = 110;

copyPixels()
BitmapData . ( sourceRect)
.
destPoint.
copyChannel() (, , )
BitmapData BitmapData.
BitmapData .
draw() drawWithQuality(), ,
, .
matrix, colorTransform, blendMode clipRect ( )
. Flash
Player AIR.
draw() drawWithQuality() (,
) , .
myBitmap.draw(movieClip);

- (, ..) , ,
. ,
transform transform Bitmap,
BitmapData.


Flash Player 11.3 , AIR 3.3
flash.display.BitmapData.encode()
.

PNG PNG, ,
, .
PNG, flash.display.PNGEncoderOptions
BitmapData.encode().

JPEG JPEG .
JPEG, flash.display.JPEGEncoderOptions
BitmapData.encode().

23.11.2012.

268

ACTIONSCRIPT 3.0

JPEGXR JPEG (XR);


, .
JPEGXR, flash.display.JPEGXREncoderOptions
BitmapData.encode().

.
BitmapData JPEGEncoderOptions:
// Compress a BitmapData object as a JPEG file.
var bitmapData:BitmapData = new BitmapData(640,480,false,0x00FF00);
var byteArray:ByteArray = new ByteArray();
bitmapData.encode(new Rectangle(0,0,640,480), new flash.display.JPEGEncoderOptions(),
byteArray);


Flash Player 9 , Adobe AIR 1.0

noise() perlinNoise(). ,
.
noise().
.
.

randomSeed (int): , . ,

, .
Math.random().
.

low (uint): , ( 0 255).


0. ,
.

high (uint): , ( 0 255).


255.
, .

channelOptions (uint): , .
ARGB. 7.

grayScale (Boolean): true randomSeed

. -.
false.
, .

23.11.2012.

269

ACTIONSCRIPT 3.0

package
{
import
import
import
import

flash.display.Sprite;
flash.display.Bitmap;
flash.display.BitmapData;
flash.display.BitmapDataChannel;

public class BitmapNoise1 extends Sprite


{
public function BitmapNoise1()
{
var myBitmap:BitmapData = new BitmapData(250, 250,false, 0xff000000);
myBitmap.noise(500, 0, 255, BitmapDataChannel.BLUE,false);
var image:Bitmap = new Bitmap(myBitmap);
addChild(image);
}
}
}

, perlinNoise() .
perlinNoise() , ,
, , .
perlinNoise() , ,
. ,
, ,
. - ,
.
( ).

baseX (Number): x () .

baseY (Number): y () .

numOctaves (uint): ,

.
, .

randomSeed (int): , noise().

Math.random().
.

stitch (Boolean): true


, .

fractalNoise (Boolean): , .
true , . false

. ,
,
.

channelOptions (uint): channelOptions , noise().

, ( ) .
ARGB. 7.

23.11.2012.

270

ACTIONSCRIPT 3.0

grayScale (Boolean): grayScale , noise().


true randomSeed

. false.

offsets (Array): , x y .

, .
. null.
BitmapData 150 150 ,
perlinNoise().
package
{
import
import
import
import

flash.display.Sprite;
flash.display.Bitmap;
flash.display.BitmapData;
flash.display.BitmapDataChannel;

public class BitmapNoise2 extends Sprite


{
public function BitmapNoise2()
{
var myBitmapDataObject:BitmapData =
new BitmapData(150, 150, false, 0x00FF0000);
var seed:Number = Math.floor(Math.random() * 100);
var channels:uint = BitmapDataChannel.GREEN | BitmapDataChannel.BLUE
myBitmapDataObject.perlinNoise(100, 80, 6, seed, false, true, channels, false, null);
var myBitmap:Bitmap = new Bitmap(myBitmapDataObject);
addChild(myBitmap);
}
}
}


Flash Player 9 , Adobe AIR 1.0
, , , ,
( ).
,
. scroll().
scroll() ,
(x, y). ,
. ( enterFrame)
.

23.11.2012.

271

ACTIONSCRIPT 3.0

, ( )
, . scroll()
enterFrame, .
,
.
import flash.display.Bitmap;
import flash.display.BitmapData;
var myBitmapDataObject:BitmapData = new BitmapData(1000, 1000, false, 0x00FF0000);
var seed:Number = Math.floor(Math.random() * 100);
var channels:uint = BitmapDataChannel.GREEN | BitmapDataChannel.BLUE;
myBitmapDataObject.perlinNoise(100, 80, 6, seed, false, true, channels, false, null);
var myBitmap:Bitmap = new Bitmap(myBitmapDataObject);
myBitmap.x = -750;
myBitmap.y = -750;
addChild(myBitmap);
addEventListener(Event.ENTER_FRAME, scrollBitmap);
function scrollBitmap(event:Event):void
{
myBitmapDataObject.scroll(1, 1);
}


Flash Player 9 , Adobe AIR 1.0
(mipmaps) ,
.
MIP , .
, MIP, 64 64
. MIP 32 32,
16 16, 8 8, 4 4, 2 2 1 1 .
, ,
,
. ,
, .
.
Flash Player 9.115.0 AIR

( 50 %).
Flash Player 11.3 AIR 3.3
streamingLevels Context3D.createCubeTexture() Context3D.createTexture().

23.11.2012.

272

ACTIONSCRIPT 3.0


,
. , ,
. Flash Player 11.4 AIR 3.4
, ,
.
.

. Context3D.createTexture(),
flash.display3D.Context3DTextureFormat.COMPRESSED
flash.display3D.Context3DTextureFormat.COMPRESSED_ALPHA .

flash.display3D.textures.Texture, createTexture(),
flash.display3D.textures.Texture.uploadFromBitmapData()
flash.display3D.textures.Texture.uploadFromByteArray().
.
:

( JPEG, GIF PNG), Loader ActionScript 3.0


, Flash Professional
BitmapData
, loadMovie() ActionScript 2.0
, , ,
. ,
,
.
,
, .

smoothing Video true (.


Video).

smoothing true,
.

, 4 8 (, 640 x
128, : 320 x 64 > 160 x 32 > 80 x 16 > 40 x 8 > 20 x 4 > 10 x 2 >
5 x 1).
MIP, ,
2 ( 2^n). , 1024 x 1024 .
MIP 512 x 512, 256 x 256,
128 x 128 1 x 1 , MIP 11 .
,
.

23.11.2012.

273

274

ACTIONSCRIPT 3.0

:

Flash Player 9 , Adobe AIR 1.0
Bitmap
( BitmapData).
,
. , , .

.

.



www.adobe.com/go/learn_programmingAS3samples_flash_ru.
Samples/SpinningMoon. .
File

SpinningMoon.mxml

Flex (MXML) Flash (FLA).

SpinningMoon.fla
com/example/programmingas3/moon/MoonSphere.as

, , .

moonMap.png

,
.


Flash Player 9 , Adobe AIR 1.0

. MoonSphere:
MoonSphere(), , imageLoadComplete(),
.
SWF-: ,
flash.display.Loader. MoonSphere(),
, :
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoadComplete);
imageLoader.load(new URLRequest("moonMap.png"));

Loader imageLoader.
, load() Loader, URLRequest URL-
. ,
. , addEventListener()
Loader, , , contentLoaderInfo Loader. Loader

23.11.2012.

ACTIONSCRIPT 3.0

, . contentLoaderInfo
LoaderInfo, Loader (
). LoaderInfo ,
, complete (Event.COMPLETE),
imageLoadComplete(), .
, ,
, . ,
imageLoadComplete().
. . ,
.
Loader, Bitmap,
Loader.
Loader ,
. imageLoadComplete() :
private function imageLoadComplete(event:Event):void
{
textureMap = event.target.content.bitmapData;
...
}

, event Event.
Event target, ,
( LoaderInfo, addEventListener(),
). LoaderInfo, , content, (
) Bitmap .
, Bitmap
(event.target.content) . ( Loader
.) ,
, . ,
imageLoadComplete() bitmapData Bitmap
(event.target.content.bitmapData), textureMap,
. . .

23.11.2012.

275

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, ,
. ,
. ,
. ,
.

, , .
,
.
, . ,
, ,
.
,
. ,
.
. .
ActionScript. -,
, BitmapData textureMap. ,
textureMap , .
:
textureMap = event.target.content.bitmapData;

textureMap . ,
Bitmap sphere,
, . textureMap, sphere
imageLoadComplete() :
sphere = new Bitmap();
sphere.bitmapData = new BitmapData(textureMap.width / 2, textureMap.height);
sphere.bitmapData.copyPixels(textureMap,
new Rectangle(0, 0, sphere.width, sphere.height),
new Point(0, 0));

23.11.2012.

276

ACTIONSCRIPT 3.0

, sphere. bitmapData ( ,
sphere)
textureMap. , sphere ,
( textureMap ).
bitmapData copyPixels().
copyPixels() .

, textureMap.
( Rectangle) , textureMap .
textureMap,
Rectangle(): 0, 0, width
height sphere.

( Point x y, 0)
: (0, 0) sphere.bitmapData.
, textureMap, ,
sphere. , BitmapData sphere
textureMap, .

, sphere ,
sphere.
, sphere ,
. imageLoadComplete(). Timer
rotationTimer, :
var rotationTimer:Timer = new Timer(15);
rotationTimer.addEventListener(TimerEvent.TIMER, rotateMoon);
rotationTimer.start();

Timer rotationTimer. ,
Timer(), , rotationTimer timer 15 .
addEventListener() , timer
(TimerEvent.TIMER) rotateMoon(). ,
start().
- rotationTimer Flash Player rotateMoon()
MoonSphere 15 , .
rotateMoon() :

23.11.2012.

277

ACTIONSCRIPT 3.0

private function rotateMoon(event:TimerEvent):void


{
sourceX += 1;
if (sourceX > textureMap.width / 2)
{
sourceX = 0;
}
sphere.Data.copyPixels(textureMap,
new Rectangle(sourceX, 0, sphere.width, sphere.height),
new Point(0, 0));
event.updateAfterEvent();
}

.
1 sourceX ( 0) 1.
sourceX += 1;

, sourceX textureMap,
sphere,
textureMap . .
, .

, ,
. ,
sphere, , .
(textureMap). ,
, ,
, .

23.11.2012.

278

ACTIONSCRIPT 3.0

2 .

textureMap, ,
sphere, .

:
if (sourceX >= textureMap.width / 2)
{
sourceX = 0;
}

, sourceX ( ) textureMap.
, sourceX 0,
textureMap, :

3 sourceX

sphere.
, sphere ( ).
new Rectangle()
sourceX:
sphere.bitmapData.copyPixels(textureMap,
new Rectangle(sourceX, 0, sphere.width, sphere.height),
new Point(0, 0));

, 15 .
, sphere, ,
sphere, , . , ,
.

23.11.2012.

279

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, , . ,
.
: , ,
.
-, MoonSphere,
, . Shape
MoonSphere.
moonMask = new Shape();
moonMask.graphics.beginFill(0);
moonMask.graphics.drawCircle(0, 0, radius);
this.addChild(moonMask);
this.mask = moonMask;

, - , MoonSphere ( Sprite),
MoonSphere mask.

-
. - :
, . ,
.
,
. , .
, .
,
. ,
, . ,
().
displaceFilter:
var displaceFilter:DisplacementMapFilter;
displaceFilter = new DisplacementMapFilter(fisheyeLens,
new Point(radius, 0),
BitmapDataChannel.RED,
BitmapDataChannel.GREEN,
radius, 0);

23.11.2012.

280

ACTIONSCRIPT 3.0

fisheyeLens .
BitmapData, .
281.
, ,

. sphere, -
imageLoadComplete():
sphere.filters = [displaceFilter];

( ) .

BitmapData
. , ,
Bitmap ( ),
( ). , Bitmap
, , .
: Bitmap , ,
BitmapData , .
BitmapData ( , -
, ). ,
Bitmap
( ).
bitmapData Bitmap,
. ,
Bitmap, .
ActionScript .
288.


Flash Player 9 , Adobe AIR 1.0
, .
, .
Bitmap sphere. ,
. .
, .. x,
y , ( )
, .

23.11.2012.

281

ACTIONSCRIPT 3.0

, ,
: ,
() , .

,
imageLoadComplete() ( , ).
fisheyeLens createFisheyeMap()
MoonSphere:
var fisheyeLens:BitmapData = createFisheyeMap(radius);

createFisheyeMap()
setPixel() BitmapData. createFisheyeMap()
, :
private function createFisheyeMap(radius:int):BitmapData
{
var diameter:int = 2 * radius;
var result:BitmapData = new BitmapData(diameter,
diameter,
false,
0x808080);
// Loop through the pixels in the image one by one
for (var i:int = 0; i < diameter; i++)
{
for (var j:int = 0; j < diameter; j++)
{
// Calculate the x and y distances of this pixel from
// the center of the circle (as a percentage of the radius).
var pctX:Number = (i - radius) / radius;
var pctY:Number = (j - radius) / radius;
// Calculate the linear distance of this pixel from
// the center of the circle (as a percentage of the radius).
var pctDistance:Number = Math.sqrt(pctX * pctX + pctY * pctY);
// If the current pixel is inside the circle,

23.11.2012.

282

ACTIONSCRIPT 3.0

// set its color.


if (pctDistance < 1)
{
// Calculate the appropriate color depending on the
// distance of this pixel from the center of the circle.
var red:int;
var green:int;
var blue:int;
var rgb:uint;
red = 128 * (1 + 0.75 * pctX * pctX * pctX / (1 - pctY * pctY));
green = 0;
blue = 0;
rgb = (red << 16 | green << 8 | blue);
// Set the pixel to the calculated color.
result.setPixel(i, j, rgb);
}
}
}
return result;
}

-, radius, .
BitmapData, . , result,
.
, result , ,
( false) 0x808080 ():
var result:BitmapData = new BitmapData(diameter,
diameter,
false,
0x808080);

.
( i ,
),
( j ).
( ):
for (var i:int = 0; i < diameter; i++)
{
for (var j:int = 0; j < diameter; j++)
{
...
}
}

(
). .
1 (i - radius).

, ,
((i - radius) / radius). pctX,
pctY,
.
var pctX:Number = (i - radius) / radius;
var pctY:Number = (j - radius) / radius;

23.11.2012.

283

ACTIONSCRIPT 3.0

, pctX pctY.
pctDistance:
var pctDistance:Number = Math.sqrt(pctX * pctX + pctY * pctY);

3 , (. . 100 % ,

, ). ,
( , 4).
, , :
if (pctDistance < 1)
{
...
}

4 , , .

, (0 % ) - (100 % ) .
(, ):
red = 128 * (1 + 0.75 * pctX * pctX * pctX / (1 - pctY * pctY));
green = 0;
blue = 0;

, - ( red).
( green blue) ,
. ,
.
,
:
rgb = (red << 16 | green << 8 | blue);

, ,
setPixel() BitmapData result:
result.setPixel(i, j, rgb);

Flash Player 11 , Adobe AIR 2.6



.
, .
,
Loader COMPLETE. ,
.
ImageDecodingPolicy flash.system
. .

23.11.2012.

284

285

ACTIONSCRIPT 3.0

ImageDecodingPolicy.ON_DEMAND



.


. ,
,

.

ImageDecodingPolicy.ON_LOAD



COMPLETE.

( 10
).

AIR


.

. ON_LOAD,
COMPLETE.
ImageDecodingPolicy.
var loaderContext:LoaderContext = new LoaderContext();
loaderContext.imageDecodingPolicy = ImageDecodingPolicy.ON_LOAD
var loader:Loader = new Loader();
loader.load(new URLRequest("http://www.adobe.com/myimage.png"), loaderContext);

ON_DEMAND Loader.load()
Loader.loadBytes(). , LoaderContext
, ImageDecodingPolicy .

.

23.11.2012.

ACTIONSCRIPT 3.0

package
{
import
import
import
import
import
import

flash.display.Loader;
flash.display.Sprite;
flash.events.Event;
flash.net.URLRequest;
flash.system.ImageDecodingPolicy;
flash.system.LoaderContext;

public class AsyncTest extends Sprite


{
private var loaderContext:LoaderContext;
private var loader:Loader;
private var urlRequest:URLRequest;
public function AsyncTest()
{
//Load the image synchronously
loaderContext = new LoaderContext();
//Default behavior.
loaderContext.imageDecodingPolicy = ImageDecodingPolicy.ON_DEMAND;
loader = new Loader();
loadImageSync();
//Load the image asynchronously
loaderContext = new LoaderContext();
loaderContext.imageDecodingPolicy = ImageDecodingPolicy.ON_LOAD;
loader = new Loader();
loadImageASync();
}
private function loadImageASync():void{
trace("Loading image asynchronously...");
urlRequest = new URLRequest("http://www.adobe.com/myimage.png");
urlRequest.useCache = false;
loader.load(urlRequest, loaderContext);
loader.contentLoaderInfo.addEventListener
(Event.COMPLETE, onAsyncLoadComplete);

23.11.2012.

286

ACTIONSCRIPT 3.0

}
private function onAsyncLoadComplete(event:Event):void{
trace("Async. Image Load Complete");
}
private function loadImageSync():void{
trace("Loading image synchronously...");
urlRequest = new URLRequest("http://www.adobe.com/myimage.png");
urlRequest.useCache = false;
loader.load(urlRequest, loaderContext);
loader.contentLoaderInfo.addEventListener
(Event.COMPLETE, onSyncLoadComplete);
}
private function onSyncLoadComplete(event:Event):void{
trace("Sync. Image Load Complete");
}
}
}


(Thibaud Imbert). Adobe Flash

23.11.2012.

287

288

14.

Flash Player 9 , Adobe AIR 1.0



( Adobe Photoshop
Adobe Fireworks). ActionScript 3.0 flash.filters,
.
,
, .


Flash Player 9 , Adobe AIR 1.0

. , ,
, , . ActionScript 3.0 ,
BitmapData.
, , ,
.
.
, Pixel Bender. . Pixel Bender
323.

, .
,
. .
.

.
.
Matrix ,


flash.filters
flash.display.DisplayObject.filters
flash.display.BitmapData.applyFilter()

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
(
). .
, .
,
filters . BitmapData applyFilter().


Flash Player 9 , Adobe AIR 1.0
, .
, DropShadowFilter, :
import flash.filters.DropShadowFilter;
var myFilter:DropShadowFilter = new DropShadowFilter();

, DropShadowFilter() ( )
,
.


Flash Player 9 , Adobe AIR 1.0
BitmapData.
, .

, filters.
filters Array,
, . ,
, Array Array filters
:

23.11.2012.

289

ACTIONSCRIPT 3.0

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.filters.DropShadowFilter;
// Create a bitmapData object and render it to screen
var myBitmapData:BitmapData = new BitmapData(100,100,false,0xFFFF3300);
var myDisplayObject:Bitmap = new Bitmap(myBitmapData);
addChild(myDisplayObject);
// Create a DropShadowFilter instance.
var dropShadow:DropShadowFilter = new DropShadowFilter();
// Create the filters array, adding the filter to the array by passing it as
// a parameter to the Array() constructor.
var filtersArray:Array = new Array(dropShadow);
// Assign the filters array to the display object to apply the filter.
myDisplayObject.filters = filtersArray;

, Array
filters. Array ,
. ,
:
import flash.filters.BevelFilter;
import flash.filters.GlowFilter;
// Create the filters and add them to an array.
var bevel:BevelFilter = new BevelFilter();
var glow:GlowFilter = new GlowFilter();
var filtersArray:Array = new Array(bevel, glow);
// Assign the filters array to the display object to apply the filter.
myDisplayObject.filters = filtersArray;

, , new Array() (
), Array,
([]). , :
var filters:Array = new Array(dropShadow, blur);

,
var filters:Array = [dropShadow, blur];

,
. , ( ,
, , ),
, . - ,
. ,
.
,
. ,
myDisplayObject:
myDisplayObject.filters = [new BlurFilter()];

23.11.2012.

290

ACTIONSCRIPT 3.0

Array Array ( ),
BlurFilter Array Array filters
myDisplayObject.

,
filters:
myDisplayObject.filters = null;

,
, filters. .
291.
BitmapData
BitmapData applyFilter()
BitmapData:
var rect:Rectangle = new Rectangle();
var origin:Point = new Point();
myBitmapData.applyFilter(sourceBitmapData, rect, origin, new BlurFilter());

applyFilter() BitmapData,
. ;
BitmapData,
applyFilter().


Flash Player 9 , Adobe AIR 1.0

.

, .

.
, , :
, ,
. . ,
.


Flash Player 9 , Adobe AIR 1.0
.

23.11.2012.

291

ACTIONSCRIPT 3.0


,
. , cacheAsBitmap
false, cacheAsBitmap true.
, cacheAsBitmap
.

,
filters.
, ,
, filters ,
. filters
Array .
filters .
. , filters
.

,
, . myDisplayObject
; addFilters().
myDisplayObject :
import flash.events.MouseEvent;
import flash.filters.*;
myDisplayObject.filters = [new GlowFilter()];
function addFilters(event:MouseEvent):void
{
// Make a copy of the filters array.
var filtersCopy:Array = myDisplayObject.filters;
// Make desired changes to the filters (in this case, adding filters).
filtersCopy.push(new BlurFilter());
filtersCopy.push(new DropShadowFilter());
// Apply the changes by reassigning the array to the filters property.
myDisplayObject.filters = filtersCopy;
}
myDisplayObject.addEventListener(MouseEvent.CLICK, addFilters);


,
, ,
,
filters . 33
.

23.11.2012.

292

ACTIONSCRIPT 3.0

(,
). pop() Array :
// Example of removing the top-most filter from a display object
// named "filteredObject".
var tempFilters:Array = filteredObject.filters;
// Remove the last element from the Array (the top-most filter).
tempFilters.pop();
// Apply the new set of filters to the display object.
filteredObject.filters = tempFilters;

, ( , ),
, shift() Array pop().
(, ),
splice(). ( )
. , ( 1) :
// Example of removing a filter from the middle of a stack of filters
// applied to a display object named "filteredObject".
var tempFilters:Array = filteredObject.filters;
// Remove the second filter from the array. It's the item at index 1
// because Array indexes start from 0.
// The first "1" indicates the index of the filter to remove; the
// second "1" indicates how many elements to remove.
tempFilters.splice(1, 1);
// Apply the new set of filters to the display object.
filteredObject.filters = tempFilters;


, , .
( ), .
,
. ,
, ( ),
, , (
). , Array (
Array.pop() ).
, , ,
,
, , . , ,
, .

23.11.2012.

293

ACTIONSCRIPT 3.0

// Example of removing a glow filter from a set of filters, where the


//filter you want to remove is the only GlowFilter instance applied
// to the filtered object.
var tempFilters:Array = filteredObject.filters;
// Loop through the filters to find the index of the GlowFilter instance.
var glowIndex:int;
var numFilters:int = tempFilters.length;
for (var i:int = 0; i < numFilters; i++)
{
if (tempFilters[i] is GlowFilter)
{
glowIndex = i;
break;
}
}
// Remove the glow filter from the array.
tempFilters.splice(glowIndex, 1);
// Apply the new set of filters to the display object.
filteredObject.filters = tempFilters;

, , , ,
,
.
, filters .
,
. ,
. ,
. ,
, ,
.

23.11.2012.

294

ACTIONSCRIPT 3.0

//
//
//
//

Example of removing a filter from a set of


filters, where there may be more than one
of that type of filter applied to the filtered
object, and you only want to remove one.

// A master list of filters is stored in a separate,


// persistent Array variable.
var masterFilterList:Array;
// At some point, you store a reference to the filter you
// want to remove.
var filterToRemove:ConvolutionFilter;
// ... assume the filters have been added to masterFilterList,
// which is then assigned as the filteredObject.filters:
filteredObject.filters = masterFilterList;
// ... later, when it's time to remove the filter, this code gets called:
// Loop through the filters to find the index of masterFilterList.
var removeIndex:int = -1;
var numFilters:int = masterFilterList.length;
for (var i:int = 0; i < numFilters; i++)
{
if (masterFilterList[i] == filterToRemove)
{
removeIndex = i;
break;
}
}
if (removeIndex >= 0)
{
// Remove the filter from the array.
masterFilterList.splice(removeIndex, 1);
// Apply the new set of filters to the display object.
filteredObject.filters = masterFilterList;
}

( ,
, ) .
, ,
filters . ,
filters,
. ( ) .
filters ,
, . ,
filterToRemove,
, .

23.11.2012.

295

ACTIONSCRIPT 3.0


(, ),
,
( ).
DisplayObject ,
. ,
, .
, ;
( scaleX scaleY 100 %),
. , , ,
, .
,
BitmapData,
.
Bitmap
BitmapData , cacheAsBitmap
true. , ,
.
( )
. ,
, .
, cacheAsBitmap ,
.


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 ,
BitmapData:

( BevelFilter);
( BlurFilter);
( DropShadowFilter);
( GlowFilter);
( GradientBevelFilter);
( GradientGlowFilter);
( ColorMatrixFilter);
( ConvolutionFilter);
( DisplacementMapFilter);
( ShaderFilter).

23.11.2012.

296

ACTIONSCRIPT 3.0

,
.
ActionScript. Flash Professional .
, , ActionScript, Flash
Professional, ,
, .
ActionScript. (
, , )
, . ,
, . ,

, , , , ,
..
( ) .
.
. , ,
, ,
. ,
. , ,
.
, . flash.filters
c ActionScript 3.0 Flash Platform.


Flash Player 9 , Adobe AIR 1.0
BevelFilter .
.
BevelFilter .
, , . .
.

23.11.2012.

297

ACTIONSCRIPT 3.0

import
import
import
import
import

flash.display.*;
flash.filters.BevelFilter;
flash.filters.BitmapFilterQuality;
flash.filters.BitmapFilterType;
flash.net.URLRequest;

// Load an image onto the Stage.


var imageLoader:Loader = new Loader();
var url:String = "http://www.helpexamples.com/flash/images/image3.jpg";
var urlReq:URLRequest = new URLRequest(url);
imageLoader.load(urlReq);
addChild(imageLoader);
// Create the bevel filter and set filter properties.
var bevel:BevelFilter = new BevelFilter();
bevel.distance = 5;
bevel.angle = 45;
bevel.highlightColor = 0xFFFF00;
bevel.highlightAlpha = 0.8;
bevel.shadowColor = 0x666666;
bevel.shadowAlpha = 0.8;
bevel.blurX = 5;
bevel.blurY = 5;
bevel.strength = 5;
bevel.quality = BitmapFilterQuality.HIGH;
bevel.type = BitmapFilterType.INNER;
bevel.knockout = false;
// Apply filter to the image.
imageLoader.filters = [bevel];


Flash Player 9 , Adobe AIR 1.0
BlurFilter , .
, , , ,
. quality ,
, .
quality, , .
drawCircle() , Graphics,
:

23.11.2012.

298

ACTIONSCRIPT 3.0

import flash.display.Sprite;
import flash.filters.BitmapFilterQuality;
import flash.filters.BlurFilter;
// Draw a circle.
var redDotCutout:Sprite = new Sprite();
redDotCutout.graphics.lineStyle();
redDotCutout.graphics.beginFill(0xFF0000);
redDotCutout.graphics.drawCircle(145, 90, 25);
redDotCutout.graphics.endFill();
// Add the circle to the display list.
addChild(redDotCutout);
// Apply the blur filter to the rectangle.
var blur:BlurFilter = new BlurFilter();
blur.blurX = 10;
blur.blurY = 10;
blur.quality = BitmapFilterQuality.MEDIUM;
redDotCutout.filters = [blur];


Flash Player 9 , Adobe AIR 1.0
, .
,
.
DropShadowFilter , .
, ,
(-, , ).
,
().
:

23.11.2012.

299

ACTIONSCRIPT 3.0

import flash.display.Sprite;
import flash.filters.DropShadowFilter;
// Draw a box.
var boxShadow:Sprite = new Sprite();
boxShadow.graphics.lineStyle(1);
boxShadow.graphics.beginFill(0xFF3300);
boxShadow.graphics.drawRect(0, 0, 100, 100);
boxShadow.graphics.endFill();
addChild(boxShadow);
// Apply the drop shadow filter to the box.
var shadow:DropShadowFilter = new DropShadowFilter();
shadow.distance = 10;
shadow.angle = 25;
// You can also set other properties, such as the shadow color,
// alpha, amount of blur, strength, quality, and options for
// inner shadows and knockout effects.
boxShadow.filters = [shadow];


Flash Player 9 , Adobe AIR 1.0
GlowFilter , , -
, .
,
, . GlowFilter
, .
Sprite :

23.11.2012.

300

ACTIONSCRIPT 3.0

import flash.display.Sprite;
import flash.filters.BitmapFilterQuality;
import flash.filters.GlowFilter;
// Create a cross graphic.
var crossGraphic:Sprite = new Sprite();
crossGraphic.graphics.lineStyle();
crossGraphic.graphics.beginFill(0xCCCC00);
crossGraphic.graphics.drawRect(60, 90, 100, 20);
crossGraphic.graphics.drawRect(100, 50, 20, 100);
crossGraphic.graphics.endFill();
addChild(crossGraphic);
// Apply the glow filter to the cross shape.
var glow:GlowFilter = new GlowFilter();
glow.color = 0x009922;
glow.alpha = 1;
glow.blurX = 25;
glow.blurY = 25;
glow.quality = BitmapFilterQuality.MEDIUM;
crossGraphic.filters = [glow];


Flash Player 9 , Adobe AIR 1.0
GradientBevelFilter
BitmapData.
, .
drawRect(), Shape,
.

23.11.2012.

301

ACTIONSCRIPT 3.0

import flash.display.Shape;
import flash.filters.BitmapFilterQuality;
import flash.filters.GradientBevelFilter;
// Draw a rectangle.
var box:Shape = new Shape();
box.graphics.lineStyle();
box.graphics.beginFill(0xFEFE78);
box.graphics.drawRect(100, 50, 90, 200);
box.graphics.endFill();
// Apply a gradient bevel to the rectangle.
var gradientBevel:GradientBevelFilter = new GradientBevelFilter();
gradientBevel.distance = 8;
gradientBevel.angle = 225; // opposite of 45 degrees
gradientBevel.colors = [0xFFFFCC, 0xFEFE78, 0x8F8E01];
gradientBevel.alphas = [1, 0, 1];
gradientBevel.ratios = [0, 128, 255];
gradientBevel.blurX = 8;
gradientBevel.blurY = 8;
gradientBevel.quality = BitmapFilterQuality.HIGH;
// Other properties let you set the filter strength and set options
// for inner bevel and knockout effects.
box.filters = [gradientBevel];
// Add the graphic to the display list.
addChild(box);


Flash Player 9 , Adobe AIR 1.0
GradientGlowFilter
BitmapData.
. ,
, .
,
.
. ,
.

23.11.2012.

302

ACTIONSCRIPT 3.0

import
import
import
import

flash.events.MouseEvent;
flash.filters.BitmapFilterQuality;
flash.filters.BitmapFilterType;
flash.filters.GradientGlowFilter;

// Create a new Shape instance.


var shape:Shape = new Shape();
// Draw the shape.
shape.graphics.beginFill(0xFF0000, 100);
shape.graphics.moveTo(0, 0);
shape.graphics.lineTo(100, 0);
shape.graphics.lineTo(100, 100);
shape.graphics.lineTo(0, 100);
shape.graphics.lineTo(0, 0);
shape.graphics.endFill();
// Position the shape on the Stage.
addChild(shape);
shape.x = 100;
shape.y = 100;
// Define a gradient glow.
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0x000000, 0xFF0000];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
// Define functions to listen for two events.
function onClick(event:MouseEvent):void
{
gradientGlow.strength++;
shape.filters = [gradientGlow];
}
function onMouseMove(event:MouseEvent):void
{
gradientGlow.blurX = (stage.mouseX / stage.stageWidth) * 255;
gradientGlow.blurY = (stage.mouseY / stage.stageHeight) * 255;
shape.filters = [gradientGlow];
}
stage.addEventListener(MouseEvent.CLICK, onClick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);

23.11.2012.

303

ACTIONSCRIPT 3.0

:
Flash Player 9 , Adobe AIR 1.0
Timer
, .
import
import
import
import
import
import
import
import
var
var
var
var
var
var
var
var
var
var
var
var

flash.display.Shape;
flash.events.TimerEvent;
flash.filters.BitmapFilterQuality;
flash.filters.BitmapFilterType;
flash.filters.DropShadowFilter;
flash.filters.GlowFilter;
flash.filters.GradientBevelFilter;
flash.utils.Timer;

count:Number = 1;
distance:Number = 8;
angleInDegrees:Number = 225; // opposite of 45 degrees
colors:Array = [0xFFFFCC, 0xFEFE78, 0x8F8E01];
alphas:Array = [1, 0, 1];
ratios:Array = [0, 128, 255];
blurX:Number = 8;
blurY:Number = 8;
strength:Number = 1;
quality:Number = BitmapFilterQuality.HIGH;
type:String = BitmapFilterType.INNER;
knockout:Boolean = false;

// Draw the rectangle background for the traffic light.


var box:Shape = new Shape();
box.graphics.lineStyle();
box.graphics.beginFill(0xFEFE78);
box.graphics.drawRect(100, 50, 90, 200);
box.graphics.endFill();
// Draw the 3 circles for the three lights.
var stopLight:Shape = new Shape();
stopLight.graphics.lineStyle();
stopLight.graphics.beginFill(0xFF0000);
stopLight.graphics.drawCircle(145,90,25);
stopLight.graphics.endFill();
var cautionLight:Shape = new Shape();
cautionLight.graphics.lineStyle();
cautionLight.graphics.beginFill(0xFF9900);
cautionLight.graphics.drawCircle(145,150,25);
cautionLight.graphics.endFill();
var goLight:Shape = new Shape();
goLight.graphics.lineStyle();
goLight.graphics.beginFill(0x00CC00);
goLight.graphics.drawCircle(145,210,25);
goLight.graphics.endFill();
// Add the graphics to the display list.
addChild(box);

23.11.2012.

304

ACTIONSCRIPT 3.0

addChild(stopLight);
addChild(cautionLight);
addChild(goLight);
// Apply a gradient bevel to the traffic light rectangle.
var gradientBevel:GradientBevelFilter = new GradientBevelFilter(distance, angleInDegrees,
colors, alphas, ratios, blurX, blurY, strength, quality, type, knockout);
box.filters = [gradientBevel];
// Create the inner shadow (for lights when off) and glow
// (for lights when on).
var innerShadow:DropShadowFilter = new DropShadowFilter(5, 45, 0, 0.5, 3, 3, 1, 1, true,
false);
var redGlow:GlowFilter = new GlowFilter(0xFF0000, 1, 30, 30, 1, 1, false, false);
var yellowGlow:GlowFilter = new GlowFilter(0xFF9900, 1, 30, 30, 1, 1, false, false);
var greenGlow:GlowFilter = new GlowFilter(0x00CC00, 1, 30, 30, 1, 1, false, false);
// Set the starting state of the lights (green on, red/yellow off).
stopLight.filters = [innerShadow];
cautionLight.filters = [innerShadow];
goLight.filters = [greenGlow];
// Swap the filters based on the count value.
function trafficControl(event:TimerEvent):void
{
if (count == 4)
{
count = 1;
}
switch (count)
{
case 1:
stopLight.filters = [innerShadow];
cautionLight.filters = [yellowGlow];
goLight.filters = [innerShadow];
break;
case 2:
stopLight.filters = [redGlow];
cautionLight.filters = [innerShadow];
goLight.filters = [innerShadow];
break;
case 3:
stopLight.filters = [innerShadow];
cautionLight.filters = [innerShadow];
goLight.filters = [greenGlow];
break;
}
count++;
}
// Create a timer to swap the filters at a 3 second interval.
var timer:Timer = new Timer(3000, 9);
timer.addEventListener(TimerEvent.TIMER, trafficControl);
timer.start();

23.11.2012.

305

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
ColorMatrixFilter -
. , (
), -
,
.

, , -. ,
, ,
, . matrix
20 , . ,
, . matrix ColorMatrixFilter
c ActionScript 3.0 Adobe Flash Platform.


Flash Player 9 , Adobe AIR 1.0
ConvolutionFilter BitmapData
, , , ,
.

, . ,
, ,
.
3 3. :
N
N
N

N
P
N

N
N
N

,
( P), ( N).
,
.
, , ,
:
0
0
0

0
1
0

0
0
0

,
1 ,
0. , .
:

23.11.2012.

306

ACTIONSCRIPT 3.0

0
0
0

0
0
0

0
1
0

, ,
.
.
ActionScript Array, , ,
. ,

:
// Load an image onto the Stage.
var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("http://www.helpexamples.com/flash/images/image1.jpg");
loader.load(url);
this.addChild(loader);
function applyFilter(event:MouseEvent):void
{
// Create the convolution matrix.
var matrix:Array = [0, 0, 0,
0, 0, 1,
0, 0, 0];
var convolution:ConvolutionFilter = new ConvolutionFilter();
convolution.matrixX = 3;
convolution.matrixY = 3;
convolution.matrix = matrix;
convolution.divisor = 1;
loader.filters = [convolution];
}
loader.addEventListener(MouseEvent.CLICK, applyFilter);

, , 1 0 .
, 8 1
( ). , , 8
. ,
,
divisor . , divisor 1.
, , ,
, .
8, 1, 8 .
,
. 3 3
.

( 5):
0 1 0
1 1 1
0 1 0

23.11.2012.

307

ACTIONSCRIPT 3.0

( 1):
0, -1, 0
-1, 5, -1
0, -1, 0

( 1):
0, -1, 0
-1, 4, -1
0, -1, 0

( 1):
-2, -1, 0
-1, 1, 1
0, 1, 2

, 1. ,
1 ( 0
, divisor 0).


Flash Player 9 , Adobe AIR 1.0
DisplacementMapFilter BitmapData (
) .
BitmapData,
. .
, .
, .
, , ,
.
, :

: ,
. ,
.

X: , , x.
Y: , , y.
X: , x.
Y: , y.
: ,
. , DisplacementMapFilterMode,
( IGNORE) ,
( WRAP, ),
( CLAMP) ( COLOR).
, .
. ,
,
.

23.11.2012.

308

ACTIONSCRIPT 3.0

import
import
import
import
import
import

flash.display.BitmapData;
flash.display.Loader;
flash.events.MouseEvent;
flash.filters.DisplacementMapFilter;
flash.geom.Point;
flash.net.URLRequest;

// Load an image onto the Stage.


var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("http://www.helpexamples.com/flash/images/image3.jpg");
loader.load(url);
this.addChild(loader);
var mapImage:BitmapData;
var displacementMap:DisplacementMapFilter;
// This function is called when the image finishes loading.
function setupStage(event:Event):void
{
// Center the loaded image on the Stage.
loader.x = (stage.stageWidth - loader.width) / 2;
loader.y = (stage.stageHeight - loader.height) / 2;
// Create the displacement map image.
mapImage = new BitmapData(loader.width, loader.height, false, 0xFF0000);
// Create the displacement filter.
displacementMap = new DisplacementMapFilter();
displacementMap.mapBitmap = mapImage;
displacementMap.mapPoint = new Point(0, 0);
displacementMap.componentX = BitmapDataChannel.RED;
displacementMap.scaleX = 250;
loader.filters = [displacementMap];
}
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, setupStage);

: BitmapData,
. (
).
.

: 0, 0 (
).

X: BitmapDataChannel.RED. ,

( ) x.

X: 250. (
) (
). 1, 0,5
. 250, 125 .

23.11.2012.

309

ACTIONSCRIPT 3.0

, 250 .
( )
. ( ,
, ).
.
1 . ,

,
, ,
.
2 .

x ,
. ,
0xFF 255. .
3 (127,

0 255). ,
( x; y). ,
( ),
( x; y).
, 127, ( )
.
4 , ,

.
100 % . x y,
. 100 %,
250, ( 125 ).
y y , (
). .
(WRAP).
, .
, .
, , (
loader.filters = [displacementMap]), ,
:
displacementMap.mode = DisplacementMapFilterMode.CLAMP;

.
, :

23.11.2012.

310

ACTIONSCRIPT 3.0

import
import
import
import
import
import
import
import
import
import
import
import

flash.display.Bitmap;
flash.display.BitmapData;
flash.display.BitmapDataChannel;
flash.display.GradientType;
flash.display.Loader;
flash.display.Shape;
flash.events.MouseEvent;
flash.filters.DisplacementMapFilter;
flash.filters.DisplacementMapFilterMode;
flash.geom.Matrix;
flash.geom.Point;
flash.net.URLRequest;

// Create the gradient circles that will together form the


// displacement map image
var radius:uint = 50;
var type:String = GradientType.LINEAR;
var redColors:Array = [0xFF0000, 0x000000];
var blueColors:Array = [0x0000FF, 0x000000];
var alphas:Array = [1, 1];
var ratios:Array = [0, 255];
var xMatrix:Matrix = new Matrix();
xMatrix.createGradientBox(radius * 2, radius * 2);
var yMatrix:Matrix = new Matrix();
yMatrix.createGradientBox(radius * 2, radius * 2, Math.PI / 2);
var xCircle:Shape = new Shape();
xCircle.graphics.lineStyle(0, 0, 0);
xCircle.graphics.beginGradientFill(type, redColors, alphas, ratios, xMatrix);
xCircle.graphics.drawCircle(radius, radius, radius);
var yCircle:Shape = new Shape();
yCircle.graphics.lineStyle(0, 0, 0);
yCircle.graphics.beginGradientFill(type, blueColors, alphas, ratios, yMatrix);
yCircle.graphics.drawCircle(radius, radius, radius);
// Position the circles at the bottom of the screen, for reference.
this.addChild(xCircle);
xCircle.y = stage.stageHeight - xCircle.height;
this.addChild(yCircle);
yCircle.y = stage.stageHeight - yCircle.height;
yCircle.x = 200;
// Load an image onto the Stage.
var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("http://www.helpexamples.com/flash/images/image1.jpg");
loader.load(url);
this.addChild(loader);
// Create the map image by combining the two gradient circles.
var map:BitmapData = new BitmapData(xCircle.width, xCircle.height, false, 0x7F7F7F);
map.draw(xCircle);
var yMap:BitmapData = new BitmapData(yCircle.width, yCircle.height, false, 0x7F7F7F);
yMap.draw(yCircle);
map.copyChannel(yMap, yMap.rect, new Point(0, 0), BitmapDataChannel.BLUE,
BitmapDataChannel.BLUE);

23.11.2012.

311

ACTIONSCRIPT 3.0

yMap.dispose();
// Display the map image on the Stage, for reference.
var mapBitmap:Bitmap = new Bitmap(map);
this.addChild(mapBitmap);
mapBitmap.x = 400;
mapBitmap.y = stage.stageHeight - mapBitmap.height;
// This function creates the displacement map filter at the mouse location.
function magnify():void
{
// Position the filter.
var filterX:Number = (loader.mouseX) - (map.width / 2);
var filterY:Number = (loader.mouseY) - (map.height / 2);
var pt:Point = new Point(filterX, filterY);
var xyFilter:DisplacementMapFilter = new DisplacementMapFilter();
xyFilter.mapBitmap = map;
xyFilter.mapPoint = pt;
// The red in the map image will control x displacement.
xyFilter.componentX = BitmapDataChannel.RED;
// The blue in the map image will control y displacement.
xyFilter.componentY = BitmapDataChannel.BLUE;
xyFilter.scaleX = 35;
xyFilter.scaleY = 35;
xyFilter.mode = DisplacementMapFilterMode.IGNORE;
loader.filters = [xyFilter];
}
// This function is called when the mouse moves. If the mouse is
// over the loaded image, it applies the filter.
function moveMagnifier(event:MouseEvent):void
{
if (loader.hitTestPoint(loader.mouseX, loader.mouseY))
{
magnify();
}
}
loader.addEventListener(MouseEvent.MOUSE_MOVE, moveMagnifier);

23.11.2012.

312

ACTIONSCRIPT 3.0

, ,
. x (xyFilter.componentX = BitmapDataChannel.RED),
y (xyFilter.componentY = BitmapDataChannel.BLUE).
, ,
, .


, . ,
, . ,
.
0x7F7F7F.
, .
. ,
. ,
, .


Flash Player 10 , Adobe AIR 1.5
ShaderFilter , Pixel
Bender. Pixel Bender,
. ,
.
. Shader , Flash Player 10 Adobe AIR 1.5.
, Shader,
Pixel Bender. Shader
, , . Pixel
Bender 323.
.

.
23.11.2012.

313

ACTIONSCRIPT 3.0

( BitmapData, )
. -
.

,
( input ShaderInput,
Shader).
Shader ShaderFilter.
, , . ShaderFilter,
Shader, ShaderFilter() Shader
, :
var myFilter:ShaderFilter = new ShaderFilter(myShader);

.
342.

: Filter
Workbench
Flash Player 9 , Adobe AIR 1.0
Filter Workbench ,
,
ActionScript.
.




www.adobe.com/go/learn_programmingAS3samples_flash_ru. Filter Workbench
Samples/FilterWorkbench. .

23.11.2012.

314

315

ACTIONSCRIPT 3.0

File

com/example/programmingas3/filterWorkbench/FilterWorkbenchController.as

,
,
,
,
.

com/example/programmingas3/filterWorkbench/IFilterFactory.as

, ,

.
,
FilterWorkbenchController

.

com/example/programmingas3/filterWorkbench/:

,
IFilterFactory.

,
.


,
FilterWorkbenchController
.

BevelFactory.as
BlurFactory.as
ColorMatrixFactory.as
ConvolutionFactory.as
DropShadowFactory.as
GlowFactory.as
GradientBevelFactory.as
GradientGlowFactory.as
com/example/programmingas3/filterWorkbench/IFilterPanel.as

,
, ,

,
.

com/example/programmingas3/filterWorkbench/ColorStringFormatter.as

com/example/programmingas3/filterWorkbench/GradientColor.as

, ,
(,
),
GradientBevelFilter
GradientGlowFilter

(Flex)
FilterWorkbench.mxml

,
.

flexapp/FilterWorkbench.as

,

.
,
MXML.

23.11.2012.

316

ACTIONSCRIPT 3.0

File

flexapp/filterPanels:

MXML,

,
.

BevelPanel.mxml
BlurPanel.mxml
ColorMatrixPanel.mxml
ConvolutionPanel.mxml
DropShadowPanel.mxml
GlowPanel.mxml
GradientBevelPanel.mxml
GradientGlowPanel.mxml
flexapp/ImageContainer.as

flexapp/controls/BGColorCellRenderer.as

,

DataGrid

flexapp/controls/QualityComboBox.as

,
,

.

flexapp/controls/TypeComboBox.as

,
,

.

(Flash)
FilterWorkbench.fla

,
.

flashapp/FilterWorkbench.as

,

.
FLA- .

flashapp/filterPanels:

,

,
.

BevelPanel.as
BlurPanel.as
ColorMatrixPanel.as
ConvolutionPanel.as
DropShadowPanel.as
GlowPanel.as
GradientBevelPanel.as
GradientGlowPanel.as
flashapp/ImageContainer.as


MovieClip FLA-
,
(, BlurPanel
,
BlurPanel.as).
,

.
,

23.11.2012.

317

ACTIONSCRIPT 3.0

File

flashapp/BGColorCellRenderer.as

,

DataGrid

flashapp/ButtonCellRenderer.as

,

DataGrid


com/example/programmingas3/filterWorkbench/ImageType.as

,
URL
,
.
,

.

images/sampleAnimation.swf,

,
.

images/sampleImage1.jpg,
images/sampleImage2.jpg

ActionScript
Flash Player 9 , Adobe AIR 1.0
Filter Workbench ,
ActionScript .
, (
, Flash)
ActionScript .
. :

(flash.filters.BevelFilter),
(flash.filters.BlurFilter),
(flash.filters.ColorMatrixFilter),
(flash.filters.ConvolutionFilter),
(flash.filters.DropShadowFilter),
(flash.filters.GlowFilter),
(flash.filters.GradientBevelFilter),
(flash.filters.GradientGlowFilter).

23.11.2012.

ACTIONSCRIPT 3.0

, ,
.
, :

,
. .
, , , .
.


, , ,
. , .

, ActionScript,
, .
ConvolutionFilter , Filter Workbench
3 x 3 ( ).

, ActionScript,
Filter Workbench.


Flash Player 9 , Adobe AIR 1.0
Filter Workbench ( ),
. ,
ActionScript, ,
. ,
. , .

23.11.2012.

318

ACTIONSCRIPT 3.0

, ,
. ,
. ,
, BlurFactory. BlurFactory
modifyFilter(), : blurX, blurY quality,
BlurFilter:
private var _filter:BlurFilter;
public function modifyFilter(blurX:Number = 4, blurY:Number = 4, quality:int = 1):void
{
_filter = new BlurFilter(blurX, blurY, quality);
dispatchEvent(new Event(Event.CHANGE));
}

, ,
) , , . ConvolutionFactory
:
private var _filter:ConvolutionFilter;
public function modifyFilter(matrixX:Number = 0,
matrixY:Number = 0,
matrix:Array = null,
divisor:Number = 1.0,
bias:Number = 0.0,
preserveAlpha:Boolean = true,
clamp:Boolean = true,
color:uint = 0,
alpha:Number = 0.0):void
{
_filter = new ConvolutionFilter(matrixX, matrixY, matrix, divisor, bias, preserveAlpha,
clamp, color, alpha);
dispatchEvent(new Event(Event.CHANGE));
}

,
Event.CHANGE, .
FilterWorkbenchController,
, , ,
.
FilterWorkbenchController
. , ,
. IFilterFactory, ,
,
FilterWorkbenchController . IFilterFactory getFilter(),
FilterWorkbenchController:
function getFilter():BitmapFilter;

23.11.2012.

319

ACTIONSCRIPT 3.0

, getFilter() ,
BitmapFilter . BitmapFilter .
BitmapFilter ,
. getFilter(),
. , ,
ConvolutionFactory:
public class ConvolutionFactory extends EventDispatcher implements IFilterFactory
{
// ------- Private vars ------private var _filter:ConvolutionFilter;
...
// ------- IFilterFactory implementation ------public function getFilter():BitmapFilter
{
return _filter;
}
...
}

getFilter() ConvolutionFactory ConvolutionFilter,


, getFilter(), .
getFilter(), ConvolutionFactory,
BitmapFilter, ActionScript.


Flash Player 9 , Adobe AIR 1.0
, Filter Workbench FilterWorkbenchController
( ),
. ,
, ,
. , setFilterTarget()
FilterWorkbenchController, , ImageType:
public function setFilterTarget(targetType:ImageType):void
{
...
_loader = new Loader();
...
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, targetLoadComplete);
...
}

,
_currentTarget :
private var _currentTarget:DisplayObject;
private function targetLoadComplete(event:Event):void
{
...
_currentTarget = _loader.content;
...
}

23.11.2012.

320

ACTIONSCRIPT 3.0

, setFilter() ,
,
_filterFactory.
private var _filterFactory:IFilterFactory;
public function setFilter(factory:IFilterFactory):void
{
...
_filterFactory = factory;
_filterFactory.addEventListener(Event.CHANGE, filterChange);
}

, , ,
, . ,
IFilterFactory. , getFilter()
change (Event.CHANGE) .
, ,
change ,
filterChange() .
applyTemporaryFilter():
private function filterChange(event:Event):void
{
applyTemporaryFilter();
}
private function applyTemporaryFilter():void
{
var currentFilter:BitmapFilter = _filterFactory.getFilter();
// Add the current filter to the set temporarily
_currentFilters.push(currentFilter);
// Refresh the filter set of the filter target
_currentTarget.filters = _currentFilters;
// Remove the current filter from the set
// (This doesn't remove it from the filter target, since
// the target uses a copy of the filters array internally.)
_currentFilters.pop();
}

applyTemporaryFilter(). , getFilter()
.
var currentFilter:BitmapFilter = _filterFactory.getFilter();

Array _currentFilters,
, .
:
_currentFilters.push(currentFilter);

23.11.2012.

321

ACTIONSCRIPT 3.0

filters ,
:
_currentTarget.filters = _currentFilters;

, ,
. _currentFilters:
_currentFilters.pop();

,
, filters
. , ,
, filters
.

23.11.2012.

322

323

15. Pixel
Bender
Flash Player 10 , Adobe AIR 1.5
Adobe Pixel Bender Toolkit
. - Pixel Bender
ActionScript
. Pixel Bender ActionScript
,
ActionScript.
. Flash Player 10 Adobe AIR 1.5 Pixel
Bender. , Pixel Bender
.


Adobe Pixel Bender
Pixel Bender ( )
Pixel Bender
flash.display.Shader
flash.filters.ShaderFilter
Pixel Bender Flash ( )
Pixel Bender Flex ( )

Pixel Bender
Flash Player 10 , Adobe AIR 1.5
Adobe Pixel Bender ,
. Pixel Bender ,
. ,
. .
, .
.
, .
, .
.
ActionScript :

23.11.2012.

ACTIONSCRIPT 3.0
Pixel Bender

;
.
.
, .
, .
. .
, .
Pixel Bender Flash Player 10 Adobe AIR 1.5. ,
Pixel Bender .
Pixel Bender .
.
.

,
Pixel Bender.
Pixel Bender, , . Pixel Bender
, , , ,
.
- Pixel Bender Pixel Bender - Pixel Bender.
- .
Pixel Bender , Pixel Bender.
Pixel Bender Toolkit , - Pixel Bender
Pixel Bender. ,
Pixel Bender.
, Pixel Bender.

. ,
( ).
. .
ActionScript . Pixel Bender - Pixel
Bender. SWF-
. ActionScript Shader,
- .
, , ,

. , ,
( )
.
( )
. ,
.

23.11.2012.

324

ACTIONSCRIPT 3.0
Pixel Bender


.
SWF-.
API- ,
.
. Pixel Bender
, . Pixel Bender Toolkit
- Pixel Bender. - Pixel Bender,
.
1 Adobe Pixel Bender Toolkit. Build ()

Turn on Flash Player warnings and errors ( Flash


Player).
2 Pixel Bender Pixel Bender Toolkit.
3 File () Export kernel filter for Flash Player (

Flash Player).
4 - Pixel Bender , Flash.

, .
ActionScript, .
Flash Professional, .
1 Flash .
2 ActionScript , Flash.

. ,
MyApplication, MyApplication.as ActionScript.
3 ActionScript .
4 Flash ,

.
5 ActionScript, .
6 , >

.
ActionScript
1184.

23.11.2012.

325

ACTIONSCRIPT 3.0
Pixel Bender


Flash Player 10 , Adobe AIR 1.5
Pixel Bender ActionScript,
ActionScript. Adobe Pixel Bender Toolkit Pixel Bender,
ActionScript . Shader,
Pixel Bender ActionScript. Shader
, , . Shader
, . ,
, Shader shader ShaderFilter.
, Shader Graphics.beginShaderFill().
ActionScript , Adobe Pixel Bender Toolkit ( .pbj) .

: :
URLLoader. , .
-
Shader.
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
}

SWF-: SWF-
[Embed]. [Embed] , SWF Flex SDK. [Embed] source ,
mimeType "application/octet-stream", .
[Embed(source="myShader.pbj", mimeType="application/octet-stream")]
var MyShaderClass:Class;
// ...
// create a shader and set the embedded shader as its bytecode
var shader:Shader = 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

23.11.2012.

326

ACTIONSCRIPT 3.0
Pixel Bender

- (
URLLoader.data [Embed]) Shader.
, - Shader . -
Shader(). byteCode
Shader.
Pixel Bender Shader,
. , ,
, .
data Shader, ,
.


Flash Player 10 , Adobe AIR 1.5
Pixel Bender, Pixel Bender.
ActionScript, .
Shader Pixel Bender,
ShaderData, , data Shader.
ShaderData . ShaderData
,
. , . ,
, Pixel Bender :
namespace : "Adobe::Example";
vendor : "Bob Jones";
version : 1;
description : "Creates a version of the specified image with the specified brightness.";

ShaderData, , :

namespace (String): "Adobe::Example"

vendor (String): "Bob Jones" ( )

version (String): "1"

description (String): "Creates a version of the specified image with the specified brightness"

( )
ShaderData ,
for..in ShaderData. , . , ShaderData
, , . ShaderData
for..in, , ,
( ShaderInput), ( ShaderParameter) (
String). for..in
, data .
Vector metadata. ,
Shader myShader.

23.11.2012.

327

ACTIONSCRIPT 3.0
Pixel Bender

var shaderData:ShaderData = myShader.data;


var metadata:Vector.<String> = new Vector.<String>();
for (var prop:String in shaderData)
{
if (!(shaderData[prop] is ShaderInput) && !(shaderData[prop] is ShaderParameter))
{
metadata[metadata.length] = shaderData[prop];
}
}
// do something with the metadata

.
328. .
328.


Flash Player 10 , Adobe AIR 1.5
Pixel Bender ,
. , , ,
, .
, .
, .
.
, ,
data Shader. data ShaderData.


Flash Player 10 , Adobe AIR 1.5
, ,
: . Shader
data, ShaderData. ,
ShaderData.
. , src, ShaderData
src, . , ,
ShaderInput, , , ShaderParameter.
, ,
, , . .
, ( ), ,
. , ,
ShaderData . , ShaderData
for..in, , - .
327, ,
, , Shader.data.

23.11.2012.

328

ACTIONSCRIPT 3.0
Pixel Bender

,
. ShaderInput, .
ShaderParameter, .
. for..in
, data . ( ShaderInput)
Vector inputs. ( ShaderParameter)
Vector parameters. Vector
metadata. , Shader
myShader.
var
var
var
var

shaderData:ShaderData = myShader.data;
inputs:Vector.<ShaderInput> = new Vector.<ShaderInput>();
parameters:Vector.<ShaderParameter> = new Vector.<ShaderParameter>();
metadata:Vector.<String> = new Vector.<String>();

for (var prop:String in shaderData)


{
if (shaderData[prop] is ShaderInput)
{
inputs[inputs.length] = shaderData[prop];
}
else if (shaderData[prop] is ShaderParameter)
{
parameters[parameters.length] = shaderData[prop];
}
else
{
metadata[metadata.length] = shaderData[prop];
}
}
// do something with the inputs or properties


Flash Player 10 , Adobe AIR 1.5
,
. Shader .
, .
BitmapData,
. .
, ,
. , , ActionScript
ShaderInput. ShaderInput ShaderData data Shader,
328. ,
src Shader myShader.
ShaderInput, src,
:
myShader.data.src

23.11.2012.

329

ACTIONSCRIPT 3.0
Pixel Bender

ShaderInput input, .
input BitmapData, . input
BitmapData Vector.<Number> .
BitmapData Vector. <Number>
, . ShaderInput.input c ActionScript 3.0 Adobe Flash
Platform.
input, ShaderInput , ,
. width, height channels.
ShaderInput index, ,
. , , ,
.
, , .
333.


Flash Player 10 , Adobe AIR 1.5
, .
, , , ,
. , ,
. ,
, ActionScript ShaderParameter. ShaderParameter
ShaderData data Shader,
328. , brightness
Shader myShader. ShaderParameter,
brightness, :
myShader.data.brightness

, ActionScript
value ShaderParameter. value
Array, .
, Array,
ShaderParameter.value. value.
myShader.data.brightness.value = [75];

Pixel Bender ,
, value
ShaderParameter, Shader. value
, (
). value.
ActionScript.
color. color float4 Pixel Bender,
. color
, .
.
. (Ryan Taylor).
.
www.boostworthy.com.

23.11.2012.

330

ACTIONSCRIPT 3.0
Pixel Bender

ActionScript .

init(): init() - Pixel Bender, .


onLoadComplete().

onLoadComplete(): onLoadComplete() Shader shader.

Sprite texture. renderShader()


texture .

onEnterFrame(): onEnterFrame()

. ,
renderShader(), .

renderShader(): renderShader() Graphics.beginShaderFill(),

. ,
( ). .
334.
ActionScript .
, ActionScript Flash Builder,
FLA- Flash Professional.
package
{
import
import
import
import
import
import

flash.display.Shader;
flash.display.Sprite;
flash.events.Event;
flash.net.URLLoader;
flash.net.URLLoaderDataFormat;
flash.net.URLRequest;

public class ColorFilterExample extends Sprite


{
private const DELTA_OFFSET:Number = Math.PI * 0.5;
private var loader:URLLoader;
private var shader:Shader;
private var texture:Sprite;
private var delta:Number = 0;
public function ColorFilterExample()
{
init();
}
private function init():void
{
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(new URLRequest("ColorFilter.pbj"));
}
private function onLoadComplete(event:Event):void
{
shader = new Shader(loader.data);
texture = new Sprite();

23.11.2012.

331

ACTIONSCRIPT 3.0
Pixel Bender

addChild(texture);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
shader.data.color.value[0] = 0.5 + Math.cos(delta - DELTA_OFFSET) * 0.5;
shader.data.color.value[1] = 0.5 + Math.cos(delta) * 0.5;
shader.data.color.value[2] = 0.5 + Math.cos(delta + DELTA_OFFSET) * 0.5;
// The alpha channel value (index 3) is set to 1 by the kernel's default
// value. This value doesn't need to change.
delta += 0.1;
renderShader();
}
private function renderShader():void
{
texture:graphics.clear();
texture.graphics.beginShaderFill(shader);
texture.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
texture.graphics.endFill();
}
}
}

ColorFilter,
- Pixel Bender ColorFilter.pbj.
<languageVersion : 1.0;>
kernel ColorFilter
<
namespace : "boostworthy::Example";
vendor : "Ryan Taylor";
version : 1;
description : "Creates an image where every pixel has the specified color value.";
>
{
output pixel4 result;
parameter float4 color
<
minValue:float4(0, 0, 0, 0);
maxValue:float4(1, 1, 1, 1);
defaultValue:float4(0, 0, 0, 1);
>;
void evaluatePixel()
{
result = color;
}
}

23.11.2012.

332

ACTIONSCRIPT 3.0
Pixel Bender

, , type
ShaderParameter, , .
type .
, , . ShaderParameter.value
ActionScript 3.0 Adobe Flash Professional CS5.
ShaderParameter index,
. ShaderParameter
, , . ,
, , .
, , ShaderParameter
. , for..in
ShaderParameter .
for..in ShaderParameter.
Vector metadata. ,
Shader myShader,
brightness.
var brightness:ShaderParameter = myShader.data.brightness;
var metadata:Vector.<String> = new Vector.<String>();
for (var prop:String in brightness)
{
if (brightness[prop] is String)
{
metadata[metadata.length] = brightness[prop];
}
}
// do something with the metadata


Flash Player 10 , Adobe AIR 1.5
Pixel Bender shader ActionScript Shader,
.

: , API

:
: ,
:
. ,
.
, .

23.11.2012.

333

ACTIONSCRIPT 3.0
Pixel Bender


Flash Player 10 , Adobe AIR 1.5
,
API- . ,
API- .
, , , beginShaderFill()
Graphics. Shader beginShaderFill(),
.
var canvas:Sprite = new Sprite();
canvas.graphics.beginShaderFill(myShader);
canvas.graphics.drawRect(10, 10, 150, 150);
canvas.graphics.endFill();
// add canvas to the display list to see the result

,
, .
.
. ,
, . ,
, .

. e (Petri Leskinen).
. , ,
http://pixelero.wordpress.com.
ActionScript .

init(): init() .

Point, . Sprite
canvas. , updateShaderFill(), canvas

. , - .

onLoadComplete(): onLoadComplete() Shader shader.

. updateShaderFill()
enterFrame,
.

23.11.2012.

334

ACTIONSCRIPT 3.0
Pixel Bender

updateShaderFill(): updateShaderFill()

. .
beginShaderFill(), , API .
ActionScript .
, ActionScript Flash Builder,
FLA- Flash Professional.
package
{
import
import
import
import
import
import
import

flash.display.Shader;
flash.display.Sprite;
flash.events.Event;
flash.geom.Point;
flash.net.URLLoader;
flash.net.URLLoaderDataFormat;
flash.net.URLRequest;

public class ThreePointGradient extends Sprite


{
private var canvas:Sprite;
private var shader:Shader;
private var loader:URLLoader;
private var topMiddle:Point;
private var bottomLeft:Point;
private var bottomRight:Point;
private var colorAngle:Number = 0.0;
private const d120:Number = 120 / 180 * Math.PI; // 120 degrees in radians

public function ThreePointGradient()


{
init();
}
private function init():void
{
canvas = new Sprite();
addChild(canvas);
var size:int = 400;
topMiddle = new Point(size / 2, 10);
bottomLeft = new Point(0, size - 10);
bottomRight = new Point(size, size - 10);
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(new URLRequest("ThreePointGradient.pbj"));
}
private function onLoadComplete(event:Event):void
{
shader = new Shader(loader.data);

23.11.2012.

335

ACTIONSCRIPT 3.0
Pixel Bender

shader.data.point1.value = [topMiddle.x, topMiddle.y];


shader.data.point2.value = [bottomLeft.x, bottomLeft.y];
shader.data.point3.value = [bottomRight.x, bottomRight.y];
addEventListener(Event.ENTER_FRAME, updateShaderFill);
}
private function updateShaderFill(event:Event):void
{
colorAngle += .06;
var c1:Number = 1 / 3 + 2 / 3 * Math.cos(colorAngle);
var c2:Number = 1 / 3 + 2 / 3 * Math.cos(colorAngle + d120);
var c3:Number = 1 / 3 + 2 / 3 * Math.cos(colorAngle - d120);
shader.data.color1.value = [c1, c2, c3, 1.0];
shader.data.color2.value = [c3, c1, c2, 1.0];
shader.data.color3.value = [c2, c3, c1, 1.0];
canvas.graphics.clear();
canvas.graphics.beginShaderFill(shader);
canvas.graphics.moveTo(topMiddle.x, topMiddle.y);
canvas.graphics.lineTo(bottomLeft.x, bottomLeft.y);
canvas.graphics.lineTo(bottomRight.x, bottomLeft.y);
canvas.graphics.endFill();
}
}
}

ThreePointGradient,
- Pixel Bender ThreePointGradient.pbj.
<languageVersion : 1.0;>
kernel ThreePointGradient
<
namespace : "Petri Leskinen::Example";
vendor : "Petri Leskinen";
version : 1;
description : "Creates a gradient fill using three specified points and colors.";
>
{
parameter float2 point1 // coordinates of the first point
<
minValue:float2(0, 0);
maxValue:float2(4000, 4000);
defaultValue:float2(0, 0);
>;
parameter float4 color1 // color at the first point, opaque red by default
<
defaultValue:float4(1.0, 0.0, 0.0, 1.0);
>;
parameter float2 point2 // coordinates of the second point

23.11.2012.

336

ACTIONSCRIPT 3.0
Pixel Bender

<
minValue:float2(0, 0);
maxValue:float2(4000, 4000);
defaultValue:float2(0, 500);
>;
parameter float4 color2 // color at the second point, opaque green by default
<
defaultValue:float4(0.0, 1.0, 0.0, 1.0);
>;
parameter float2 point3 // coordinates of the third point
<
minValue:float2(0, 0);
maxValue:float2(4000, 4000);
defaultValue:float2(0, 500);
>;
parameter float4 color3 // color at the third point, opaque blue by default
<
defaultValue:float4(0.0, 0.0, 1.0, 1.0);
>;
output pixel4 dst;
void evaluatePixel()
{
float2 d2 = point2 - point1;
float2 d3 = point3 - point1;
// transformation to a new coordinate system
// transforms point 1 to origin, point2 to (1, 0), and point3 to (0, 1)
float2x2 mtrx = float2x2(d3.y, -d2.y, -d3.x, d2.x) / (d2.x * d3.y - d3.x * d2.y);
float2 pNew = mtrx * (outCoord() - point1);
// repeat the edge colors on the outside
pNew.xy = clamp(pNew.xy, 0.0, 1.0); // set the range to 0.0 ... 1.0
// interpolating the output color or alpha value
dst = mix(mix(color1, color2, pNew.x), color3, pNew.y);
}
}

.
, .
API- .
API 238.

23.11.2012.

337

ACTIONSCRIPT 3.0
Pixel Bender


Flash Player 10 , Adobe AIR 1.5

. ,
. ,
Shader blendShader , .
blendShader , null, blendMode
BlendMode.SHADER.
. , foreground,
, , foreground
.
foreground.blendShader = myShader;


. , . ,
. , ,
( , .)
,
.
. ,
, .
.
.
,
.
. (Mario Klingemann).
. www.quasimondo.com.
ActionScript .

init(): init() . -

onLoadComplete(): onLoadComplete() Shader shader.

. , backdrop, -
. , backgroundShape
. , foregroundShape, .

23.11.2012.

338

ACTIONSCRIPT 3.0
Pixel Bender

foregroundShape .
backdrop backgroundShape,
foregroundShape. foregroundShape
.
backgroundShape backdrop. ,
(foregroundShape) ,
(backgroundShape) .


, foregroundShape.

ActionScript .
, ActionScript Flash Builder,
FLA- Flash Professional.

23.11.2012.

339

ACTIONSCRIPT 3.0
Pixel Bender

package
{
import
import
import
import
import
import
import
import
import
import
import

flash.display.BlendMode;
flash.display.GradientType;
flash.display.Graphics;
flash.display.Shader;
flash.display.Shape;
flash.display.Sprite;
flash.events.Event;
flash.geom.Matrix;
flash.net.URLLoader;
flash.net.URLLoaderDataFormat;
flash.net.URLRequest;

public class LumaLighten extends Sprite


{
private var shader:Shader;
private var loader:URLLoader;
public function LumaLighten()
{
init();
}
private function init():void
{
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(new URLRequest("LumaLighten.pbj"));
}

private function onLoadComplete(event:Event):void


{
shader = new Shader(loader.data);
var backdrop:Shape = new Shape();
var g0:Graphics = backdrop.graphics;
g0.beginFill(0x303030);
g0.drawRect(0, 0, 400, 200);
g0.endFill();
addChild(backdrop);
var backgroundShape:Shape = new Shape();
var g1:Graphics = backgroundShape.graphics;
var c1:Array = [0x336600, 0x80ff00];
var a1:Array = [255, 255];
var r1:Array = [100, 255];
var m1:Matrix = new Matrix();
m1.createGradientBox(300, 200);
g1.beginGradientFill(GradientType.LINEAR, c1, a1, r1, m1);
g1.drawEllipse(0, 0, 300, 200);

23.11.2012.

340

ACTIONSCRIPT 3.0
Pixel Bender

g1.endFill();
addChild(backgroundShape);
var foregroundShape:Shape = new Shape();
var g2:Graphics = foregroundShape.graphics;
var c2:Array = [0xff8000, 0x663300];
var a2:Array = [255, 255];
var r2:Array = [100, 255];
var m2:Matrix = new Matrix();
m2.createGradientBox(300, 200);
g2.beginGradientFill(GradientType.LINEAR, c2, a2, r2, m2);
g2.drawEllipse(100, 0, 300, 200);
g2.endFill();
addChild(foregroundShape);
foregroundShape.blendShader = shader;
foregroundShape.blendMode = BlendMode.SHADER;
}
}
}

LumaLighten,
- Pixel Bender LumaLighten.pbj.
<languageVersion : 1.0;>
kernel LumaLighten
<
namespace : "com.quasimondo.blendModes";
vendor : "Quasimondo.com";
version : 1;
description : "Luminance based lighten blend mode";
>
{
input image4 background;
input image4 foreground;
output pixel4 dst;
const float3 LUMA = float3(0.212671, 0.715160, 0.072169);
void evaluatePixel()
{
float4 a = sampleNearest(foreground, outCoord());
float4 b = sampleNearest(background, outCoord());
float luma_a = a.r * LUMA.r + a.g * LUMA.g + a.b * LUMA.b;
float luma_b = b.r * LUMA.r + b.g * LUMA.g + b.b * LUMA.b;
dst = luma_a > luma_b ? a : b;
}
}

.
200.

23.11.2012.

341

ACTIONSCRIPT 3.0
Pixel Bender

. Pixel Bender Flash Player AIR,


outCoord() , .
, . ,
outCoord() . , outCoord()
, 0. , ,
.


Flash Player 10 , Adobe AIR 1.5

ActionScript. ,
( BitmapData).
, .
, .
BitmapData,
BitmapData, applyFilter().
Shader,
326. ShaderFilter,
Shader. ShaderFilter ,
. , .
filters applyFilter(), BitmapData.
, ShaderFilter
homeButton.
var myFilter:ShaderFilter = new ShaderFilter(myShader);
homeButton.filters = [myFilter];

.
, . ,
BitmapData. ,
, .
. ,
, . ,
, leftExtension, rightExtension, topExtension
bottomExtension, , .
.
, .
.
. Pixel Bender invertRGB.pbk,
Pixel Bender Toolkit. Pixel Bender
Toolkit. - ,
ActionScript.
ActionScript .

init(): init() . -

23.11.2012.

342

ACTIONSCRIPT 3.0
Pixel Bender

onLoadComplete(): onLoadComplete() Shader shader.

target. target ,
: , - .
:

, :

Pixel Bender invertRGB.pbk,


Pixel Bender Toolkit. invertRGB.pbk Pixel Bender Toolkit.
- invertRGB.pbj ,
ActionScript.
ActionScript .
, ActionScript Flash Builder,
FLA- Flash Professional.

23.11.2012.

343

ACTIONSCRIPT 3.0
Pixel Bender

package
{
import
import
import
import
import
import
import
import
import
import
import

flash.display.GradientType;
flash.display.Graphics;
flash.display.Shader;
flash.display.Shape;
flash.display.Sprite;
flash.filters.ShaderFilter;
flash.events.Event;
flash.geom.Matrix;
flash.net.URLLoader;
flash.net.URLLoaderDataFormat;
flash.net.URLRequest;

public class InvertRGB extends Sprite


{
private var shader:Shader;
private var loader:URLLoader;
public function InvertRGB()
{
init();
}
private function init():void
{
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(new URLRequest("invertRGB.pbj"));
}

private function onLoadComplete(event:Event):void


{
shader = new Shader(loader.data);
var target:Shape = new Shape();
addChild(target);
var g:Graphics = target.graphics;
var c:Array = [0x990000, 0x445500, 0x007799];
var a:Array = [255, 255, 255];
var r:Array = [0, 127, 255];
var m:Matrix = new Matrix();
m.createGradientBox(w, h);
g.beginGradientFill(GradientType.LINEAR, c, a, r, m);
g.drawRect(10, 10, w, h);
g.endFill();
var invertFilter:ShaderFilter = new ShaderFilter(shader);
target.filters = [invertFilter];
}
}
}

23.11.2012.

344

ACTIONSCRIPT 3.0
Pixel Bender

.
289.


Flash Player 10 , Adobe AIR 1.5
,
. ,
, , .
.

.
. ,
,
.

. .
, , .
. ,
,
.
ShaderJob .
ShaderJob Shader, , .
var job:ShaderJob = new ShaderJob(myShader);

, .
, complete
ShaderJob. .
function completeHandler(event:ShaderEvent):void
{
// do something with the shader result
}
job.addEventListener(ShaderEvent.COMPLETE, completeHandler);

, .
target ShaderJob.
var jobResult:BitmapData = new BitmapData(100, 75);
job.target = jobResult;

target BitmapData, ShaderJob .


, ByteArray Vector.<Number>
target. width height ShaderJob,
target.
. shader, target, width height ShaderJob,
ShaderJob(), : var job:ShaderJob = new
ShaderJob(myShader, myTarget, myWidth, myHeight);

, start() ShaderJob.
job.start();

23.11.2012.

345

ACTIONSCRIPT 3.0
Pixel Bender

start() ShaderJob.
,
. ShaderJob
complete, . ( complete)
target .
. , target,
, .
ShaderEvent. ShaderEvent ,
, target:
ShaderEvent.bitmapData, ShaderEvent.byteArray ShaderEvent.vector.
true start().
. (
) .
target , .
job.start(true);

23.11.2012.

346

347

16.
Flash Player 9 , Adobe AIR 1.0
MovieClip ,
Adobe Flash. ,
.


Flash Player 9 , Adobe AIR 1.0
,
Flash ActionScript.
Flash Flash.
MovieClip
MovieClip.
,
,
ActionScript. MovieClip
Flash.
, Sprite, ,
.
ActionScript, MovieClip
. ActionScript 3.0 ,
. ,
Shape Sprite MovieClip
.
. DisplayObject 185.

, .
AVM1 SWF SWF-, ActionScript 1.0 ActionScript 2.0, ,

Flash Player 8 .
AVM2 SWF SWF-, ActionScript 3.0 Adobe Flash Player 9

Adobe AIR.
SWF SWF-, SWF-

SWF- .
. ,

, ,
.

23.11.2012.

ACTIONSCRIPT 3.0

,
. MovieClip
Flash.
, () ,

MovieClip
Flash Player 9 , Adobe AIR 1.0
SWF- Flash ,
, MovieClip. ActionScript,
. SWF- Flash
, MovieClip ,
. ,
, . ,
, . ,
childClip
parentClip, , :
parentClip.childClip.play();

. , Flash,
,
.
, , , ,
Event.ADDED_TO_STAGE.
MovieClip ActionScript 2.0 ,
. ,
, . , _width _height width
height, _xscale _yscale scaleX scaleY.
MovieClip . c ActionScript 3.0 Adobe Flash Platform.


Flash Player 9 , Adobe AIR 1.0
Flash .
, , MovieClip
MovieClip. ActionScript ,
,

Flash.
MovieClip,
, SWF-. ,
Stage.frameRate ActionScript.

23.11.2012.

348

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
play() stop()
. , ,
, , bicycle.
,
bicycle.stop();

( ).
. , startButton,
.
// This function will be called when the button is clicked. It causes the
// bicycle animation to play.
function playAnimation(event:MouseEvent):void
{
bicycle.play();
}
// Register the function as a listener with the button.
startButton.addEventListener(MouseEvent.CLICK, playAnimation);


Flash Player 9 , Adobe AIR 1.0
play() stop().

nextFrame() prevFrame().
.
play() nextFrame() ,
enterFrame . bicycle

, enterFrame
bicycle ,
.
// This function is called when the enterFrame event is triggered, meaning
// it's called once per frame.
function everyFrame(event:Event):void
{
if (bicycle.currentFrame == 1)
{
bicycle.gotoAndStop(bicycle.totalFrames);
}
else
{
bicycle.prevFrame();
}
}
bicycle.addEventListener(Event.ENTER_FRAME, everyFrame);

23.11.2012.

349

ACTIONSCRIPT 3.0

,
, 1.
prevFrame() nextFrame(), (
prevFrame() 1 ).
if , ,
,
.


Flash Player 9 , Adobe AIR 1.0
.
gotoAndPlay() gotoAndStop()
, . ,
. .
.
, ,
. , ,
,
(, ., , ). ,
ActionScript, , (),
. ,
ActionScript ,
.
ActionScript 3.0 FrameLabel.
name, ,
, frame, ,
.
FrameLabel, ,
MovieClip , FrameLabel. currentLabels
, FrameLabel .
currentLabel .
, robot .
, currentLabel
robot, .
if (robot.currentLabel == "walking")
{
// do something
}

Flash Player 11.3 AIR 3.3 frameLabel FrameLabel.


FrameLabel, , .
, .
FrameLabel
MovieClip. frameLabel:

23.11.2012.

350

ACTIONSCRIPT 3.0

var myFrameLabel:FrameLabel = robot.currentLabels[1];


myFrameLabel.addEventListener(Event.FRAME_LABEL, onFrameLabel);
function onFrameLabel(e:Event):void {
//do something
}


Flash Player 9 , Adobe AIR 1.0
Flash
, SWF-. gotoAndPlay()
gotoAndStop(), , . FLA , .
, .
Flash, , ,
.
,
. ,
. , ,
, ,
.
scenes MovieClip Scene,
SWF-. currentScene Scene, ,
.
Scene , . labels
FrameLabel, .
name . numFrames
, .

MovieClip
ActionScript
Flash Player 9 , Adobe AIR 1.0
Flash
, .
, ,
. : ,
, ActionScript.
API- ActionScript 3.0
MovieClip. MovieClip
, .

23.11.2012.

351

ACTIONSCRIPT 3.0

( ) ActionScript 3.0

addChild() addChildAt() . ,
, .
.
172.

ActionScript
Flash Player 9 , Adobe AIR 1.0
Flash
( ActionScript). , ,
ActionScript, SWF-. ,
. ,
ActionScript, ActionScript.
ActionScript
1 .
2 .
3 ActionScript.

.
(,
Tree House TreeHouse). ,
, , .
ActionScript, ,
.
flash.display.MovieClip. ,
,
, Sprite ( MovieClip).
4 , .

Flash ActionScript
(, ),
:
.
SWF- .
,
MovieClip.
, Flash , :

23.11.2012.

352

ACTIONSCRIPT 3.0

package
{
import flash.display.MovieClip;
public class ExampleMovieClip extends MovieClip
{
public function ExampleMovieClip()
{
}
}
}

ActionScript,
. , ,
50 , ActionScript
Circle. Circle.as MovieClip
getArea() getCircumference().
package
{
import flash.display.MovieClip;
public class Circle extends MovieClip
{
public function Circle()
{
}
public function getArea():Number
{
// The formula is Pi times the radius squared.
return Math.PI * Math.pow((width / 2), 2);
}
public function getCircumference():Number
{
// The formula is Pi times the diameter.
return Math.PI * width;
}
}
}

, 1 Flash,
.
var c:Circle = new Circle();
addChild(c);
trace(c.width);
trace(c.height);
trace(c.getArea());
trace(c.getCircumference());

ActionScript
. , ,
, Circle. .
.

23.11.2012.

353

ACTIONSCRIPT 3.0

ActionScript ,
, . ,
, .
, Circle .
Circle Flash,
.
import flash.geom.ColorTransform;
var totalCircles:uint = 10;
var i:uint;
for (i = 0; i < totalCircles; i++)
{
// Create a new Circle instance.
var c:Circle = new Circle();
// Place the new Circle at an x coordinate that will space the circles
// evenly across the Stage.
c.x = (stage.stageWidth / totalCircles) * i;
// Place the Circle instance at the vertical center of the Stage.
c.y = stage.stageHeight / 2;
// Change the Circle instance to a random color
c.transform.colorTransform = getRandomColor();
// Add the Circle instance to the current timeline.
addChild(c);
}
function getRandomColor():ColorTransform
{
// Generate random values for the red, green, and blue color channels.
var red:Number = (Math.random() * 512) - 255;
var green:Number = (Math.random() * 512) - 255;
var blue:Number = (Math.random() * 512) - 255;
// Create and return a ColorTransform object with the random colors.
return new ColorTransform(1, 1, 1, 1, red, green, blue, 0);
}

,
. ,
transform ( Circle
MovieClip).

SWF-
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 SWF- Loader. SWF-,
ActionScript :
1 URLRequest URL- ;
2 Loader;
3 load() Loader, URLRequest.

23.11.2012.

354

ACTIONSCRIPT 3.0

4 addChild() (

Flash), Loader .
:
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/externalSwf.swf");
var loader:Loader = new Loader()
loader.load(request);
addChild(loader);

, JPEG,
GIF PNG. URL- , SWF-. ,
SWF- ActionScript. , SWF , SWF- SWF-, ,
, SWF Flash Player
AIR SWF- ActionScript. ,
SWF- , SWF-,
, SWF-,
.
. 158
1141.
SWF- Loader.content.
SWF- ActionScript 3.0,
, .

SWF-
Flash Player 9 , Adobe AIR 1.0
SWF- ActionScript,
. SWF- ActionScript 3.0,
AVM2 (ActionScript Virtual Machine 2), SWF-, ActionScript 1.0 2.0,
AVM1 (ActionScript Virtual Machine 1).
SWF- ActionScript 1.0 2.0 SWF- ActionScript 3.0
SWF- ActionScript 3.0 . Flash Player
. ,
Flash Player, Flash Player, ActionScript 3.0.
, .

ActionScript 3.0 SWF-, ActionScript 1.0 2.0.


SWF-, ActionScript 1.0 2.0, ,
( Loader.content ) AVM1Movie. AVM1Movie
MovieClip. , , ,
, . SWF- AVM2
, AVM1Movie.

SWF-, ActionScript 1.0 2.0, SWF-,


ActionScript 3.0. , SWF-, Adobe Flash 8 Flex Builder 1.5,
, SWF- ActionScript 3.0.

23.11.2012.

355

356

ACTIONSCRIPT 3.0

, SWF- ActionScript 2.0


SWF- ActionScript 3.0, SWF- ActionScript 2.0 -
. SWF- ActionScript 2.0
loadMovieNum(), 0 level.

SWF-, ActionScript 1.0 2.0, ,


SWF- ActionScript 3.0. , ,
ActionScript 2.0.
, ActionScript 2.0.
ActionScript 3.0 .
ActionScript 3.0.
ActionScript 3.0,
ActionScript 2.0.
Flash Player
,
SWF-, ActionScript.

Flash Player 7

Flash Player 8

Flash Player 9 10

SWF-,

9 ( 10)

AVM

AVM1

AVM1

AVM1 AVM2

SWF-,
ActionScript

1.0 2.0

1.0 2.0

1.0, 2.0 3.0

,
Flash Player 9 . , Adobe
Flash Player 8 , , ,
ActionScript 1.0 2.0.

, ActionScript
1.0 2.0

, ActionScript
3.0

ActionScript 1.0 2.0

ActionScript 1.0 2.0, ActionScript


3.0

ActionScript 1.0 2.0 (ActionScript 3.0


LocalConnection)

ActionScript 1.0 2.0 LocalConnection.


ActionScript 3.0

: RuntimeAssetsExplorer
Flash Player 9 , Adobe AIR 1.0
ActionScript ,
. Flash Player AIR SWF-, ,
ActionScript, SWF-, ,
SWF-. , Flash SWF-,
.

23.11.2012.

357

ACTIONSCRIPT 3.0

, , ,
, SWF-, SWF-
.
,
.
RuntimeAssetsExplorer SWF-, RuntimeAsset,
SWF-. :

SWF- Loader.load();
, ActionScript;
MovieClip ActionScript.
, , SWF-,
Flash Player, .
. 1122.
Flash Professional.
RuntimeAssetsExplorer Samples/RuntimeAssetsExplorer.
.
File

RuntimeAssetsExample.mxml


Flex (MXML) Flash (FLA).

RuntimeAssetsExample.fla
RuntimeAssetsExample.as

Flash (FLA).

GeometricAssets.as

,
RuntimeAsset.

GeometricAssets.fla

FLA-, GeometricAssets
( FLA),
, ActionScript.

com/example/programmingas3/runtimeassetexplorer/RuntimeLibrary.as

,
, SWF-,
,

.

com/example/programmingas3/runtimeassetexplorer/AnimatingBox.as

com/example/programmingas3/runtimeassetexplorer/AnimatingStar.as

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
SWF-,
. ,
, , , ,
.
. SWF- , ,
. .
ActionScript 3.0.
RuntimeLibrary . ,
,
.
: getAssets().
package com.example.programmingas3.runtimeassetexplorer
{
public interface RuntimeLibrary
{
function getAssets():Array;
}
}

SWF-
Flash Player 9 , Adobe AIR 1.0
RuntimeLibrary SWF , SWF-. SWF :

SWF-
,

SWF-
RuntimeLibrary
GeometricAssets, RuntimeLibrary.
FLA. RuntimeLibrary.
, getAssets() .

23.11.2012.

358

ACTIONSCRIPT 3.0

package
{
import flash.display.Sprite;
import com.example.programmingas3.runtimeassetexplorer.RuntimeLibrary;
public class GeometricAssets extends Sprite implements RuntimeLibrary
{
public function GeometricAssets() {
}
public function getAssets():Array {
return [ "com.example.programmingas3.runtimeassetexplorer.AnimatingBox",
"com.example.programmingas3.runtimeassetexplorer.AnimatingStar" ];
}
}
}

, FLA (, AnimationAssets),
getAssets().
MovieClip
MovieClip, .
AnimatingStar AnimatingBox.
package com.example.programmingas3.runtimeassetexplorer
{
import flash.display.MovieClip;
public class AnimatingStar extends MovieClip
{
public function AnimatingStar() {
}
}
}


MovieClip FLA-
GeometricAssets .
, (
360 ). animatingBox animatingStar
ActionScript, ,
getAssets(). flash.display.MovieClip ,
MovieClip.
, FLA-.
. SWF- SWF- AVM2, AnimatingBox AnimatingStar
SWF-.

23.11.2012.

359

ACTIONSCRIPT 3.0

SWF-
Flash Player 9 , Adobe AIR 1.0
.

ASSETS_PATH. FileReference, , ,
SWF- .
Flash Player
runtimeAssetsLoadComplete().
private function runtimeAssetsLoadComplete(event:Event):void
{
var rl:* = event.target.content;
var assetList:Array = rl.getAssets();
populateDropdown(assetList);
stage.frameRate = 60;
}

rl SWF-. getAssets()
SWF-, ,
ComboBox, populateDropDown(). ,
. addAsset().
private
{
var
var
var
...
}

function addAsset():void
className:String = assetNameCbo.selectedItem.data;
AssetClass:Class = getDefinitionByName(className) as Class;
mc:MovieClip = new AssetClass();

, ComboBox
(assetNameCbo.selectedItem.data), getDefinitionByName() ( flash.utils)
, .

23.11.2012.

360

361

17.
Flash Player 9 , Adobe AIR 1.0 , Flash CS3

208
ActionScript.
: .
Adobe Flash Professional.
ActionScript
.
Flash Professional ActionScript,
.
Flash Professional.


fl.motion


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

.
, ,
. ,
.
Flash Professional, ActionScript
. Flash ActionScript
3.0 ActionScript . ActionScript
,
.
.
Flash Professional.

, .
,

; , .

23.11.2012.

ACTIONSCRIPT 3.0

,
, , .

Flash
Flash Player 9 , Adobe AIR 1.0 , Flash CS3

,
. ,
.
, , , .
, ,
, .
Flash,
. Flash ActionScript,
, . .
Flash Professional.
ActionScript 3.0 Flash
. -, .
1 .
2 (Windows) Control (Macintosh).
3 ActionScript 3.0 . . .

-, Flash.
1 .

23.11.2012.

362

ACTIONSCRIPT 3.0

2 > > ActionScript 3.0.

.
, ,
ActionScript.


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

ActionScript, Flash, ,
.


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

AnimatorFactory, MotionBase Motion
fl.motion. ,
. ,
, flash.geom.
, flash.filter. ActionScript
Motion. Motion ,
. , ,
, , .
ActionScript , Flash
Symbol1_2. MotionBase __motion_Symbol1_2.
MotionBase Motion.

23.11.2012.

363

ACTIONSCRIPT 3.0

var __motion_Symbol1_2:MotionBase;

Motion.
__motion_Symbol1_2 = new Motion();

Motion
Flash Player 9 , Adobe AIR 1.0 , Flash CS3

Flash __motion_Symbol1_2
Motion. __motion_ . ,
Flash.
duration Motion .
__motion_Symbol1_2.duration = 200;

Flash ,
, .
ActionScript, Flash
, , Flash ,
. , ,
.
Flash .
.
, Motion ActionScript .


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

addPropertyArray() MotionBase
.
.

. ,
.
duration Motion, addPropertyArray()
duration.
, .
.

23.11.2012.

364

ACTIONSCRIPT 3.0

x y Motion
.
. addPropertyArray()
. , scaleX scaleY, .
scewX skewY, . rotationConcat,
.
addPropertyArray() :
x

Z ()

scaleX

(%)

scaleY

(%)

skewX

( )

skewY

( )

rotationX

rotationY

rotationConcat

( Z)

useRotationConcat , , addPropertyArray()


blendMode

BlendMode,

matrix3D

matrix3D, ;
; ,

rotationZ

Z
, rotationConcat.

, , ,
Flash.
, .
__motion_Wheel.
, 29
. , rotationConcat.
.

23.11.2012.

365

ACTIONSCRIPT 3.0

__motion_Wheel = new Motion();


__motion_Wheel.duration = 29;
__motion_Wheel.addPropertyArray("x", [0]);
__motion_Wheel.addPropertyArray("y", [0]);
__motion_Wheel.addPropertyArray("scaleX", [1.00]);
__motion_Wheel.addPropertyArray("scaleY", [1.00]);
__motion_Wheel.addPropertyArray("skewX", [0]);
__motion_Wheel.addPropertyArray("skewY", [0]);
__motion_Wheel.addPropertyArray("rotationConcat",
[
0,-13.2143,-26.4285,-39.6428,-52.8571,-66.0714,-79.2857,-92.4999,-105.714,
-118.929,-132.143,-145.357,-158.571,-171.786,-185,-198.214,-211.429,-224.643,
-237.857,-251.071,-264.286,-277.5,-290.714,-303.929,-317.143,-330.357,
-343.571,-356.786,-370
]
);
__motion_Wheel.addPropertyArray("blendMode", ["normal"]);

Leaf_1 .
x y 100 . ,
Z.
rotationZ.
__motion_Leaf_1 = new MotionBase();
__motion_Leaf_1.duration = 100;
__motion_Symbol1_4.addPropertyArray("y",
[
0,5.91999,11.84,17.76,23.68,29.6,35.52,41.44,47.36,53.28,59.2,65.12,71.04,
76.96,82.88,88.8,94.72,100.64,106.56,112.48,118.4,124.32,130.24,136.16,142.08,
148,150.455,152.909,155.364,157.818,160.273,162.727,165.182,167.636,170.091,
172.545,175,177.455,179.909,182.364,184.818,187.273,189.727,192.182,194.636,
197.091,199.545,202,207.433,212.865,218.298,223.73,229.163,234.596,240.028,
245.461,250.893,256.326,261.759,267.191,272.624,278.057,283.489,
288.922,294.354,299.787,305.22,310.652,316.085,321.517,326.95,330.475,334,
337.525,341.05,344.575,348.1,351.625,355.15,358.675,362.2,365.725,369.25,
372.775,376.3,379.825,383.35,386.875,390.4,393.925,397.45,400.975,404.5,
407.5,410.5,413.5,416.5,419.5,422.5,425.5
]
);
__motion_Symbol1_4.addPropertyArray("scaleX", [1.00]);
__motion_Symbol1_4.addPropertyArray("scaleY", [1.00]);
__motion_Symbol1_4.addPropertyArray("skewX", [0]);
__motion_Symbol1_4.addPropertyArray("skewY", [0]);
__motion_Symbol1_4.addPropertyArray("z",
[
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
);

23.11.2012.

366

ACTIONSCRIPT 3.0

__motion_Symbol1_4.addPropertyArray("rotationX", [64.0361]);
__motion_Symbol1_4.addPropertyArray("rotationY", [41.9578]);
__motion_Symbol1_4.addPropertyArray("rotationZ",
[
-18.0336,-17.5536,-17.0736,-16.5936,-16.1136,-15.6336,-15.1536,-14.6736,
-14.1936,-13.7136,-13.2336,-12.7536,-12.2736,-11.7936,-11.3136,-10.8336,
-10.3536,-9.8736,-9.3936,-8.9136,-8.4336,-7.9536,-7.4736,-6.9936,-6.5136,
-6.0336,-7.21542,-8.39723,-9.57905,-10.7609,-11.9427,-13.1245,-14.3063,
-15.4881,-16.67,-17.8518,-19.0336,-20.2154,-21.3972,-22.5791,-23.7609,
-24.9427,-26.1245,-27.3063,-28.4881,-29.67,-30.8518,-32.0336,-31.0771,
-30.1206,-29.164,-28.2075,-27.251,-26.2945,-25.338,-24.3814,-23.4249,
-22.4684,-21.5119,-20.5553,-19.5988,-18.6423,-17.6858,-16.7293,-15.7727
-14.8162,-13.8597,-12.9032,-11.9466,-10.9901,-10.0336,-10.9427,-11.8518,
-12.7609,-13.67,-14.5791,-15.4881,-16.3972,-17.3063,-18.2154,-19.1245,
-20.0336,-20.9427,-21.8518,-22.7609,-23.67,-24.5791,-25.4881,-26.3972,
-27.3063,-28.2154,-29.1245,-30.0336,-28.3193,-26.605,-24.8907,-23.1765,
-21.4622,-19.7479,-18.0336
]
);
__motion_Symbol1_4.addPropertyArray("blendMode", ["normal"]);


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

,
initFilters() addFilterPropertyArray() Motion.


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

initFilters() .
, .
Flash.
, flash.filters.
.
DropShadowFilter, GlowFilter BevelFilter,
Motion.
__motion_Box.initFilters(["flash.filters.DropShadowFilter", "flash.filters.GlowFilter",
"flash.filters.BevelFilter"], [0, 0, 0]);

23.11.2012.

367

368

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0 , Flash CS3

addFilterPropertyArray() ,
.
1 .

, initFilters().
2 ,

.
3 .

initFilters() addFilterPropertyArray()
5 blurX blurY DropShadowFilter. DropShadowFilter
( 0) .
__motion_Box.addFilterPropertyArray(0, "blurX", [5]);
__motion_Box.addFilterPropertyArray(0, "blurY", [5]);

, -
GlowFilter, ( 1) .
__motion_Box.addFilterPropertyArray(1, "quality", [BitmapFilterQuality.LOW]);
__motion_Box.addFilterPropertyArray(1, "alpha", [1.00]);
__motion_Box.addFilterPropertyArray(1, "color", [0xff0000]);

shadowAlpha, shadowColor, highlightAlpha


highlightColor BevelFilter, ( 2)
.
__motion_Box.addFilterPropertyArray(2,
__motion_Box.addFilterPropertyArray(2,
__motion_Box.addFilterPropertyArray(2,
__motion_Box.addFilterPropertyArray(2,

"shadowAlpha", [1.00]);
"shadowColor", [0x000000]);
"highlightAlpha", [1.00]);
"highlightColor", [0xffffff]);

ColorMatrixFilter
Flash Player 9 , Adobe AIR 1.0 , Flash CS3

ColorMatrixFilter AdjustColor,
, , .
, Flash , AdjustColor;
ActionScript.
.

23.11.2012.

ACTIONSCRIPT 3.0

__motion_Leaf_1.initFilters(["flash.filters.ColorMatrix"], [0], -1, -1);


__motion_Leaf_1.addFilterPropertyArray(0, "adjustColorBrightness", [0], -1, -1);
__motion_Leaf_1.addFilterPropertyArray(0, "adjustColorContrast", [0], -1, -1);
__motion_Leaf_1.addFilterPropertyArray(0, "adjustColorSaturation",
[
0,-0.589039,1.17808,-1.76712,-2.35616,-2.9452,-3.53424,-4.12328,
-4.71232,-5.30136,-5.89041, 6.47945,-7.06849,-7.65753,-8.24657,
-8.83561,-9.42465,-10.0137,-10.6027,-11.1918,11.7808,-12.3699,
-12.9589,-13.5479,-14.137,-14.726,-15.3151,-15.9041,-16.4931,
17.0822,-17.6712,-18.2603,-18.8493,-19.4383,-20.0274,-20.6164,
-21.2055,-21.7945,22.3836,-22.9726,-23.5616,-24.1507,-24.7397,
-25.3288,-25.9178,-26.5068,-27.0959,27.6849,-28.274,-28.863,-29.452,
-30.0411,-30.6301,-31.2192,-31.8082,-32.3973,32.9863,-33.5753,
-34.1644,-34.7534,-35.3425,-35.9315,-36.5205,-37.1096,-37.6986,
38.2877,-38.8767,-39.4657,-40.0548,-40.6438,-41.2329,-41.8219,
-42.411,-43
],
-1, -1);
__motion_Leaf_1.addFilterPropertyArray(0, "adjustColorHue",
[
0,0.677418,1.35484,2.03226,2.70967,3.38709,4.06451,4.74193,5.41935,
6.09677,6.77419,7.45161,8.12903,8.80645,9.48387,10.1613,10.8387,11.5161,
12.1935,12.871,13.5484,14.2258,14.9032,15.5806,16.2581,16.9355,17.6129,
18.2903,18.9677,19.6452,20.3226,21,22.4286,23.8571,25.2857,26.7143,28.1429,
29.5714,31,32.4286,33.8571,35.2857,36.7143,38.1429,39.5714,41,42.4286,43.8571,
45.2857,46.7143,48.1429,49.5714,51,54,57,60,63,66,69,72,75,78,81,84,87,
90,93,96,99,102,105,108,111,114
],
-1, -1);

Flash Player 9 , Adobe AIR 1.0 , Flash CS3




, .
AnimatorFactory .
AnimatorFactory Motion.
var __animFactory_Wheel:AnimatorFactory = new AnimatorFactory(__motion_Wheel);

addTarget() AnimatorFactory,
. ActionScript, Flash addTarget()
.
// __animFactory_Wheel.addTarget(<instance name goes here>, 0);

23.11.2012.

369

ACTIONSCRIPT 3.0

, .
greenWheel redWheel.
__animFactory_Wheel.AnimatorFactory.addTarget(greenWheel, 0);
__animFactory_Wheel.AnimationFactory.addTarget(redWheel, 0);

,
addTarget().

23.11.2012.

370

371

18.

Flash Player 10 , Adobe AIR 1.5 , Flash CS4



() .
,
, .
. ,
.
. ,
Adobe Flash Professional.
ActionScript. , Flash Professional,
, . ActionScript
.
Flash Professional CS5
, .

. ,
.
Flash Professional.


fl.ik


Flash Player 10 , Adobe AIR 1.5 , Flash CS4

() ,
.
,
, . ,
, . fl.ik
, .
, , .

23.11.2012.

372

ACTIONSCRIPT 3.0

Flash Professional .
, .
.
Flash Professional.

, .
, ,
.
, .
() ,
.
, , ;
.
, ,
.
, ,


Flash Player 10 , Adobe AIR 1.5 , Flash CS4

Flash Professional, fl.ik ,
.
Wheel. IKArmature
Axle. IKMover . IKBone, ikBone2,
.
A

A. Wheel . Axle . ikBone2

23.11.2012.

ACTIONSCRIPT 3.0


__motion_Wheel (. 364). IKMover
. ,
, .

ActionScript:

;
IKMover;
.
import fl.ik.*
var
var
var
var

tree:IKArmature = IKManager.getArmatureByName("Axle");
bone:IKBone = tree.getBoneByName("ikBone2");
endEffector:IKJoint = bone.tailJoint;
pos:Point = endEffector.position;

var ik:IKMover = new IKMover(endEffector, pos);


ik.limitByDistance = true;
ik.distanceLimit = 0.1;
ik.limitByIteration = true;
ik.iterationLimit = 10;
Wheel.addEventListener(Event.ENTER_FRAME, frameFunc);
function frameFunc(event:Event)
{
if (Wheel != null)
{
var mat:Matrix = Wheel.transform.matrix;
var pt = new Point(90, 0);
pt = mat.transformPoint(pt);
ik.moveTo(pt);
}
}

23.11.2012.

373

ACTIONSCRIPT 3.0

IKArmature: , , ;
Flash. Professional

IKManager: - ;
Flash Professional.

IKBone: .
IKJoint:
IKMover: .
. ik.


Flash Player 10 , Adobe AIR 1.5 , Flash CS4

-, , , ,
.
getArmatureByName() IKManager,
Axle IKArmature tree. Axle Flash
Professional.
var tree:IKArmature = IKManager.getArmatureByName("Axle");

getBoneByName() IKArmature,
IKBone ikBone2.
var bone:IKBone = tree.getBoneByName("ikBone2");

ikBone2 , .
endEffector tailjoint ikBone2.
var endEffector:IKJoint = home.tailjoint;

pos , endEffector.
var pos:Point = endEffector.position;

pos , .
position IKJoint.

23.11.2012.

374

375

ACTIONSCRIPT 3.0

IK Mover

Flash Player 10 , Adobe AIR 1.5 , Flash CS4



IKMover .
IKMover ik, ,
, .
var ik:IKMover = new IKMover(endEffector, pos);

IKMover .
, .
.
Boolean, , , , .
Boolean

Integer

limitByDistance:Boolean

distanceLimit:int

,
.

limitByIteration:Boolean

iterationLimit:int

,
.

limitByTime:Boolean

timeLimit:int

,
.

Boolean false, ,
Boolean true. ,
true, .
, Boolean,
.
IKMover.
0,1
. .
ik.limitByDistance = true;
ik.distanceLimit = 0.1;
ik.limitByIteration = true;
ik.iterationLimit = 10;

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 10 , Adobe AIR 1.5 , Flash CS4

IKMover .
enterFrame . moveTo() IKMover
,
limitByDistance, limitByIteration limitByTime.
Wheel.addEventListener(Event.ENTER_FRAME, frameFunc);
function frameFunc(event:Event)
{
if (Wheel != null)
{
var mat:Matrix = Wheel.transform.matrix;
var pt = new Point(90,0);
pt = mat.transformPoint(pt);
ik.moveTo(pt);
}
}


Flash Player 10 , Adobe AIR 1.5 , Flash CS5

Flash Professional CS5 .
,
. Spring . :
IKJoint.springStrength, , IKJoint.springDamping,
, .
0 ( ) 100 ( ,
). .
( X Y, ), .
0 ( ) 100 (
). ,
.
, IKArmature,
IKArmature.springsEnabled .
IKJoint. X Y.

IKJoint.setSpringAngle,
IKJoint.setSpringPt.

23.11.2012.

376

ACTIONSCRIPT 3.0

tailJoint.
, , ,
.
var arm:IKArmature = IKManager.getArmatureAt(0);
var bone:IKBone = arm.getBoneByName("c");
var joint:IKJoint = bone.tailJoint;
if (arm.springsEnabled) {
joint.springStrength = 50; //medium spring strength
joint.springDamping = 10; //light damping resistance
if (joint.hasSpringAngle) {
joint.setSpringAngle(30); //set angle for rotational spring
}
}


Flash Player 10 , Adobe AIR 1.5 , Flash CS4

IKEvent , .
IKEvent ,
, .

. , ,
,
, IKMover.
var ikmover:IKMover = new IKMover(endjoint, pos);
ikMover.limitByTime = true;
ikMover.timeLimit = 1000;
ikmover.addEventListener(IKEvent.TIME_LIMIT, timeLimitFunction);
function timeLimitFunction(evt:IKEvent):void
{
trace("timeLimit hit");
trace("time is " + evt.time);
trace("distance is " + evt.distance);
trace("iterationCount is " + evt.iterationCount);
trace("IKJoint is " + evt.joint.name);
}

23.11.2012.

377

378

19. (3D)
Flash Player 10 , Adobe AIR 1.5
Flash Player AIR 3D- .
Flash .
Flash, . Flash Player 11
AIR 3 3D- API Stage3D.
Stage3D . 3D-
, Flash (
StageVideo). Flash DisplayObject
3D- ( OpenGL Direct3D).
.
,
.
Stage3D API- .
3D-, Stage3D.
( ).
3D- Stage3D, 3D . Flash Player Developer Center: Stage 3D.

Flash Player 10 , Adobe AIR 1.5


(2D) (3D) ,
, , .
.
z ,
.
.
, .
x/y, , z.
: x, y z.
.

, .
,

23.11.2012.

ACTIONSCRIPT 3.0
(3D)

;
.
( ) ,
.
, ,
, .

.
, ,

.

x, y z.
Vertex .
, .
UV- . UV-


(U) (V) .
T

.
.
, .

Flash Player
AIR
Flash Player 10 , Adobe AIR 1.5
Flash Player Flash Player 10 Adobe AIR Adobe AIR 1.5
: x y, . Flash
Player 10 Adobe AIR 1.5, ActionScript z,
z, .
Flash Player 10 Adobe AIR 1.5 . ,
. , MovieClip Sprite,
.
, , -
.
x y .
.
ActionScript .
ActionScript x
x, y y.
z, .

23.11.2012.

379

ACTIONSCRIPT 3.0
(3D)

(0,0,0)

x, y z ActionScript.
A. + Z . . + X . + Y

. , Flash Player AIR


. , A
, Flash Player AIR A
z .
z transform.getRelativeMatrix3D()
, . .
Matrix3D 390.
ActionScript :
1 flash.display.DisplayObject z, rotation scaling

.
DisplayObject.local3DToGlobal()
.
2 flash.geom.Vector3D

. .
3 flash.geom.Matrix3D , ,

, .
4 flash.geom.PerspectiveProjection

.
ActionScript .
1 .

x, y z
rotation scaling DisplayObject.
DisplayObject.transform.matrix3D.
DisplayObject.transform.perspectiveProjection
. ,
.
,
.

23.11.2012.

380

ACTIONSCRIPT 3.0
(3D)

.
,
. ,
Graphics.drawTriangles() Graphics.
, ,
.

Flash Player 10 , Adobe AIR 1.5



z . z
Transform. DisplayObject.rotationX
DisplayObject.rotationY Transform. Transform
Matrix3D, .
leaf:
leaf.x = 100; leaf.y = 50; leaf.z = -30;

, matrix3D Transform
leaf.
var leafMatrix:Matrix3D

= leaf.transform.matrix3D;

trace(leafMatrix.position.x);
trace(leafMatrix.position.y);
trace(leafMatrix.position.z);
trace(leafMatrix.position.length);
trace(leafMatrix.position.lengthSquared);

Transform . Transform.
Matrix3D . Matrix3D.

;
Flash Player 10 , Adobe AIR 1.5
x, y, z.
z , .
z
z . ellipse2 ellipse1: z
20 Frame, z ellipse1 10 .

23.11.2012.

381

ACTIONSCRIPT 3.0
(3D)

var depth:int = 1000;


function ellipse1FrameHandler(e:Event):void
{
ellipse1Back = setDepth(e, ellipse1Back);
e.currentTarget.z += ellipse1Back * 10;
}
function ellipse2FrameHandler(e:Event):void
{
ellipse2Back = setDepth(e, ellipse1Back);
e.currentTarget.z += ellipse1Back * 20;
}
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;
}
}

;
Flash Player 10 , Adobe AIR 1.5
,
: rotationX, rotationY rotationZ.
:


rotationY y.
:

23.11.2012.

382

ACTIONSCRIPT 3.0
(3D)

container.rotationY += 10;

rotationX .
x.

rotationZ .
z.



Flash Player 10 , Adobe AIR 1.5
PerspectiveProjection flash.geom
.
,
PerspectiveProjection ,
.
, PerspectiveProjection:

fieldOfView;

projectionCenter;

focalLength.

23.11.2012.

383

ACTIONSCRIPT 3.0
(3D)

fieldOfView focalLength
, .
focalLength fieldOfView
:
focalLength = stageWidth/2 * (cos(fieldOfView/2) / sin(fieldOfView/2)

, fieldOfView .


Flash Player 10 , Adobe AIR 1.5
fieldOfView PerspectiveProjection
,
.
fieldOfView 0 180 , .
, , ,
z. fieldOfView ,
, .
fieldOfView , ,
. (179.9999 )
. fieldOfView 179.9999...,
0.00001... 0 180 .


Flash Player 10 , Adobe AIR 1.5
projectionCenter .
(0,0),
.
, .
. ,
.
, .
projectionCenter . ,
, ,
, projectionCenter ,
.


Flash Player 10 , Adobe AIR 1.5
focalLength (0,0,0)
z.

23.11.2012.

384

ACTIONSCRIPT 3.0
(3D)


.
. ,
.
, focalLength
, .


Flash Player 10 , Adobe AIR 1.5
PerspectiveProjection , , :

fieldOfView: 55

perspectiveCenter: stagewidth/2, stageHeight/2

focalLength: stageWidth/ 2 * ( cos(fieldOfView/2) / sin(fieldOfView/2) )

, PerspectiveProjection.
projectionCenter fieldOfView
PerspectiveProjection. ,
500500:

fieldOfView: 55

perspectiveCenter: 250,250

focalLength: 480.24554443359375

:
Flash Player 10 , Adobe AIR 1.5
.

projectionCenter.
focalLength fieldOfView .
:
1 center, ;
2 center projectionCenter perspectiveProjection

transform ;
3 , ,
projectionCenter , center;

4 , .

, ProjectionDragger.swf,
. ,
. , , ,
.

23.11.2012.

385

ACTIONSCRIPT 3.0
(3D)


www.adobe.com/go/learn_programmingAS3samples_flash_ru. ProjectionDragger
Samples/ProjectionDragger.
package
{
import flash.display.Sprite;
import flash.display.Shape;
import flash.geom.Point;
import flash.events.*;
public class ProjectionDragger extends Sprite
{
private var center : Sprite;
private var boxPanel:Shape;
private var inDrag:Boolean = false;
public function ProjectionDragger():void
{
createBoxes();
createCenter();
}
public function createCenter():void
{
var centerRadius:int = 20;
center = new Sprite();
// circle
center.graphics.lineStyle(1, 0x000099);
center.graphics.beginFill(0xCCCCCC, 0.5);
center.graphics.drawCircle(0, 0, centerRadius);
center.graphics.endFill();
// cross hairs
center.graphics.moveTo(0, centerRadius);
center.graphics.lineTo(0, -centerRadius);
center.graphics.moveTo(centerRadius, 0);
center.graphics.lineTo(-centerRadius, 0);
center.x = 175;
center.y = 175;
center.z = 0;
this.addChild(center);
center.addEventListener(MouseEvent.MOUSE_DOWN, startDragProjectionCenter);
center.addEventListener(MouseEvent.MOUSE_UP, stopDragProjectionCenter);
center.addEventListener( MouseEvent.MOUSE_MOVE, doDragProjectionCenter);
root.transform.perspectiveProjection.projectionCenter = new Point(center.x,
center.y);
}
public function createBoxes():void
{
// createBoxPanel();
var boxWidth:int = 50;
var boxHeight:int = 50;
var numLayers:int = 12;
var depthPerLayer:int = 50;
// var boxVec:Vector.<Shape> = new Vector.<Shape>(numLayers);

23.11.2012.

386

ACTIONSCRIPT 3.0
(3D)

boxHeight,
boxHeight,
boxHeight,
boxHeight,

for (var i:int = 0; i < numLayers; i++)


{
this.addChild(createBox(150, 50, (numLayers - i) * depthPerLayer, boxWidth,
0xCCCCFF));
this.addChild(createBox(50, 150, (numLayers - i) * depthPerLayer, boxWidth,
0xFFCCCC));
this.addChild(createBox(250, 150, (numLayers - i) * depthPerLayer, boxWidth,
0xCCFFCC));
this.addChild(createBox(150, 250, (numLayers - i) * depthPerLayer, boxWidth,
0xDDDDDD));
}

}
public function createBox(xPos:int = 0, yPos:int = 0, zPos:int = 100, w:int = 50, h:int
= 50, color:int = 0xDDDDDD):Shape
{
var box:Shape = new Shape();
box.graphics.lineStyle(2, 0x666666);
box.graphics.beginFill(color, 1.0);
box.graphics.drawRect(0, 0, w, h);
box.graphics.endFill();
box.x = xPos;
box.y = yPos;
box.z = zPos;
return box;
}
public function startDragProjectionCenter(e:Event)
{
center.startDrag();
inDrag = true;
}
public function doDragProjectionCenter(e:Event)
{
if (inDrag)
{
root.transform.perspectiveProjection.projectionCenter = new Point(center.x,
center.y);
}
}
public function stopDragProjectionCenter(e:Event)
{
center.stopDrag();
root.transform.perspectiveProjection.projectionCenter = new Point(center.x,
center.y);
inDrag = false;
}
}
}

Matrix3D.

23.11.2012.

387

ACTIONSCRIPT 3.0
(3D)


Flash Player 10 , Adobe AIR 1.5
Matrix3D
.
Matrix3D .
.
.
z
Matrix3D Transform.
var leafMatrix:Matrix3D = this.transform.matrix3D;

Matrix3D , ,
.
Vector3D x, y z.
, .
Vector3D , ,
, .
. Vector3D Vector ActionScript. Vector3D
, Vector
.

Matrix3D
Flash Player 10 , Adobe AIR 1.5
Matrix3D:
1 Matrix3D() . Matrix3D()

Vector, 16 ,
. :
var rotateMatrix:Matrix3D = new Matrix3D(1,0,0,1, 0,1,0,1, 0,0,1,1, 0,0,0,1);

2 z .

transform.matrix3D .
3 Matrix3D,

perspectiveProjection.matrix3D
.

23.11.2012.

388

ACTIONSCRIPT 3.0
(3D)


Flash Player 10 , Adobe AIR 1.5
Matrix3D
. , , , ,
.
Matrix3D,
.
. , .
. ,
, .
.
package {
import
import
import
import

flash.display.Sprite;
flash.display.Shape;
flash.display.Graphics;
flash.geom.*;

public class Matrix3DTransformsExample extends Sprite


{
private var rect1:Shape;
private var rect2:Shape;
public function Matrix3DTransformsExample():void
{
var pp:PerspectiveProjection = this.transform.perspectiveProjection;
pp.projectionCenter = new Point(275,200);
this.transform.perspectiveProjection = pp;
rect1 = new Shape();
rect1.x = -70;
rect1.y = -40;
rect1.z = 0;
rect1.graphics.beginFill(0xFF8800);
rect1.graphics.drawRect(0,0,50,80);
rect1.graphics.endFill();
addChild(rect1);
rect2 = new Shape();
rect2.x = 20;
rect2.y = -40;
rect2.z = 0;
rect2.graphics.beginFill(0xFF0088);
rect2.graphics.drawRect(0,0,50,80);
rect2.graphics.endFill();
addChild(rect2);

23.11.2012.

389

ACTIONSCRIPT 3.0
(3D)

doTransforms();
}
private function doTransforms():void
{
rect1.rotationX = 15;
rect1.scaleX = 1.2;
rect1.x += 100;
rect1.y += 50;
rect1.rotationZ = 10;
var matrix:Matrix3D = rect2.transform.matrix3D;
matrix.appendRotation(15, Vector3D.X_AXIS);
matrix.appendScale(1.2, 1, 1);
matrix.appendTranslation(100, 50, 0);
matrix.appendRotation(10, Vector3D.Z_AXIS);
rect2.transform.matrix3D = matrix;
}
}
}

doTransforms() DisplayObject ,
. Matrix3D
.
Matrix3D ,
.
transform.matrix3D. DisplayObject
.
.

Matrix3D .

Matrix3D
Flash Player 10 , Adobe AIR 1.5
,
z.
, ,
,
z. , ,
, , .

, , :
1 getRelativeMatrix3D() Transform zaxes .

2 removeChild() .
3 z.
4 addChild()

23.11.2012.

390

ACTIONSCRIPT 3.0
(3D)


z.
.
:
public var faces:Array; . . .
public function ReorderChildren()
{
for(var ind:uint = 0; ind < 6; ind++)
{
faces[ind].z = faces[ind].child.transform.getRelativeMatrix3D(root).position.z;
this.removeChild(faces[ind].child);
}
faces.sortOn("z", Array.NUMERIC | Array.DESCENDING);
for (ind = 0; ind < 6; ind++)
{
this.addChild(faces[ind].child);
}
}


www.adobe.com/go/learn_programmingAS3samples_flash_ru.
Samples/ReorderByZ.



Flash Player 10 , Adobe AIR 1.5
ActionScript
Graphics.drawTriangles(),
. ( Flash Player AIR ,
, . .
Flash Player AIR 379.)
Graphics.drawTriangles() Graphics.drawPath(),
.
Graphics.drawPath() .
253.
Graphics.drawTriangles() Vector.<Number>
:
drawTriangles(vertices:Vector.<Number>, indices:Vector.<int> = null, uvtData:Vector.<Number>
= null, culling:String = "none"):void

drawTriangles() vertices.
, ,
. ( ) .
indices, ,
( x/y). :

23.11.2012.

391

ACTIONSCRIPT 3.0
(3D)

graphics.beginFill(0xFF8000);
graphics.drawTriangles(
Vector.<Number>([
10,10, 100,10, 10,100,
110,10, 110,100, 20,100]));

,
drawTriangles(), indices,
vertices .
indices , indices ,
vertices. , vertices,
indices, , 2. ,
vertices 2 indices, ,
4.
, indices ,
.
graphics.beginFill(0xFF8000);
graphics.drawTriangles(
Vector.<Number>([10,10, 100,10, 10,100, 100,100]),
Vector.<int>([0,1,2, 1,3,2]));

, ,
vertices. indices, , ,
. 6 (12 )
4 (8 ).

, vertices

,
.
.
, .

23.11.2012.

392

ACTIONSCRIPT 3.0
(3D)


Flash Player 10 , Adobe AIR 1.5

. , ,
.
,
.

, .

UV-
Flash Player 10 , Adobe AIR 1.5
uvtData drawTriangles().
UV- .
UV- . : U
(x) V (y). , .
0 U 0 V , 1 U 1 V .

UV 0 1

UV-
.

23.11.2012.

393

ACTIONSCRIPT 3.0
(3D)

UV-

UV- .

, UV-

ActionScript , ,
UV-.
UV-.
Graphics.drawTriangles()
: T. T uvtData ,
. UVT-
UV-. ,
, 50%
0,5. ,
z. T.
T = focalLength/(focalLength + z);

focalLength ,
, .

23.11.2012.

394

395

ACTIONSCRIPT 3.0
(3D)

z
A. . . . focalLength . z

, . ,
. UVT-

.
UVT- T UV,
. T uvtData (U, V T)
vertices (x y). UV uvtData.length ==
vertices.length. T uvtData.length = 1.5*vertices.length.
,
UVT. ocean.jpg
ImageLoader, ocean.jpg BitmapData.
ImageLoader (
ImageLoader.as).

23.11.2012.

ACTIONSCRIPT 3.0
(3D)

package {
import flash.display.*
import flash.events.*;
import flash.net.URLRequest;
public class ImageLoader extends Sprite {
public var url:String;
public var bitmap:Bitmap;
public function ImageLoader(loc:String = null) {
if (loc != null){
url = loc;
loadImage();
}
}
public function loadImage():void{
if (url != null){
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
var req:URLRequest = new URLRequest(url);
loader.load(req);
}
}
private function onComplete(event:Event):void {
var loader:Loader = Loader(event.target.loader);
var info:LoaderInfo = LoaderInfo(loader.contentLoaderInfo);
this.bitmap = info.content as Bitmap;
this.dispatchEvent(new Event(Event.COMPLETE));
}
private function onIoError(event:IOErrorEvent):void {
trace("onIoError: " + event);
}
}
}

ActionScript , UV- T ,
.
Spinning3dOcean.as:

23.11.2012.

396

ACTIONSCRIPT 3.0
(3D)

package {
import flash.display.*
import flash.events.*;
import flash.utils.getTimer;
public class Spinning3dOcean extends Sprite {
// plane vertex coordinates (and t values)
var x1:Number = -100,y1:Number = -100,z1:Number = 0,t1:Number = 0;
var x2:Number = 100,y2:Number = -100,z2:Number = 0,t2:Number = 0;
var x3:Number = 100,y3:Number = 100,z3:Number = 0,t3:Number = 0;
var x4:Number = -100,y4:Number = 100,z4:Number = 0,t4:Number = 0;
var focalLength:Number = 200;
// 2 triangles for 1 plane, indices will always be the same
var indices:Vector.<int>;
var container:Sprite;
var bitmapData:BitmapData; // texture
var imageLoader:ImageLoader;
public function Spinning3dOcean():void {
indices = new Vector.<int>();
indices.push(0,1,3, 1,2,3);
container = new Sprite(); // container to draw triangles in
container.x = 200;
container.y = 200;
addChild(container);
imageLoader = new ImageLoader("ocean.jpg");
imageLoader.addEventListener(Event.COMPLETE, onImageLoaded);
}
function onImageLoaded(event:Event):void {
bitmapData = imageLoader.bitmap.bitmapData;
// animate every frame
addEventListener(Event.ENTER_FRAME, rotatePlane);
}
function rotatePlane(event:Event):void {
// rotate vertices over time
var ticker = getTimer()/400;
z2 = z3 = -(z1 = z4 = 100*Math.sin(ticker));
x2 = x3 = -(x1 = x4 = 100*Math.cos(ticker));
// calculate t values

23.11.2012.

397

398

ACTIONSCRIPT 3.0
(3D)

t1
t2
t3
t4

=
=
=
=

focalLength/(focalLength
focalLength/(focalLength
focalLength/(focalLength
focalLength/(focalLength

+
+
+
+

z1);
z2);
z3);
z4);

// determine triangle vertices based on t values


var vertices:Vector.<Number> = new Vector.<Number>();
vertices.push(x1*t1,y1*t1, x2*t2,y2*t2, x3*t3,y3*t3, x4*t4,y4*t4);
// set T values allowing perspective to change
// as each vertex moves around in z space
var uvtData:Vector.<Number> = new Vector.<Number>();
uvtData.push(0,0,t1, 1,0,t2, 1,1,t3, 0,1,t4);
// draw
container.graphics.clear();
container.graphics.beginBitmapFill(bitmapData);
container.graphics.drawTriangles(vertices, indices, uvtData);
}
}
}

,
ocean.jpg. , ,
.

Flash Player 10 , Adobe AIR 1.5


, ,
, .
, ,
.
A

.
A. . .

, .
Flash Player AIR.
, ,
. , .
,
. ,
. Flash Player AIR ,
.

23.11.2012.

ACTIONSCRIPT 3.0
(3D)

Graphics.drawTriangles() :
public function drawTriangles(vertices:Vector.<Number>, indices:Vector.<int> = null,
uvtData:Vector.<Number> = null, culling:String = "none"):void

TriangleCulling: TriangleCulling.NONE,
TriangleCulling.POSITIVE TriangleCulling.NEGATIVE.
, . API- ActionScript
, , ,
. ,
. ( ).
, TriangleCulling POSITIVE
( ). TriangleCulling NEGATIVE
( ). c ,
, , , , ,
.

. ;

UV 393, drawTriangles()
TriangleCulling.NEGATIVE.
container.graphics.drawTriangles(vertices, indices, uvtData, TriangleCulling.NEGATIVE);

, , .

23.11.2012.

399

400

20.
Flash Player 9 , Adobe AIR 1.0
Adobe Flash Player Adobe AIR
TextField Flash Text Engine. ,
. Text Layout Framework (TLF) -
Flash Text Engine.
StageText.
,
. ,
.
TextField, Flash Text Engine Flash Player
AIR. TextField , .
TextField , TextArea TextInput.
TextFormat TextField,
Textfield.styleSheet StyleSheet
(Cascading Style Sheets, CSS). HTML,
( , SWF-, GIF-,
PNG- JPEG-).
Flash TextEngine (FTE), Flash Player 10 AIR 1.5,
,
.
. , Flash Text Engine
, , ,
. Text Layout Framework,
, Flash Text Engine,
. Text Layout Framework ,
ActionScript 3.0. TLF,
.
StageText, AIR 3, . ,
,
. StageText .
,
. StageText .
. .

TextField 402
Flash Text Engine 427
Text Layout Framework 457
Native text input with StageText ( StageText)

23.11.2012.

ACTIONSCRIPT 3.0


, .

, XML ( HTML).
, .
,
ActionScript, .
, SWF- .
HTML- , ActionScript
.
,
ActionScript.
Kerning

.
, ,
SWF-.
,

, , ( ,
) . .

.

23.11.2012.

401

402

21.
TextField
Flash Player 9 , Adobe AIR 1.0
TextField
Adobe Flash Player Adobe AIR. TextField
, TextArea TextInput.
SWF-,
.
HTML-, ,
HTML.
flash.text, TextFormat StyleSheet. flash.text
, , ActionScript.
TextField
. HTML-,
StyleSheet, . TextFormat StyleSheet
, , , .
TextFormat . ,
,
.
flash.text flash.events.TextEvent,
, .


410
HTML- 404
411


Flash Player 9 , Adobe AIR 1.0
, Adobe Flash Builder Flash Professional,
, ,
.

23.11.2012.

ACTIONSCRIPT 3.0
TextField


Flash Player 9 , Adobe AIR 1.0
.


, , ,
, XML- web-.


, , ,
.
flash.text.TextFormat
. . 408.


Flash Professional.
ActionScript 3.0. ActionScript, StaticText TextSnapshot,
.
. 416.


Flash Player 9 , Adobe AIR 1.0
, flash.text.TextField.text.
, :
myTextField.text = "Hello World";

text , ,
:
package
{
import flash.display.Sprite;
import flash.text.*;
public class TextWithImage extends Sprite
{
private var myTextBox:TextField = new TextField();
private var myText:String = "Hello World";
public function TextWithImage()
{
addChild(myTextBox);
myTextBox.text = myText;
}
}
}

23.11.2012.

403

ACTIONSCRIPT 3.0
TextField

text .
:

flash.net.URLLoader flash.net.URLRequest
.

HTML-, SWF-, FlashVars,


.

flash.net.SharedObject .
. 753.

HTML-
Flash Player 9 , Adobe AIR 1.0
flash.text.TextField htmlText,
HTML- . ,
Flash Player AIR HTML
htmlText ( text).
var myText:String = "<p>This is <b>some</b> content to <i>render</i> as <u>HTML</u> text.</p>";
myTextBox.htmlText = myText;

Flash Player AIR HTML htmlText.


HTML .
flash.text.TextField.htmlText ActionScript 3.0 Adobe Flash Professional CS5.
htmlText, textformat
. .
410.


Flash Player 9 , Adobe AIR 1.0
HTML- ,
.
img, .
myTextBox,
JPG, , SWF-.

23.11.2012.

404

ACTIONSCRIPT 3.0
TextField

package
{
import flash.display.Sprite;
import flash.text.*;
public class TextWithImage extends Sprite
{
private var myTextBox:TextField;
private var myText:String = "<p>This is <b>some</b> content to <i>test</i> and
<i>see</i></p><p><img src='eye.jpg' width='20' height='20'></p><p>what can be
rendered.</p><p>You should see an eye image and some <u>HTML</u> text.</p>";
public function TextWithImage()
{
myTextBox.width = 200;
myTextBox.height = 200;
myTextBox.multiline = true;
myTextBox.wordWrap = true;
myTextBox.border = true;
addChild(myTextBox);
myTextBox.htmlText = myText;
}
}
}

img JPEG, GIF, PNG SWF.


Flash Player 9 , Adobe AIR 1.0
, .
, .
flash.text.TextField, ,
.
TextField.scrollV, TextField.scrollH, maxScrollV maxScrollH.
, .
, ,
. ,
.

23.11.2012.

405

ACTIONSCRIPT 3.0
TextField

package
{
import flash.display.Sprite;
import flash.text.*;
import flash.events.MouseEvent;
public class TextScrollExample extends Sprite
{
private var myTextBox: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()
{
myTextBox.text = myText;
myTextBox.width = 200;
myTextBox.height = 50;
myTextBox.multiline = true;
myTextBox.wordWrap = true;
myTextBox.background = true;
myTextBox.border = true;
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0xFF0000;
format.size = 10;
myTextBox.defaultTextFormat = format;
addChild(myTextBox);
myTextBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
}
public function mouseDownScroll(event:MouseEvent):void
{
myTextBox.scrollV++;
}
}
}


Flash Player 9 , Adobe AIR 1.0
.
TextField ,
, .
. Flash Professional
, , ,
.

23.11.2012.

406

ACTIONSCRIPT 3.0
TextField


Flash Player 9 , Adobe AIR 1.0
flash.text.TextField.selectable true.
, setSelection().
, , ,
:
var myTextField:TextField = new TextField();
myTextField.text = "No matter where you click on this text field the TEXT IN ALL CAPS is selected.";
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
addEventListener(MouseEvent.CLICK, selectText);
function selectText(event:MouseEvent):void
{
myTextField.setSelection(49, 65);
}

, , ,
,
.

,
Flash Player 9 , Adobe AIR 1.0
selectionBeginIndex selectionEndIndex TextField ,
. ,
. , caretIndex.
, , .
var myTextField:TextField = new TextField();
myTextField.text = "Please select the TEXT IN ALL CAPS to see the index values for the first
and last letters.";
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
addEventListener(MouseEvent.MOUSE_UP, selectText);
function selectText(event:MouseEvent):void
{
trace("First letter index position: " + myTextField.selectionBeginIndex);
trace("Last letter index position: " + myTextField.selectionEndIndex);
}


TextFormat. TextFormat
. 413.

23.11.2012.

407

408

ACTIONSCRIPT 3.0
TextField


Flash Player 9 , Adobe AIR 1.0
type dynamic. type
input TextFieldType
.
, .
, myTextBox.
textInput. textInputCapture
. Flash Player AIR
myOutputBox.
package
{
import
import
import
import

flash.display.Sprite;
flash.display.Stage;
flash.text.*;
flash.events.*;

public class CaptureUserInput extends


{
private var myTextBox:TextField =
private var myOutputBox:TextField
private var myText:String = "Type

Sprite
new TextField();
= new TextField();
your text here.";

public function CaptureUserInput()


{
captureText();
}
public function captureText():void
{
myTextBox.type = TextFieldType.INPUT;
myTextBox.background = true;
addChild(myTextBox);

23.11.2012.

ACTIONSCRIPT 3.0
TextField

myTextBox.text = myText;
myTextBox.addEventListener(TextEvent.TEXT_INPUT, textInputCapture);
}
public function textInputCapture(event:TextEvent):void
{
var str:String = myTextBox.text;
createOutputBox(str);
}
public function createOutputBox(str:String):void
{
myOutputBox.background = true;
myOutputBox.x = 200;
addChild(myOutputBox);
myOutputBox.text = str;
}
}
}


Flash Player 9 , Adobe AIR 1.0
,
,
, , , . flash.text.TextField
displayAsPassword restrict, .
displayAsPassword , ,
. displayAsPassword true, ,
. ,
displayAsPassword , , , background color.
myTextBox.type = TextFieldType.INPUT;
myTextBox.background = true;
myTextBox.displayAsPassword = true;
addChild(myTextBox);

restrict , ,
. ,
, .
( ).
myTextBox.restrict = "A-Z";

ActionScript 3.0 ,
. .
flash.text.TextField.restrict ActionScript 3.0 Adobe Flash Professional CS5.

23.11.2012.

409

ACTIONSCRIPT 3.0
TextField

. flash.text.TextField.restrict,
.
fl.text.TLFTextField.restrict ( TLF),
.


Flash Player 9 , Adobe AIR 1.0
.
TextField, , TextFIeld.thickness, TextField.textColor
TextField.textHeight.
htmlText HTML, , b, i u. ,
TextFormat , , StyleSheet
htmlText. TextFormat StyleSheet
.
TextFormat StyleSheet .


Flash Player 9 , Adobe AIR 1.0
TextFormat
TextField .
TextFormat TextField, TextFormat
TextField.
var tf:TextField = new TextField();
tf.text = "Hello Hello";
var format1:TextFormat = new TextFormat();
format1.color = 0xFF0000;
var format2:TextFormat = new TextFormat();
format2.font = "Courier";
tf.setTextFormat(format1);
var startRange:uint = 6;
tf.setTextFormat(format2, startRange);
addChild(tf);

TextField.setTextFormat() , .
TextField TextField.setTextFormat()
. defaultTextFormat
TextField, , .

23.11.2012.

410

ACTIONSCRIPT 3.0
TextField


Flash Player 9 , Adobe AIR 1.0
HTML.
text , HTML- htmlText.
CSS- ,
. CSS-
CSS-.
flash.text.StyleSheet CSS-. StyleSheet
CSS. , StyleSheet, . flash.textStylesheet
ActionScript 3.0 Adobe Flash Professional CS5.
, CSS- HTML-
StyleSheet.
var style:StyleSheet = new StyleSheet();
var styleObj:Object = new Object();
styleObj.fontSize = "bold";
styleObj.color = "#FF0000";
style.setStyle(".darkRed", styleObj);
var tf:TextField = new TextField();
tf.styleSheet = style;
tf.htmlText = "<span class = 'darkRed'>Red</span> apple";
addChild(tf);

StyleSheet ,
. StyleSheet.setStyle(),
.darkred.
StyleSheet TextField styleSheet.
CSS- , TextField ,
htmlText.
.
, ,
. , ,
API- ActionScript:

TextField.replaceText()
TextField.replaceSelectedText()
TextField.defaultTextFormat
TextField.setTextFormat()
, TextField.styleSheet
null, TextField.text TextField.htmlText
, .
htmlText
null.

23.11.2012.

411

ACTIONSCRIPT 3.0
TextField

CSS-
Flash Player 9 , Adobe AIR 1.0
CSS , CSS
. CSS,
, ActionScript 3.0.
CSS. SWF-.
StyleSheet.parseCSS() CSS StyleSheet.
, CSS-
TextField.
CSS- example.css.
p {
font-family: Times New Roman, Times, _serif;
font-size: 14;
}
h1 {
font-family: Arial, Helvetica, _sans;
font-size: 20;
font-weight: bold;
}
.bluetext {
color: #0000CC;
}

ActionScript , example.css
TextField:
package
{
import
import
import
import
import
import
import

flash.display.Sprite;
flash.events.Event;
flash.net.URLLoader;
flash.net.URLRequest;
flash.text.StyleSheet;
flash.text.TextField;
flash.text.TextFieldAutoSize;

public class CSSFormattingExample extends Sprite


{
var loader:URLLoader;
var field:TextField;
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>";
public function CSSFormattingExample():void
{
field = new TextField();
field.width = 300;

23.11.2012.

412

ACTIONSCRIPT 3.0
TextField

field.autoSize = TextFieldAutoSize.LEFT;
field.wordWrap = true;
addChild(field);
var req:URLRequest = new URLRequest("example.css");
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);
loader.load(req);
}
public function onCSSFileLoaded(event:Event):void
{
var sheet:StyleSheet = new StyleSheet();
sheet.parseCSS(loader.data);
field.styleSheet = sheet;
field.htmlText = exampleText;
}
}
}

CSS onCSSFileLoaded(),
StyleSheet.parseCSS() StyleSheet.


Flash Player 9 , Adobe AIR 1.0
flash.text.TextField setTextFormat(). setTextFormat()
,
(, )
, .
TextField.setTextFormat() ,
myTextField,
.
var myTextField:TextField = new TextField();
myTextField.text = "No matter where you click on this text field the TEXT IN ALL CAPS changes
format.";
myTextField.autoSize = TextFieldAutoSize.LEFT;
addChild(myTextField);
addEventListener(MouseEvent.CLICK, changeText);
var myformat:TextFormat = new TextFormat();
myformat.color = 0xFF0000;
myformat.size = 18;
myformat.underline = true;
function changeText(event:MouseEvent):void
{
myTextField.setTextFormat(myformat, 49, 65);
}

23.11.2012.

413

ACTIONSCRIPT 3.0
TextField


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 flash.text,
, , , -
. , CSMSettings,
Font TextRenderer, ActionScript 3.0 Adobe Flash Professional CS5.


Flash Player 9 , Adobe AIR 1.0
TextField, Flash Player AIR
(, ).

, , . ,
, Times Roman.
, .
.

, ,
.

, , .
, , .
CSS- kerning.
,
.
SWF- .
, TextField .

embedFonts TextField true.


TextFormat, fontFamily
TextFormat TextField.
fontFamily .

, .

CSS TextFields ,
CSS font-family .
, font-family , .
Flash
Flash Professional , ,
TrueType Type 1 Postscript.
, :

font style TextField


;

23.11.2012.

414

ACTIONSCRIPT 3.0
TextField

;
, .
.
Flash.
Flex
Flex , :

[Embed];
@font-face.
[Embed].
Flex TrueType. ,
, Type 1 Postscript, SWF- Flash Professional,
SWF- Flex.
SWF- Flex .
SWF- Flex 4.



(Peter deHaan):
Divillysausages.com: - AS3

,
Flash Player 9 , Adobe AIR 1.0
Flash Player AIR
, , , .
, ,
, . Flash
Player AIR flash.text.TextRenderer , ,
CSMSettings. ,
. .
414.
. flash.text.TextField.antiAliasType
AntiAliasType.ADVANCED, , gridFitType,
TextRenderer.setAdvancedAntiAliasingTable().

(CSM) myFont.
Flash Player Adobe AIR .

23.11.2012.

415

ACTIONSCRIPT 3.0
TextField

var format:TextFormat = new TextFormat();


format.color = 0x336699;
format.size = 48;
format.font = "myFont";
var myText:TextField = new TextField();
myText.embedFonts = true;
myText.autoSize = TextFieldAutoSize.LEFT;
myText.antiAliasType = AntiAliasType.ADVANCED;
myText.defaultTextFormat = format;
myText.selectable = false;
myText.mouseEnabled = true;
myText.text = "Hello World";
addChild(myText);
myText.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:Event):void
{
var myAntiAliasSettings = new CSMSettings(48, 0.8, -0.8);
var myAliasTable:Array = new Array(myAntiAliasSettings);
TextRenderer.setAdvancedAntiAliasingTable("myFont", FontStyle.ITALIC,
TextColorType.DARK_COLOR, myAliasTable);
}


Flash Player 9 , Adobe AIR 1.0
Flash Professional.
ActionScript .
, ( ).
, ,
Flash Professional. ,
, ActionScript 3.0 StaticText.
TextSnapshot.

StaticText
Flash Player 9 , Adobe AIR 1.0
, ,
flash.text.StaticText Flash Professional. ,
ActionScript, SWF-, .
.
Flash Professional.

. :

23.11.2012.

416

ACTIONSCRIPT 3.0
TextField

for (var 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);
}
}

, ActionScript 3.0.
, myFieldLabel
. myField x y,
myFieldLabel, myFieldLabel.
var myField:TextField = new TextField();
addChild(myField);
myField.x = myFieldLabel.x;
myField.y = myFieldLabel.y + 20;
myField.autoSize = TextFieldAutoSize.LEFT;
myField.text = "and " + myFieldLabel.text

TextSnapshot
Flash Player 9 , Adobe AIR 1.0
,
flash.text.TextSnapshot textSnapshot
flash.display.DisplayObjectContainer. , TextSnapshot
DisplayObjectContainer.textSnapshot. , ,
.
, TextSnapshot.
ActionScript 1 :
var mySnap:TextSnapshot = this.textSnapshot;
var count:Number = mySnap.charCount;
mySnap.setSelected(0, 4, true);
mySnap.setSelected(1, 2, false);
var myText:String = mySnap.getSelectedText(false);
trace(myText);

TextSnapshot SWF-,
.

23.11.2012.

417

ACTIONSCRIPT 3.0
TextField

TextField:

Flash Player 9 , Adobe AIR 1.0
News Layout .
, . , News
Layout , .
.
ActionScript:

TextField;
CSS-;
CSS TextFormat;
TextLineMetrics .

www.adobe.com/go/learn_programmingAS3samples_flash_ru. News Layout
Samples/NewsLayout. .
File

NewsLayout.mxml

Flex (MXML) Flash (FLA).

NewsLayout.fla
com/example/programmingas3/ne
wslayout/StoryLayoutComponent.a
s

UIComponent Flex, StoryLayout.

com/example/programmingas3/ne
wslayout/StoryLayout.as

ActionScript, ,
.

com/example/programmingas3/ne
wslayout/FormattedTextField.as

TextField, TextFormat.

com/example/programmingas3/ne
wslayout/HeadlineTextField.as

FormattedTextField,
.

com/example/programmingas3/ne
wslayout/MultiColumnTextField.as

ActionScript, .

story.css

CSS-, .

CSS-
Flash Player 9 , Adobe AIR 1.0
News Layout XML-.
CSS-, ,
.
CSS- : h1 h2
.

23.11.2012.

418

ACTIONSCRIPT 3.0
TextField

p {
font-family: Georgia, "Times New Roman", Times, _serif;
font-size: 12;
leading: 2;
text-align: justify;
indent: 24;
}
h1 {
font-family: Verdana, Arial, Helvetica, _sans;
font-size: 20;
font-weight: bold;
color: #000099;
text-align: left;
}
h2 {
font-family: Verdana, Arial, Helvetica, _sans;
font-size: 16;
font-weight: normal;
text-align: left;
}

CSS- , CSS-
412. CSS- onCSSFileLoaded(),
.
public function onCSSFileLoaded(event:Event):void
{
this.sheet = new StyleSheet();
this.sheet.parseCSS(loader.data);
h1Format = getTextStyle("h1", this.sheet);
if (h1Format == null)
{
h1Format = getDefaultHeadFormat();
}
h2Format = getTextStyle("h2", this.sheet);
if (h2Format == null)
{
h2Format = getDefaultHeadFormat();
h2Format.size = 16;
}
pFormat = getTextStyle("p", this.sheet);
if (pFormat == null)
{
pFormat = getDefaultTextFormat();
pFormat.size = 12;
}
displayText();
}

onCSSFileLoaded() StyleSheet, CSS.


MultiColumnTextField,
StyleSheet. HeadlineTextField,
TextFormat.

23.11.2012.

419

ACTIONSCRIPT 3.0
TextField

onCSSFileLoaded() getTextStyle(), CSS TextFormat HeadlineTextField.


public function getTextStyle(styleName:String, ss:StyleSheet):TextFormat
{
var format:TextFormat = null;
var style:Object = ss.getStyle(styleName);
if (style != null)
{
var colorStr:String = style.color;
if (colorStr != null && colorStr.indexOf("#") == 0)
{
style.color = colorStr.substr(1);
}
format = new TextFormat(style.fontFamily,
style.fontSize,
style.color,
(style.fontWeight == "bold"),
(style.fontStyle == "italic"),
(style.textDecoration == "underline"),
style.url,
style.target,
style.textAlign,
style.marginLeft,
style.marginRight,
style.indent,
style.leading);
if (style.hasOwnProperty("letterSpacing"))
{
format.letterSpacing = style.letterSpacing;
}
}
return format;
}

CSS- TextFormat
. getTextStyle() CSS ,
TextFormat.


Flash Player 9 , Adobe AIR 1.0
StoryLayout ,
. displayText() .

23.11.2012.

420

ACTIONSCRIPT 3.0
TextField

public function displayText():void


{
headlineTxt = new HeadlineTextField(h1Format);
headlineTxt.wordWrap = true;
headlineTxt.x = this.paddingLeft;
headlineTxt.y = this.paddingTop;
headlineTxt.width = this.preferredWidth;
this.addChild(headlineTxt);
headlineTxt.fitText(this.headline, 1, true);
subtitleTxt = new HeadlineTextField(h2Format);
subtitleTxt.wordWrap = true;
subtitleTxt.x = this.paddingLeft;
subtitleTxt.y = headlineTxt.y + headlineTxt.height;
subtitleTxt.width = this.preferredWidth;
this.addChild(subtitleTxt);
subtitleTxt.fitText(this.subtitle, 2, false);
storyTxt = new MultiColumnText(this.numColumns, 20,
this.preferredWidth, 400, true, this.pFormat);
storyTxt.x = this.paddingLeft;
storyTxt.y = subtitleTxt.y + subtitleTxt.height + 10;
this.addChild(storyTxt);
storyTxt.text = this.content;
...

. y y
. ,
HeadlineTextField MultiColumnTextField .


Flash Player 9 , Adobe AIR 1.0
, HeadlineTextField
, . ,
, . ,
.
HeadlineTextField.fitText(), , .

23.11.2012.

421

ACTIONSCRIPT 3.0
TextField

public function fitText(msg:String, maxLines:uint = 1, toUpper:Boolean = false,


targetWidth:Number = -1):uint
{
this.text = toUpper ? msg.toUpperCase() : msg;
if (targetWidth == -1)
{
targetWidth = this.width;
}
var pixelsPerChar:Number = targetWidth / msg.length;
var pointSize:Number = Math.min(MAX_POINT_SIZE, Math.round(pixelsPerChar * 1.8 * maxLines));
if (pointSize < 6)
{
// the point size is too small
return pointSize;
}
this.changeSize(pointSize);
if (this.numLines > maxLines)
{
return shrinkText(--pointSize, maxLines);
}
else
{
return growText(pointSize, maxLines);
}
}
public function growText(pointSize:Number, maxLines:uint = 1):Number
{
if (pointSize >= MAX_POINT_SIZE)
{
return pointSize;
}
this.changeSize(pointSize + 1);
if (this.numLines > maxLines)
{
// set it back to the last size
this.changeSize(pointSize);
return pointSize;
}
else
{
return growText(pointSize + 1, maxLines);
}

23.11.2012.

422

ACTIONSCRIPT 3.0
TextField

}
public function shrinkText(pointSize:Number, maxLines:uint=1):Number
{
if (pointSize <= MIN_POINT_SIZE)
{
return pointSize;
}
this.changeSize(pointSize);
if (this.numLines > maxLines)
{
return shrinkText(pointSize - 1, maxLines);
}
else
{
return pointSize;
}
}

HeadlineTextField.fitText()
. ,
. ,
. , shrinkText(),
. , growText(),
. ,
.


Flash Player 9 , Adobe AIR 1.0
MultiColumnTextField TextField,
.
MultiColumnTextField() TextField,
, .
for (var i:int = 0; i < cols; i++)
{
var field:TextField = new TextField();
field.multiline = true;
field.autoSize = TextFieldAutoSize.NONE;
field.wordWrap = true;
field.width = this.colWidth;
field.setTextFormat(this.format);
this.fieldArray.push(field);
this.addChild(field);
}

TextField ,
addChild().

23.11.2012.

423

ACTIONSCRIPT 3.0
TextField

, text styleSheet StoryLayout,


layoutColumns() . layoutColumns()
getOptimalHeight() ,
.
public function getOptimalHeight(str:String):int
{
if (field.text == "" || field.text == null)
{
return this.preferredHeight;
}
else
{
this.linesPerCol = Math.ceil(field.numLines / this.numColumns);
var metrics:TextLineMetrics = field.getLineMetrics(0);
this.lineHeight = metrics.height;
var prefHeight:int = linesPerCol * this.lineHeight;
return prefHeight + 4;
}
}

getOptimalHeight() .
htmlText TextField . getOptimalHeight()
TextField ,
.
TextField.getLineMetrics() TextLineMetrics,
. TextLineMetrics.height
, .
, MultiColumnTextField ,
, 4 TextField,
.
layoutColumns().
public function layoutColumns():void
{
if (this._text == "" || this._text == null)
{
return;
}
var field:TextField = fieldArray[0] as TextField;
field.text = this._text;
field.setTextFormat(this.format);
this.preferredHeight = this.getOptimalHeight(field);
var remainder:String = this._text;
var fieldText:String = "";
var lastLineEndedPara:Boolean = true;
var indent:Number = this.format.indent as Number;
for (var i:int = 0; i < fieldArray.length; i++)

23.11.2012.

424

ACTIONSCRIPT 3.0
TextField

{
field = this.fieldArray[i] as TextField;
field.height = this.preferredHeight;
field.text = remainder;
field.setTextFormat(this.format);
var lineLen:int;
if (indent > 0 && !lastLineEndedPara && field.numLines > 0)
{
lineLen = field.getLineLength(0);
if (lineLen > 0)
{
field.setTextFormat(this.firstLineFormat, 0, lineLen);
}
}
field.x = i * (colWidth + gutter);
field.y = 0;
remainder = "";
fieldText = "";
var linesRemaining:int = field.numLines;
var linesVisible:int = Math.min(this.linesPerCol, linesRemaining);
for (var j:int = 0; j < linesRemaining; j++)
{
if (j < linesVisible)
{
fieldText += field.getLineText(j);
}
else
{
remainder +=field.getLineText(j);
}
}
field.text = fieldText;
field.setTextFormat(this.format);
if (indent > 0 && !lastLineEndedPara)
{
lineLen = field.getLineLength(0);
if (lineLen > 0)
{
field.setTextFormat(this.firstLineFormat, 0, lineLen);
}
}
var lastLine:String = field.getLineText(field.numLines - 1);
var lastCharCode:Number = lastLine.charCodeAt(lastLine.length - 1);

23.11.2012.

425

ACTIONSCRIPT 3.0
TextField

if (lastCharCode == 10 || lastCharCode == 13)


{
lastLineEndedPara = true;
}
else
{
lastLineEndedPara = false;
}
if ((this.format.align == TextFormatAlign.JUSTIFY) &&
(i < fieldArray.length - 1))
{
if (!lastLineEndedPara)
{
justifyLastLine(field, lastLine);
}
}
}
}

preferredHeight getOptimalHeight()
layoutColumns() TextField,
preferredHeight . layoutColumns()
, ,
, .
justify, justifyLastLine()
.
.

23.11.2012.

426

427

22. Flash Text


Engine
Flash Player 10 , Adobe AIR 1.5
Adobe Flash Text Engine (FTE), , Flash Player 10 Adobe
AIR1.5, ,
.
. FTE
, FTE
. Flash Text Engine
. .
TextField 402.
Text Layout Framework, FTE,
. Text Layout Framework
, ActionScript 3.0.
TLF, .
. Text Layout Framework 457.


flash.text.engine


Flash Player 10 , Adobe AIR 1.5
, Flash Text Engine, , .

Flash Text Engine:

TextElement/GraphicElement/GroupElement TextBlock
ElementFormat TextBlock;
TextBlock ;
TextLine , TextBlock.
, TextElement String
ElementFormat . TextElement
content TextBlock.
TextBlock.createTextLine(). createTextLine() TextLine,
, . ,
. textLineCreationResult
TextBlock TextLineCreationResult.COMPLETE. ,
( x y).

23.11.2012.

ACTIONSCRIPT 3.0
Flash Text Engine

, FTE Hello World! This is Flash


Text Engine! (, ! Flash Text Engine!)
. .
package
{
import flash.text.engine.*;
import flash.display.Sprite;
public class HelloWorldExample extends Sprite
{
public function HelloWorldExample()
{
var str = "Hello World! This is Flash Text Engine!";
var format:ElementFormat = new ElementFormat();
var textElement:TextElement = new TextElement(str, format);
var textBlock:TextBlock = new TextBlock();
textBlock.content = textElement;
var textLine1:TextLine = textBlock.createTextLine(null, 300);
addChild(textLine1);
textLine1.x = 30;
textLine1.y = 30;
}
}
}

createTextLine() , ,
. , , ,
, null.

GraphicElement GroupElement
Flash Player 10 , Adobe AIR 1.5
TextBlock GraphicElement,
. GraphicElement, ,
TextBlock.content.
TextBlock.createTextline() . ,
GraphicElement, TextElement.

23.11.2012.

428

ACTIONSCRIPT 3.0
Flash Text Engine

package
{
import
import
import
import

flash.text.engine.*;
flash.display.Sprite;
flash.display.Shape;
flash.display.Graphics;

public class GraphicElementExample extends Sprite


{
public function GraphicElementExample()
{
var str:String = "Beware of Dog!";
var triangle:Shape = new Shape();
triangle.graphics.beginFill(0xFF0000, 1);
triangle.graphics.lineStyle(3);
triangle.graphics.moveTo(30, 0);
triangle.graphics.lineTo(60, 50);
triangle.graphics.lineTo(0, 50);
triangle.graphics.lineTo(30, 0);
triangle.graphics.endFill();
var format:ElementFormat = new ElementFormat();
format.fontSize = 20;
var graphicElement:GraphicElement = new GraphicElement(triangle, triangle.width,
triangle.height, format);
var textBlock:TextBlock = new TextBlock();
textBlock.content = graphicElement;
var textLine1:TextLine = textBlock.createTextLine(null, triangle.width);
textLine1.x = 50;
textLine1.y = 110;
addChild(textLine1);
var textElement:TextElement = new TextElement(str, format);
textBlock.content = textElement;
var textLine2 = textBlock.createTextLine(null, 300);
addChild(textLine2);
textLine2.x = textLine1.x - 30;
textLine2.y = textLine1.y + 15;
}
}
}

GroupElement TextElement, GraphicElement


GroupElement. GroupElement content TextBlock.
GroupElement() Vector, ,
, .
, .

23.11.2012.

429

ACTIONSCRIPT 3.0
Flash Text Engine

package
{
import
import
import
import

flash.text.engine.*;
flash.display.Sprite;
flash.display.Shape;
flash.display.Graphics;

public class GroupElementExample extends Sprite


{
public function GroupElementExample()
{
var str:String = "Beware of Alligators!";
var triangle1:Shape = new Shape();
triangle1.graphics.beginFill(0xFF0000, 1);
triangle1.graphics.lineStyle(3);
triangle1.graphics.moveTo(30, 0);
triangle1.graphics.lineTo(60, 50);
triangle1.graphics.lineTo(0, 50);
triangle1.graphics.lineTo(30, 0);
triangle1.graphics.endFill();
var triangle2:Shape = new Shape();
triangle2.graphics.beginFill(0xFF0000, 1);
triangle2.graphics.lineStyle(3);
triangle2.graphics.moveTo(30, 0);
triangle2.graphics.lineTo(60, 50);
triangle2.graphics.lineTo(0, 50);
triangle2.graphics.lineTo(30, 0);
triangle2.graphics.endFill();
var format:ElementFormat = new ElementFormat();
format.fontSize = 20;
var graphicElement1:GraphicElement = new GraphicElement(triangle1,
triangle1.width, triangle1.height, format);
var textElement:TextElement = new TextElement(str, format);
var graphicElement2:GraphicElement = new GraphicElement(triangle2,
triangle2.width, triangle2.height, format);
var groupVector:Vector.<ContentElement> = new Vector.<ContentElement>();
groupVector.push(graphicElement1, textElement, graphicElement2);
var groupElement = new GroupElement(groupVector);
var textBlock:TextBlock = new TextBlock();
textBlock.content = groupElement;
var textLine:TextLine = textBlock.createTextLine(null, 800);
addChild(textLine);
textLine.x = 100;
textLine.y = 200;
}
}
}

23.11.2012.

430

ACTIONSCRIPT 3.0
Flash Text Engine


Flash Player 10 , Adobe AIR 1.5
TextBlock, TextElement.replaceText(),
TextElement, TextBlock.content.
repaceText(), ,
, , .
package
{
import flash.text.engine.*;
import flash.display.Sprite;
public class ReplaceTextExample extends Sprite
{
public function ReplaceTextExample()
{
var str:String = "Lorem ipsum dolor sit amet";
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;
createLine(textBlock, 10);
textElement.replaceText(0, 0, "A text fragment: ");
createLine(textBlock, 30);
textElement.replaceText(43, 43, "...");
createLine(textBlock, 50);
textElement.replaceText(23, 28, "(ipsum)");
createLine(textBlock, 70);
}
function createLine(textBlock:TextBlock, y:Number):void {
var textLine:TextLine = textBlock.createTextLine(null, 300);
textLine.x = 10;
textLine.y = y;
addChild(textLine);
}
}
}

replaceText() , beginIndex endIndex, ,


newText. beginIndex endIndex ,
replaceText() .
beginIndex endIndex .

23.11.2012.

431

ACTIONSCRIPT 3.0
Flash Text Engine

FTE
Flash Player 10 , Adobe AIR 1.5
TextLine ,
. , ,
. .
, .
package
{
import
import
import
import
import

flash.text.engine.*;
flash.ui.Mouse;
flash.display.Sprite
flash.events.MouseEvent;
flash.events.EventDispatcher;

public class EventHandlerExample extends Sprite


{
var textBlock:TextBlock = new TextBlock();
public function EventHandlerExample():void
{
var str:String = "I'll change color if you click me.";
var fontDescription:FontDescription = new FontDescription("Arial");
var format:ElementFormat = new ElementFormat(fontDescription, 18);
var textElement = new TextElement(str, format);
textBlock.content = textElement;
createLine(textBlock);
}
private function createLine(textBlock:TextBlock):void
{
var textLine:TextLine = textBlock.createTextLine(null, 500);
textLine.x = 30;
textLine.y = 30;
addChild(textLine);
textLine.addEventListener("mouseOut", mouseOutHandler);
textLine.addEventListener("mouseOver", mouseOverHandler);
textLine.addEventListener("click", clickHandler);
}
private function mouseOverHandler(event:MouseEvent):void
{
Mouse.cursor = "button";
}
private function mouseOutHandler(event:MouseEvent):void
{
Mouse.cursor = "arrow";
}
function clickHandler(event:MouseEvent):void {
if(textBlock.firstLine)
removeChild(textBlock.firstLine);

23.11.2012.

432

ACTIONSCRIPT 3.0
Flash Text Engine

var newFormat:ElementFormat = textBlock.content.elementFormat.clone();


switch(newFormat.color)
{
case 0x000000:
newFormat.color = 0xFF0000;
break;
case 0xFF0000:
newFormat.color = 0x00FF00;
break;
case 0x00FF00:
newFormat.color = 0x0000FF;
break;
case 0x0000FF:
newFormat.color = 0x000000;
break;
}
textBlock.content.elementFormat = newFormat;
createLine(textBlock);
}
}
}


Flash Player 10 , Adobe AIR 1.5
.
EventDispatcher eventMirror TextElement.
,
. ,
TextElement, eventMirror.
: Click (), here () to see me in italic
( ). , here,
, clickHandler(). clickHandler()
. , Click here to see me in
normal font! ( , !).

23.11.2012.

433

ACTIONSCRIPT 3.0
Flash Text Engine

package
{
import
import
import
import
import

flash.text.engine.*;
flash.ui.Mouse;
flash.display.Sprite;
flash.events.MouseEvent;
flash.events.EventDispatcher;

public class EventMirrorExample extends Sprite


{
var fontDescription:FontDescription = new FontDescription("Helvetica", "bold");
var format:ElementFormat = new ElementFormat(fontDescription, 18);
var textElement1 = new TextElement("Click ", format);
var textElement2 = new TextElement("here ", format);
var textElement3 = new TextElement("to see me in italic! ", format);
var textBlock:TextBlock = new TextBlock();
public function EventMirrorExample()
{
var myEvent:EventDispatcher = new EventDispatcher();
myEvent.addEventListener("click", clickHandler);
myEvent.addEventListener("mouseOut", mouseOutHandler);
myEvent.addEventListener("mouseOver", mouseOverHandler);
textElement2.eventMirror=myEvent;
var groupVector:Vector.<ContentElement> = new Vector.<ContentElement>;
groupVector.push(textElement1, textElement2, textElement3);
var groupElement:GroupElement = new GroupElement(groupVector);
textBlock.content = groupElement;
createLines(textBlock);
}
private function clickHandler(event:MouseEvent):void
{
var newFont:FontDescription = new FontDescription();
newFont.fontWeight = "bold";
var newFormat:ElementFormat = new ElementFormat();
newFormat.fontSize = 18;
if(textElement3.text == "to see me in italic! ") {
newFont.fontPosture = FontPosture.ITALIC;
textElement3.replaceText(0,21, "to see me in normal font! ");
}
else {
newFont.fontPosture = FontPosture.NORMAL;
textElement3.replaceText(0, 26, "to see me in italic! ");
}
newFormat.fontDescription = newFont;
textElement1.elementFormat = newFormat;
textElement2.elementFormat = newFormat;
textElement3.elementFormat = newFormat;
createLines(textBlock);
}

23.11.2012.

434

ACTIONSCRIPT 3.0
Flash Text Engine

private function mouseOverHandler(event:MouseEvent):void


{
Mouse.cursor = "button";
}
private function mouseOutHandler(event:MouseEvent):void
{
Mouse.cursor = "arrow";
}
private function createLines(textBlock:TextBlock):void
{
if(textBlock.firstLine)
removeChild (textBlock.firstLine);
var textLine:TextLine = textBlock.createTextLine (null, 300);
textLine.x = 15;
textLine.y = 20;
addChild (textLine);
}
}
}

mouseOverHandler() mouseOutHandler() ,
here , .


Flash Player 10 , Adobe AIR 1.5
TextBlock . TextBlock
TextElement. ElementFormat .
ElementFormat , , , ,
, , . FontDescription,
440.

ElementFormat
Flash Player 10 , Adobe AIR 1.5
ElementFormat ,
FontDescription. .

.

23.11.2012.

435

ACTIONSCRIPT 3.0
Flash Text Engine

package
{
import flash.display.Sprite;
import flash.text.*;
public class ElementFormatExample extends Sprite
{
private var tb:TextBlock = new TextBlock();
private var te:TextElement;
private var ef:ElementFormat;
private var fd:FontDescription = new FontDescription();
private var str:String;
private var tl:TextLine;
public function ElementFormatExample()
{
fd.fontName = "Garamond";
ef = new ElementFormat(fd);
ef.fontSize = 30;
ef.color = 0xFF0000;
str = "This is flash text";
te = new TextElement(str, ef);
tb.content = te;
tl = tb.createTextLine(null,600);
addChild(tl);
}
}
}

()
Flash Player 10 , Adobe AIR 1.5
color ElementFormat . ,
RGB- ; , 0xFF0000 , 0x00FF00 .
(0x000000).
alpha - ( TextElement,
GraphicElement). : 0 ( ) 1 (

, ). , alpha 0,
, . -,
.
var ef:ElementFormat = new ElementFormat();
ef.alpha = 0.8;
ef.color = 0x999999;

23.11.2012.

436

ACTIONSCRIPT 3.0
Flash Text Engine


Flash Player 10 , Adobe AIR 1.5
.
, TextBlock.baselineFontDescription
TextBlock.baselineFontSize.
.
, .
A

A. . . .

ElementFormat .
alignmentBaseline TextElement GraphicElement.
, .
.
dominantBaseline ,
.
TextBaseline.ROMAN,
IDEOGRAPHIC_TOP IDEOGRAPHIC_BOTTOM.
baselineShift Y.
( ) , .


Flash Player 10 , Adobe AIR 1.5
TypographicCase ElementFormat , ,
.
var ef_Upper:ElementFormat = new ElementFormat();
ef_Upper.typographicCase = TypographicCase.UPPERCASE;
var ef_SmallCaps:ElementFormat = new ElementFormat();
ef_SmallCaps.typographicCase = TypographicCase.SMALL_CAPS;


Flash Player 10 , Adobe AIR 1.5
90. TextRotation
:

23.11.2012.

437

ACTIONSCRIPT 3.0
Flash Text Engine

AUTO

auto

90 .
.

ROTATE_0

rotate_0

ROTATE_180

rotate_180

180 .

ROTATE_270

rotate_270

270 .

ROTATE_90

rotate_90

90 .

TextBlock.lineRotation
TextBlock.createTextLine() .

ElementFormat.textRotation . ,

, , . ,
a i.
,
, .
. - 444.
.
.
package
{
import flash.display.Sprite;
import flash.text.*;
public class RotationExample extends Sprite
{
private var tb:TextBlock = new TextBlock();
private var te:TextElement;
private var ef:ElementFormat;
private var fd:FontDescription = new FontDescription();
private var str:String;
private var tl:TextLine;
public function RotationExample()
{
fd.fontName = "MS Mincho";
ef = new ElementFormat(fd);
ef.textRotation = TextRotation.AUTO;
str = "This is rotated Japanese text";
te = new TextElement(str, ef);
tb.lineRotation = TextRotation.ROTATE_90;
tb.content = te;
tl = tb.createTextLine(null,600);
addChild(tl);
}
}
}

23.11.2012.

438

ACTIONSCRIPT 3.0
Flash Text Engine

ElementFormat
Flash Player 10 , Adobe AIR 1.5
ElementFormat ContentElement locked
true. ElementFormat
IllegalOperationError. ,
TextElement.
ElementFormat,
locked. true, clone()
. ,
TextElement. , , .
, ,
.
package
{
import flash.display.Sprite;
import flash.text.*;
public class ElementFormatCloneExample extends Sprite
{
private var tb:TextBlock = new TextBlock();
private var te:TextElement;
private var ef1:ElementFormat;
private var ef2:ElementFormat;
private var fd:FontDescription = new FontDescription();
public function ElementFormatCloneExample()
{
fd.fontName = "Garamond";
ef1 = new ElementFormat(fd);
ef1.fontSize = 24;
var str:String = "This is flash text";
te = new TextElement(str, ef);
tb.content = te;
var tx1:TextLine = tb.createTextLine(null,600);
addChild(tx1);
ef2 = (ef1.locked) ? ef1.clone() : ef1;
ef2.fontSize = 32;
tb.content.elementFormat = ef2;
var tx2:TextLine = tb.createTextLine(null,600);
addChild(tx2);
}
}
}

23.11.2012.

439

ACTIONSCRIPT 3.0
Flash Text Engine


Flash Player 10 , Adobe AIR 1.5
FontDescription ElementFormat
. , , ,
( SWF-).
. FTE Type 1 , , Type 3, ATC, sfnt-wrapped
CID Naked CID.

( FontDescription)
Flash Player 10 , Adobe AIR 1.5
fontName FontDescription ,
. , Arial, Helvetica, _sans Arial,
Helvetica, _sans, .
: _sans, _serif _typewriter.
. ,
, , . fontName
, _serif.
fontPosture (FontPosture.NORMAL)
(FontPosture.ITALIC). fontWeight
(FontWeight.NORMAL) (FontWeight.BOLD).
var fd1:FontDescription = new FontDescription();
fd1.fontName = "Arial, Helvetica, _sans";
fd1.fontPosture = FontPosture.NORMAL;
fd1.fontWeight = FontWeight.BOLD;


Flash Player 10 , Adobe AIR 1.5
fontLookup FontDescription ,
: .
(FontLookup.DEVICE), .
(FontLookup.EMBEDDED_CFF), SWF. CFF (Compact Font Format).
, .
SWF-.
.
var fd1:FontDescription = new FontDescription();
fd1.fontLookup = FontLookup.EMBEDDED_CFF;
fd1.fontName = "Garamond, _serif";

23.11.2012.

440

ACTIONSCRIPT 3.0
Flash Text Engine


Flash Player 10 , Adobe AIR 1.5
Flash Player 10 Adobe AIR 1.5 CFF ( ).
,
, , .
. FontDescription (RenderingMode.CFF)
renderingMode.
RenderingMode.NORMAL , Flash Player 7
.
CFF-, , cffHinting,
. CFFHinting.HORIZONTAL_STEM,
. CFFHinting.NONE, .
.
var fd1:FontDescription = new FontDescription();
fd1.renderingMode = RenderingMode.CFF;
fd1.cffHinting = CFFHinting.HORIZONTAL_STEM;

FontDescription
Flash Player 10 , Adobe AIR 1.5
FontDescription ElementFormat, locked
true. FontDescription
IllegalOperationError. ,
ElementFormat.
FontDescription,
locked. true, clone()
. , ElementFormat.
, TextElement, .
, , .

23.11.2012.

441

ACTIONSCRIPT 3.0
Flash Text Engine

package
{
import flash.display.Sprite;
import flash.text.*;
public class FontDescriptionCloneExample extends Sprite
{
private var tb:TextBlock = new TextBlock();
private var te:TextElement;
private var ef1:ElementFormat;
private var ef2:ElementFormat;
private var fd1:FontDescription = new FontDescription();
private var fd2:FontDescription;
public function FontDescriptionCloneExample()
{
fd1.fontName = "Garamond";
ef1 = new ElementFormat(fd);
var str:String = "This is flash text";
te = new TextElement(str, ef);
tb.content = te;
var tx1:TextLine = tb.createTextLine(null,600);
addChild(tx1);
fd2 = (fd1.locked) ? fd1.clone() : fd1;
fd2.fontName = "Arial";
ef2 = (ef1.locked) ? ef1.clone() : ef1;
ef2.fontDescription = fd2;
tb.content.elementFormat = ef2;
var tx2:TextLine = tb.createTextLine(null,600);
addChild(tx2);
}
}
}


Flash Player 10 , Adobe AIR 1.5
FTE
( ). ,
.


Flash Player 10 , Adobe AIR 1.5

. , ,
. c
.

23.11.2012.

442

ACTIONSCRIPT 3.0
Flash Text Engine

lineJustfication SpaceJustifier .
LineJustification , :
ALL_BUT_LAST , ; ALL_INCLUDING_LAST
, ; UNJUSTIFIED ( ) .
lineJustification SpaceJustifier
textJustifier TextBlock.
, .
package
{
import flash.text.engine.*;
import flash.display.Sprite;
public class JustifyExample extends Sprite
{
public function JustifyExample()
{
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.";
var format:ElementFormat = new ElementFormat();
var textElement:TextElement=new TextElement(str,format);
var spaceJustifier:SpaceJustifier=new
SpaceJustifier("en",LineJustification.ALL_BUT_LAST);
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);
}
}
}
}

, ,
SpaceJustifier.letterspacing true.
,
.

23.11.2012.

443

ACTIONSCRIPT 3.0
Flash Text Engine

-
Flash Player 10 , Adobe AIR 1.5
- .
, , ,
. JustificationStyle ,
. PRIORITIZE_LEAST_ADJUSTMENT
, .
PUSH_IN_KINSOKU
.
PUSH_OUT_ONLY .
- TextBlock.lineRotation
TextRotation.ROTATE_90, ElementFormat.textRotation
TextRotation.AUTO, . textRotation AUTO,
. AUTO 90
,
. ,
PUSH_IN_KINSOKU.
package
{
import
import
import
import

flash.text.engine.*;
flash.display.Stage;
flash.display.Sprite;
flash.system.Capabilities;

public class EastAsianJustifyExample extends Sprite


{
public function EastAsianJustifyExample()
{
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)
var textBlock:TextBlock = new TextBlock();
var font:FontDescription = new FontDescription();
var format:ElementFormat = new ElementFormat();
format.fontSize = 12;
format.color = 0xCC0000;
format.textRotation = TextRotation.AUTO;
textBlock.baselineZero = TextBaseline.IDEOGRAPHIC_CENTER;
var eastAsianJustifier:EastAsianJustifier = new EastAsianJustifier("ja",
LineJustification.ALL_BUT_LAST);
eastAsianJustifier.justificationStyle = JustificationStyle.PUSH_IN_KINSOKU;
textBlock.textJustifier = eastAsianJustifier;
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

23.11.2012.

444

ACTIONSCRIPT 3.0
Flash Text Engine

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, 200);
if (textLine == null)
break;
textLine.y = 20;
textLine.x = linePosition;
linePosition -= 25;
addChild(textLine);
previousLine = textLine;
}
}
}
}


Flash Player 10 , Adobe AIR 1.5
.
, WA Va.
ElementFormat. (Kerning.ON); OFF
AUTO. , ,
.
.
ElementFormat. ,
. FTE : trackingLeft,
, trackingRight,
. ,
.
A

VAY
VAY
VAY

VAY
VAY
VAY

A. Kerning.OFF . TrackingRight=5, Kerning.OFF . TrackingRight=-5, Kerning.OFF . Kerning.ON . TrackingRight=-5, Kerning.ON


. TrackingRight=-5, Kerning.ON

23.11.2012.

445

ACTIONSCRIPT 3.0
Flash Text Engine

var ef1:ElementFormat = new ElementFormat();


ef1.kerning = Kerning.OFF;
var ef2:ElementFormat = new ElementFormat();
ef2.kerning = Kerning.ON;
ef2.trackingLeft = 0.8;
ef2.trackingRight = 0.8;
var ef3:ElementFormat = new ElementFormat();
ef3.trackingRight = -0.2;


Flash Player 10 , Adobe AIR 1.5
breakOpportunity ElementFormat ,
, .
BreakOpportunity.AUTO, ,
. BreakOpportunity.ALL
. ,
.
var ef:ElementFormat = new ElementFormat();
ef.breakOpportunity = BreakOpportunity.ALL;


Flash Player 10 , Adobe AIR 1.5

TabStop. TabStop() ,
. ,
. ,
, , , .
tab1.
var tab1:TabStop = new TabStop(TabAlignment.DECIMAL, 50, ".");

, tabStops TextBlock.
tabStops Vector, Vector
. Vector .
Vector<TabStop>, TabStop.
tabStops TextBlock.
var tabStops:Vector.<TabStop> = new Vector.<TabStop>();
tabStops.push(tab1, tab2, tab3, tab4);
textBlock.tabStops = tabStops

Vector . 26.
TabStop.

23.11.2012.

446

ACTIONSCRIPT 3.0
Flash Text Engine

package {
import flash.text.engine.*;
import flash.display.Sprite;
public class TabStopExample extends Sprite
{
public function TabStopExample()
{
var format:ElementFormat = new ElementFormat();
format.fontDescription = new FontDescription("Arial");
format.fontSize = 16;
var tabStops:Vector.<TabStop> = new Vector.<TabStop>();
tabStops.push(
new TabStop(TabAlignment.START, 20),
new TabStop(TabAlignment.CENTER, 140),
new TabStop(TabAlignment.DECIMAL, 260, "."),
new TabStop(TabAlignment.END, 380));
var textBlock:TextBlock = new TextBlock();
textBlock.content = new TextElement(
"\tt1\tt2\tt3\tt4\n" +
"\tThis line aligns on 1st tab\n" +
"\t\t\t\tThis is the end\n" +
"\tThe following fragment centers on the 2nd tab:\t\t\n" +
"\t\tit's on me\t\t\n" +
"\tThe following amounts align on the decimal point:\n" +
"\t\t\t45.00\t\n" +
"\t\t\t75,320.00\t\n" +
"\t\t\t6,950.00\t\n" +
"\t\t\t7.01\t\n", format);
textBlock.tabStops = tabStops;
var yPosition:Number = 60;
var previousTextLine:TextLine = null;
var textLine:TextLine;
var i:int;
for (i = 0; i < 10; i++) {
textLine = textBlock.createTextLine(previousTextLine, 1000, 0);
textLine.x = 20;
textLine.y = yPosition;
addChild(textLine);
yPosition += 25;
previousTextLine = textLine;
}
}
}
}

23.11.2012.

447

ACTIONSCRIPT 3.0
Flash Text Engine

Flash Text Engine:


Flash Player 10 , Adobe AIR 1.5
Flash Text Engine
. , .
-, FLA- 2 :
import com.example.programmingas3.newslayout.StoryLayout ;
// frame sc ript - create a 3-columned arti cle layout
var story:StoryLayout = new StoryLayout(720, 500, 3, 10);
story.x = 20;
story.y = 80;
addChild(story);
stop();

StoryLayout.as . ,
ElementFormat.
, , .
package com.example.programmingas3.newslayout
{
import flash.display.Sprite;
import flash.text.StyleSheet;
import flash.text.engine.*;
import
import
import
import
import

flash.events.Event;
flash.net.URLRequest;
flash.net.URLLoader;
flash.display.Sprite;
flash.display.Graphics;

public class StoryLayout extends Sprite


{
public var headlineTxt:HeadlineTextField;
public var subtitleTxt:HeadlineTextField;
public var storyTxt:MultiColumnText;
public var sheet:StyleSheet;
public var h1_ElFormat:ElementFormat;
public var h2_ElFormat:ElementFormat;
public var p_ElFormat:ElementFormat;
private var loader:URLLoader;
public
public
public
public

var
var
var
var

paddingLeft:Number;
paddingRight:Number;
paddingTop:Number;
paddingBottom:Number;

public var preferredWidth:Number;


public var preferredHeight:Number;
public var numColumns:int;
public var bgColor:Number = 0xFFFFFF;

23.11.2012.

448

ACTIONSCRIPT 3.0
Flash Text Engine

public var headline:String = "News Layout Example";


public var subtitle:String = "This example formats text like a newspaper page using the
Flash Text Engine API. ";
public var rawTestData:String =
"From the part Mr. Burke took in the American Revolution, it was natural that I should
consider him a friend to mankind; and as our acquaintance commenced on that ground, it would
have been more agreeable to me to have had cause to continue in that opinion than to change it. " +
"At the time Mr. Burke made his violent speech last winter in the English Parliament
against the French Revolution and the National Assembly, I was in Paris, and had written to him
but a short time before to inform him how prosperously matters were going on. Soon after this I
saw his advertisement of the Pamphlet he intended to publish: As the attack was to be made in a
language but little studied, and less understood in France, and as everything suffers by
translation, I promised some of the friends of the Revolution in that country that whenever Mr.
Burke's Pamphlet came forth, I would answer it. This appeared to me the more necessary to be
done, when I saw the flagrant misrepresentations which Mr. Burke's Pamphlet contains; and that
while it is an outrageous abuse on the French Revolution, and the principles of Liberty, it is
an imposition on the rest of the world. " +
"I am the more astonished and disappointed at this conduct in Mr. Burke, as (from the
circumstances I am going to mention) I had formed other expectations. " +
"I had seen enough of the miseries of war, to wish it might never more have existence
in the world, and that some other mode might be found out to settle the differences that should
occasionally arise in the neighbourhood of nations. This certainly might be done if Courts were
disposed to set honesty about it, or if countries were enlightened enough not to be made the
dupes of Courts. The people of America had been bred up in the same prejudices against France,
which at that time characterised the people of England; but experience and an acquaintance with
the French Nation have most effectually shown to the Americans the falsehood of those prejudices;
and I do not believe that a more cordial and confidential intercourse exists between any two
countries than between America and France. ";
public function StoryLayout(w:int = 400, h:int = 200, cols:int = 3, padding:int =
10):void
{
this.preferredWidth = w;
this.preferredHeight = h;
this.numColumns = cols;
this.paddingLeft = padding;
this.paddingRight = padding;
this.paddingTop = padding;
this.paddingBottom = padding;
var req:URLRequest = new URLRequest("story.css");
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);
loader.load(req);
}
public function onCSSFileLoaded(event:Event):void
{
this.sheet = new StyleSheet();
this.sheet.parseCSS(loader.data);
// convert headline styles to ElementFormat objects
h1_ElFormat = getElFormat("h1", this.sheet);

23.11.2012.

449

ACTIONSCRIPT 3.0
Flash Text Engine

h1_ElFormat.typographicCase = TypographicCase.UPPERCASE;
h2_ElFormat = getElFormat("h2", this.sheet);
p_ElFormat = getElFormat("p", this.sheet);
displayText();
}
public function drawBackground():void
{
var h:Number = this.storyTxt.y + this.storyTxt.height +
this.paddingTop + this.paddingBottom;
var g:Graphics = this.graphics;
g.beginFill(this.bgColor);
g.drawRect(0, 0, this.width + this.paddingRight + this.paddingLeft, h);
g.endFill();
}
/**
* Reads a set of style properties for a named style and then creates
* a TextFormat object that uses the same properties.
*/
public function getElFormat(styleName:String, ss:StyleSheet):ElementFormat
{
var style:Object = ss.getStyle(styleName);
if (style != null)
{
var colorStr:String = style.color;
if (colorStr != null && colorStr.indexOf("#") == 0)
{
style.color = colorStr.substr(1);
}
var fd:FontDescription = new FontDescription(
style.fontFamily,
style.fontWeight,
FontPosture.NORMAL,
FontLookup.DEVICE,
RenderingMode.NORMAL,
CFFHinting.NONE);
var format:ElementFormat = new ElementFormat(fd,
style.fontSize,
style.color,
1,
TextRotation.AUTO,
TextBaseline.ROMAN,
TextBaseline.USE_DOMINANT_BASELINE,
0.0,
Kerning.ON,
0.0,
0.0,
"en",
BreakOpportunity.AUTO,
DigitCase.DEFAULT,
DigitWidth.DEFAULT,
LigatureLevel.NONE,
TypographicCase.DEFAULT);
if (style.hasOwnProperty("letterSpacing"))
{

23.11.2012.

450

ACTIONSCRIPT 3.0
Flash Text Engine

format.trackingRight = style.letterSpacing;
}
}
return format;
}
public function displayText():void
{
headlineTxt = new HeadlineTextField(h1_ElFormat,headline,this.preferredWidth);
headlineTxt.x = this.paddingLeft;
headlineTxt.y = 40 + this.paddingTop;
headlineTxt.fitText(1);
this.addChild(headlineTxt);
subtitleTxt = new HeadlineTextField(h2_ElFormat,subtitle,this.preferredWidth);
subtitleTxt.x = this.paddingLeft;
subtitleTxt.y = headlineTxt.y + headlineTxt.height;
subtitleTxt.fitText(2);
this.addChild(subtitleTxt);
storyTxt = new MultiColumnText(rawTestData, this.numColumns,
20, this.preferredWidth, this.preferredHeight, p_ElFormat);
storyTxt.x = this.paddingLeft;
storyTxt.y = subtitleTxt.y + subtitleTxt.height + 10;
this.addChild(storyTxt);
drawBackground();
}
}
}

FormattedTextBlock.as .
.
package com.example.programmingas3.newslayout
{
import flash.text.engine.*;
import flash.display.Sprite;
public class FormattedTextBlock extends Sprite
{
public var tb:TextBlock;
private var te:TextElement;
private var ef1:ElementFormat;
private var textWidth:int;
public var totalTextLines:int;
public var blockText:String;
public var leading:Number = 1.25;
public var preferredWidth:Number = 720;
public var preferredHeight:Number = 100;
public function FormattedTextBlock(ef:ElementFormat,txt:String, colW:int = 0)
{
this.textWidth = (colW==0) ? preferredWidth : colW;
blockText = txt;
ef1 = ef;
tb = new TextBlock();

23.11.2012.

451

ACTIONSCRIPT 3.0
Flash Text Engine

tb.textJustifier = new SpaceJustifier("en",LineJustification.UNJUSTIFIED,false);


te = new TextElement(blockText,this.ef1);
tb.content = te;
this.breakLines();
}
private function breakLines()
{
var textLine:TextLine = null;
var y:Number = 0;
var lineNum:int = 0;
while (textLine = tb.createTextLine(textLine,this.textWidth,0,true))
{
textLine.x = 0;
textLine.y = y;
y += this.leading*textLine.height;
this.addChild(textLine);
}
for (var i:int = 0; i < this.numChildren; i++)
{
TextLine(this.getChildAt(i)).validity = TextLineValidity.STATIC;
}
this.totalTextLines = this.numChildren;
}
private function rebreakLines()
{
this.clearLines();
this.breakLines();
}
private function clearLines()
{
while(this.numChildren)
{
this.removeChildAt(0);
}
}

23.11.2012.

452

ACTIONSCRIPT 3.0
Flash Text Engine

public function changeSize(size:uint=12):void


{
if (size > 5)
{
var ef2:ElementFormat = ef1.clone();
ef2.fontSize = size;
te.elementFormat = ef2;
this.rebreakLines();
}
}
public function changeCase(newCase:String = "default"):void
{
var ef2:ElementFormat = ef1.clone();
ef2.typographicCase = newCase;
te.elementFormat = ef2;
}
}
}

HeadlineTextBlock.as FormattedTextBlock .
.
package com.example.programmingas3.newslayout
{
import flash.text.engine.*;
public class HeadlineTextField extends FormattedTextBlock
{
public static var MIN_POINT_SIZE:uint = 6;
public static var MAX_POINT_SIZE:uint = 128;
public function HeadlineTextField(te:ElementFormat,txt:String,colW:int = 0)
{
super(te,txt);
}
public function fitText(maxLines:uint = 1, targetWidth:Number = -1):uint
{
if (targetWidth == -1)
{
targetWidth = this.width;
}
var pixelsPerChar:Number = targetWidth / this.blockText.length;
var pointSize:Number = Math.min(MAX_POINT_SIZE,
Math.round(pixelsPerChar * 1.8 * maxLines));
if (pointSize < 6)
{
// the point size is too small
return pointSize;
}
this.changeSize(pointSize);
if (this.totalTextLines > maxLines)

23.11.2012.

453

ACTIONSCRIPT 3.0
Flash Text Engine

{
return shrinkText(--pointSize, maxLines);
}
else
{
return growText(pointSize, maxLines);
}
}
public function growText(pointSize:Number, maxLines:uint = 1):Number
{
if (pointSize >= MAX_POINT_SIZE)
{
return pointSize;
}
this.changeSize(pointSize + 1);
if (this.totalTextLines > maxLines)
{
// set it back to the last size
this.changeSize(pointSize);
return pointSize;
}
else
{
return growText(pointSize + 1, maxLines);
}
}
public function shrinkText(pointSize:Number, maxLines:uint=1):Number
{
if (pointSize <= MIN_POINT_SIZE)
{
return pointSize;
}
this.changeSize(pointSize);
if (this.totalTextLines > maxLines)
{
return shrinkText(pointSize - 1, maxLines);
}
else
{
return pointSize;
}
}
}
}

MultiColumnText.as ,
. TextBlock ,
.

23.11.2012.

454

ACTIONSCRIPT 3.0
Flash Text Engine

package com.example.programmingas3.newslayout
{
import flash.display.Sprite;
import flash.text.engine.*;
public class MultiColumnText extends Sprite
{
private var tb:TextBlock;
private var te:TextElement;
private var numColumns:uint = 2;
private var gutter:uint = 10;
private var leading:Number = 1.25;
private var preferredWidth:Number = 400;
private var preferredHeight:Number = 100;
private var colWidth:int = 200;
public function MultiColumnText(txt:String = "",cols:uint = 2,
gutter:uint = 10, w:Number = 400, h:Number = 100,
ef:ElementFormat = null):void
{
this.numColumns = Math.max(1, cols);
this.gutter = Math.max(1, gutter);
this.preferredWidth = w;
this.preferredHeight = h;
this.setColumnWidth();
var field:FormattedTextBlock = new FormattedTextBlock(ef,txt,this.colWidth);
var totLines:int = field.totalTextLines;
field = null;
var linesPerCol:int = Math.ceil(totLines/cols);
tb = new TextBlock();
te = new TextElement(txt,ef);
tb.content = te;
var textLine:TextLine = null;
var x:Number = 0;
var y:Number = 0;
var i:int = 0;
var j:int = 0;
while (textLine = tb.createTextLine(textLine,this.colWidth,0,true))
{
textLine.x = Math.floor(i/(linesPerCol+1))*(this.colWidth+this.gutter);
textLine.y = y;
y += this.leading*textLine.height;

23.11.2012.

455

ACTIONSCRIPT 3.0
Flash Text Engine

j++;
if(j>linesPerCol)
{
y = 0;
j = 0;
}
i++;
this.addChild(textLine);
}
}
private function setColumnWidth():void
{
this.colWidth = Math.floor( (this.preferredWidth ((this.numColumns - 1) * this.gutter)) / this.numColumns);
}
}
}

23.11.2012.

456

457

23. Text Layout


Framework
Flash Player 10 , Adobe AIR 1.5

Text Layout Framework


Flash Player 10 , Adobe AIR 1.5
Text Layout Framework (TLF) ActionScript. TLF
, Adobe Flash Player 10 Adobe AIR 1.5. TLF
-.
Adobe Flex Adobe Flash Professional.
,
.
TLF :

, 30 , , ,
, , , , , .

, .
, Tate-Chu-Yoko ( )
.

, , , ,
, .

, , ,
.

API- ,
, .

,

TLF ActionScript 3.0, Flash Text Engine
(FTE), Flash Player 10. FTE
flash.text.engine, (Application
Programming Interface, API) Flash Player 10.
, API- Flash Player,
. ,
. TLF API-. TLF
, ,
FTE, .

23.11.2012.

ACTIONSCRIPT 3.0
Text Layout Framework

FTE, TLF Flash Player.


, ActionScript 3.0.
, . Flash Professional Flex SDK
, TLF.


TLF


Flash Player 10 , Adobe AIR 1.5
TLF .
. TLF
,
. ,
, tate-chu-yoko (TCY). TCY
, .
:

(, , , );
, , , ;
;
(, ), , ( );
, ;
, , , , , , , , ;
, , , , , , , , ,
.

Text Layout Framework Flash Professional Flex


TLF Flash.
, Flash Professional CS5 fl.text.TLFTextField,
TLF. TLFTextField ActionScript,
TLF. TLFTextField ,
TextField. textFlow
TLF.
Flash Professional, the TLFTextField
. ActionScript
TLF. .
TLFTextField ActionScript 3.0 Adobe Flash Platform.
Flex, TLF. .
Text Layout Framework 459.

23.11.2012.

458

ACTIONSCRIPT 3.0
Text Layout Framework

Text Layout Framework


Flash Player 10 , Adobe AIR 1.5
Flex ,
TLF. TLF ActionScript 3.0, textLayout.swc. TLF
100 ActionScript 3.0, .
flashx.textLayout.

Text Layout Framework


Flash Player 10 , Adobe AIR 1.5
TLF :


;
.


TLF :

flashx.textLayout.elements
flashx.textLayout.formats
flashx.textLayout.conversion
TLF , .

.
.


TLF :

flashx.textLayout.factory
flashx.textLayout.container
flashx.textLayout.compose
Flash Player.
.
, .
.


TLF :

flashx.textLayout.edit
flashx.textLayout.operations
flashx.textLayout.events
23.11.2012.

459

ACTIONSCRIPT 3.0
Text Layout Framework

, ,
, .
.

Text Layout Framework


Text Layout Format.
1 TLF. .

TLF 464
TLF 468.
2 .

. TLF 470.
3 .

. ,
TLF 471.
4 resize ( ).

. TLF 471.

Text Layout Framework:


Flash Player 10 , Adobe AIR 1.5
TLF .
, :
package
{
import
import
import
import
import
import
import
import
import
import
import

flash.display.Sprite;
flash.display.StageAlign;
flash.display.StageScaleMode;
flash.events.Event;
flash.geom.Rectangle;
flashx.textLayout.compose.StandardFlowComposer;
flashx.textLayout.container.ContainerController;
flashx.textLayout.container.ScrollPolicy;
flashx.textLayout.conversion.TextConverter;
flashx.textLayout.elements.TextFlow;
flashx.textLayout.formats.TextLayoutFormat;

public class TLFNewsLayout extends Sprite


{
private var hTextFlow:TextFlow;
private var headContainer:Sprite;
private var headlineController:ContainerController;
private var hContainerFormat:TextLayoutFormat;
private
private
private
private

var
var
var
var

bTextFlow:TextFlow;
bodyTextContainer:Sprite;
bodyController:ContainerController;
bodyTextContainerFormat:TextLayoutFormat;

23.11.2012.

460

ACTIONSCRIPT 3.0
Text Layout Framework

private const headlineMarkup:String = "<flow:TextFlow


xmlns:flow='http://ns.adobe.com/textLayout/2008'><flow:p textAlign='center'><flow:span
fontFamily='Helvetica' fontSize='18'>TLF News Layout Example</flow:span><flow:br/><flow:span
fontFamily='Helvetica' fontSize='14'>This example formats text like a newspaper page with a
headline, a subtitle, and multiple columns</flow:span></flow:p></flow:TextFlow>";
private const bodyMarkup:String = "<flow:TextFlow
xmlns:flow='http://ns.adobe.com/textLayout/2008' fontSize='12' textIndent='10' marginBottom='15'
paddingTop='4' paddingLeft='4'><flow:p marginBottom='inherit'><flow:span>There are many
</flow:span><flow:span fontStyle='italic'>such</flow:span><flow:span> lime-kilns in that tract
of country, for the purpose of burning the white marble which composes a large part of the
substance of the hills. Some of them, built years ago, and long deserted, with weeds growing in
the vacant round of the interior, which is open to the sky, and grass and wild-flowers rooting
themselves into the chinks of the stones, look already like relics of antiquity, and may yet be
overspread with the lichens of centuries to come. Others, where the lime-burner still feeds his
daily and nightlong fire, afford points of interest to the wanderer among the hills, who seats
himself on a log of wood or a fragment of marble, to hold a chat with the solitary man. It is a
lonesome, and, when the character is inclined to thought, may be an intensely thoughtful
occupation; as it proved in the case of Ethan Brand, who had mused to such strange purpose, in
days gone by, while the fire in this very kiln was burning.</flow:span></flow:p><flow:p
marginBottom='inherit'><flow:span>The man who now watched the fire was of a different order, and
troubled himself with no thoughts save the very few that were requisite to his business. At
frequent intervals, he flung back the clashing weight of the iron door, and, turning his face
from the insufferable glare, thrust in huge logs of oak, or stirred the immense brands with a
long pole. Within the furnace were seen the curling and riotous flames, and the burning marble,
almost molten with the intensity of heat; while without, the reflection of the fire quivered on
the dark intricacy of the surrounding forest, and showed in the foreground a bright and ruddy
little picture of the hut, the spring beside its door, the athletic and coal-begrimed figure of
the lime-burner, and the half-frightened child, shrinking into the protection of his father's
shadow. And when again the iron door was closed, then reappeared the tender light of the halffull moon, which vainly strove to trace out the indistinct shapes of the neighboring mountains;
and, in the upper sky, there was a flitting congregation of clouds, still faintly tinged with the
rosy sunset, though thus far down into the valley the sunshine had vanished long and long
ago.</flow:span></flow:p></flow:TextFlow>";
public function TLFNewsLayout()
{
//wait for stage to exist
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(evtObj:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// Headline text flow and flow composer
hTextFlow = TextConverter.importToFlow(headlineMarkup,
TextConverter.TEXT_LAYOUT_FORMAT);
// initialize the headline container and controller objects
headContainer = new Sprite();
headlineController = new ContainerController(headContainer);
headlineController.verticalScrollPolicy = ScrollPolicy.OFF;
hContainerFormat = new TextLayoutFormat();
hContainerFormat.paddingTop = 4;

23.11.2012.

461

ACTIONSCRIPT 3.0
Text Layout Framework

hContainerFormat.paddingRight = 4;
hContainerFormat.paddingBottom = 4;
hContainerFormat.paddingLeft = 4;
headlineController.format = hContainerFormat;
hTextFlow.flowComposer.addController(headlineController);
addChild(headContainer);
stage.addEventListener(flash.events.Event.RESIZE, resizeHandler);
// Body text TextFlow and flow composer
bTextFlow = TextConverter.importToFlow(bodyMarkup,
TextConverter.TEXT_LAYOUT_FORMAT);
// The body text container is below, and has three columns
bodyTextContainer = new Sprite();
bodyController = new ContainerController(bodyTextContainer);
bodyTextContainerFormat = new TextLayoutFormat();
bodyTextContainerFormat.columnCount = 3;
bodyTextContainerFormat.columnGap = 30;
bodyController.format = bodyTextContainerFormat;
bTextFlow.flowComposer.addController(bodyController);
addChild(bodyTextContainer);
resizeHandler(null);
}
private function resizeHandler(event:Event):void
{
const verticalGap:Number = 25;
const stagePadding:Number = 16;
var stageWidth:Number = stage.stageWidth - stagePadding;
var stageHeight:Number = stage.stageHeight - stagePadding;
var headlineWidth:Number = stageWidth;
var headlineContainerHeight:Number = stageHeight;
// Initial compose to get height of headline after resize
headlineController.setCompositionSize(headlineWidth,
headlineContainerHeight);
hTextFlow.flowComposer.compose();
var rect:Rectangle = headlineController.getContentBounds();
headlineContainerHeight = rect.height;

23.11.2012.

462

ACTIONSCRIPT 3.0
Text Layout Framework

// Resize and place headline text container


// Call setCompositionSize() again with updated headline height
headlineController.setCompositionSize(headlineWidth, headlineContainerHeight );
headlineController.container.x = stagePadding / 2;
headlineController.container.y = stagePadding / 2;
hTextFlow.flowComposer.updateAllControllers();
// Resize and place body text container
var bodyContainerHeight:Number = (stageHeight - verticalGap headlineContainerHeight);
bodyController.format = bodyTextContainerFormat;
bodyController.setCompositionSize(stageWidth, bodyContainerHeight );
bodyController.container.x = (stagePadding/2);
bodyController.container.y = (stagePadding/2) + headlineContainerHeight +
verticalGap;
bTextFlow.flowComposer.updateAllControllers();
}
}
}

TLFNewsLayout .
, .
TLF. headlineMarkup
, , bodyMarkup .
TLF Markup . TLF
464.
onAddedToStage() TextFlow,
TLF:
hTextFlow = TextConverter.importToFlow(headlineMarkup, TextConverter.TEXT_LAYOUT_FORMAT);

Sprite , ,
:
headContainer = new Sprite();
headlineController = new ContainerController(headContainer);

, .
, , .
TextLayoutFormat :
hContainerFormat = new TextLayoutFormat();

, .
resizeHandler().
TextFlow .
resizeHandler() ,
. compose()
. resizeHandler()
updateAllControllers(). , resizeHandler()
.

23.11.2012.

463

464

ACTIONSCRIPT 3.0
Text Layout Framework

TLF
TLF .
, . ,
TextFlow. TextFlow .
, .
.

XHTML. :

TextFlow

Text Layout Framework Markup


TLF TLF Markup. TLF Markup
XML , TLF. ,
XML, TLF Markup ,
TextFlow. XML TextFlow
XML .
TLF Markup TextFlow.
TextFlow,
, TextLayoutFormat.
, TLF.

textflow

div, p

TextFlow

div

TextFlow.
.

div, list, p

DivElement

a, tcy, span, img, tab, br, ParagraphElement


g

tcy, span, img, tab, br, g

LinkElement

tcy


(
TextFlow).

a, span, img, tab, br, g

TCYElement

23.11.2012.

465

ACTIONSCRIPT 3.0
Text Layout Framework

span

SpanElement

img

InlineGraphicElement

tab

TabElement

br

.
; ,
,
.

BreakElement

linkNormalFormat

TextLayoutFormat

TextLayoutFormat

linkActiveFormat

,

,
.

TextLayoutFormat

TextLayoutFormat

linkHoverFormat

,

,
.

TextLayoutFormat

TextLayoutFormat

li

.
.

div, li, list, p

ListItemElement

list

.
div, li, list, p
.

.

.
.

.

ListElement

a, tcy, span, img, tab, br, SubParagraphGroupE


g
lement


TLF 2.0
SubParagraphGroupElements typeName TLF 2.0


ListElement ListItemElement
. ,
, .
<list>.
<list> <li>. ListMarkerFormat.
.
<flow:list paddingRight="24" paddingLeft="24">
<flow:li>Item 1</flow:li>
<flow:li>Item 2</flow:li>
<flow:li>Item 3</flow:li>
</flow:list>

, :

23.11.2012.

ACTIONSCRIPT 3.0
Text Layout Framework

<flow:list paddingRight="24" paddingLeft="24">


<flow:li>Item 1</flow:li>
<flow:list paddingRight="24" paddingLeft="24">
<flow:li>Item 1a</flow:li>
<flow:li>Item 1b</flow:li>
<flow:li>Item 1c</flow:li>
</flow:list>
<flow:li>Item 2</flow:li>
<flow:li>Item 3</flow:li>
</flow:list>

listStyleType ListElement.
, ListStyleType ( check, circle, decimal
box).
:
<flow:list paddingRight="24" paddingLeft="24" listStyleType="upperAlpha">
<flow:li>upperAlpha item</flow:li> <flow:li>another</flow:li> </flow:list> <flow:list
paddingRight="24" paddingLeft="24" listStyleType="lowerAlpha"> <flow:li>lowerAlpha
item</flow:li> <flow:li>another</flow:li> </flow:list> <flow:list paddingRight="24"
paddingLeft="24" listStyleType="upperRoman"> <flow:li>upperRoman item</flow:li>
<flow:li>another</flow:li> </flow:list> <flow:list paddingRight="24" paddingLeft="24"
listStyleType="lowerRoman"> <flow:listMarkerFormat> <!-- Increments the list by 2s rather than
1s. --> <flow:ListMarkerFormat counterIncrement="ordered 2"/> </flow:listMarkerFormat>
<flow:li>lowerRoman item</flow:li> <flow:li>another</flow:li> </flow:list>

ListMarkerFormat .
counterReset.
afterContent
beforeContent ListMarkerFormat. ,
.
XX, YY.
<flow:list listStyleType="upperRoman" paddingLeft="36" paddingRight="24">
<flow:listMarkerFormat>
<flow:ListMarkerFormat fontSize="16"
beforeContent="XX"
afterContent="YY"
counterIncrement="ordered -1"/>
</flow:listMarkerFormat>
<flow:li>Item 1</flow:li>
<flow:li>Item 2</flow:li>
<flow:li>Item 3</flow:li>
</flow:list>

content .
.

23.11.2012.

466

ACTIONSCRIPT 3.0
Text Layout Framework

<flow:list listStyleType="disc" paddingLeft="96" paddingRight="24">


<flow:listMarkerFormat>
<flow:ListMarkerFormat fontSize="16"
beforeContent="Section "
content="counters(ordered,&quot;*&quot;,upperRoman)"
afterContent=": "/>
</flow:listMarkerFormat>
<flow:li>Item 1</li>
<flow:li>Item 2</li>
<flow:li>Item 3</li>
</flow:list>

, content ,
, afterContent. XML>").
, HTML- &quote; ("<


TLF 2.0

TLF
FlowElement ,
.
paddingLeft
paddingRight. paddingTop
paddingBottom.
. : paddingBottom, paddingTop,
paddingLeft paddingRight. TextFlow,

div
img
li
list
p
span.
TextFlow.
<flow:TextFlow version="2.0.0" xmlns:flow="http://ns.adobe.com/textLayout/2008" fontSize="14"
textIndent="15" paddingTop="4" paddingLeft="4" fontFamily="Times New Roman">

: ( ), , auto inherit.
auto, ,
0 , ListElement. ListElements auto 0
, listAutoPadding. listAutoPadding
40, .
. auto inherit ,
FormatValue.
.

23.11.2012.

467

ACTIONSCRIPT 3.0
Text Layout Framework


TLF 2.0

TLF
Flash Player 10 , Adobe AIR 1.5
flashx.textLayout.formats ,
FlowElement .
.
.
ITextLayoutFormat , FlowElement.
,
. , ,
, , .

FlowElement
Flash Player 10 , Adobe AIR 1.5
FlowElement . FlowElement
ITextLayoutFormat, FlowElement
.
,
ParagraphElement:
var p:ParagraphElement = new ParagraphElement();
p.fontSize = 18;
p.fontFamily = "Arial";

FlowElement
TextLayoutFormat
Flash Player 10 , Adobe AIR 1.5
FlowElement TextLayoutFormat.
,
. format FlowElement.
TextLayoutFormat FlowElement ITextLayoutFormat.
, .
. TextLayoutFormat ActionScript 3.0
Adobe Flash Platform.

23.11.2012.

468

ACTIONSCRIPT 3.0
Text Layout Framework


Flash Player 10 , Adobe AIR 1.5
. TextLayoutFormat
FlowElement , .
,
FlowElement.
. :
1 (

).
2 , (. .

undefined).
3 undefined,

flashx.textLayout.formats.FormatValue.INHERIT.
, fontSize TextFlow
TextFlow. , .
.
: backgroundColor TextFlow,
TextFlow . backgroundColor ,
. ,
backgroundColor
flashx.textLayout.formats.FormatValue.INHERIT.
. TextLayoutFormat ActionScript 3.0
Adobe Flash Platform.

TLF
Flash Player 10 , Adobe AIR 1.5
TextConverter flashx.textLayout.conversion.*
TLF. , ,
SWF-. ,
TextFlow, String XML.
. export()
importToFlow(). TextConverter. .
, TextConverter,
TextConverter.
flashx.textLayout.conversion , .
,
. flashx.textLayout.edit
.
. flashx.textLayout.conversion ActionScript 3.0
Adobe Flash Platform.

23.11.2012.

469

470

ACTIONSCRIPT 3.0
Text Layout Framework


TLF
Flash Player 10 , Adobe AIR 1.5
TLF, Flash Player .
, , , Flash Player. TLF
.
. ,
.
TextLine, flash.text.engine.* Flash Player 10.


TextFlowTextLineFactory,
flashx.textLayout.factory. FlowComposer,
, .
, , .
. TextFlowTextLineFactory ActionScript 3.0
Adobe Flash Platform.


, ,
TextFlowTextLineFactory. ,
. . ,
TLF 471.
StandardFlowComposer flashx.textLayout.compose.
TextFlow TextLine,
TextLine .
TextFlow

Stage

IFlowComposer

Sprite

ContainerController

TextLine

TextLine

IFlowComposer ContainerControllers

TextFlow , IFlowComposer.
IFlowComposer TextFlow.flowComposer.
, IFlowComposer.

.

23.11.2012.

ACTIONSCRIPT 3.0
Text Layout Framework

Sprite,
DisplayObjectContainer. API Flash Player.
,
TextLineFactory. , ,
TextLine.
-. , , ,
.
-, ContainerController
flashx.textLayout.container.
, -
. .
, : .
TextLine ,
.
Flash Player.
. IFlowComposer, StandardFlowComposer
ContainerController ActionScript 3.0 Adobe Flash Platform.

,
TLF
Flash Player 9.0 , Adobe AIR 1.0
.
TextFlow .
TextFlow
TextFlow.interactionManager .
SelectionManager interactionManager. ,
EditManager SelectionManager.
UndoManager
EditManager. UndoManager
,
. .
. SelectionManager, EditManager UndoManager
ActionScript 3.0 Adobe Flash Platform.

TLF
Flash Player 10 , Adobe AIR 1.5
TextFlow , :

;
;

23.11.2012.

471

ACTIONSCRIPT 3.0
Text Layout Framework

FlowElement;
compose.
. flashx.textLayout.events ActionScript 3.0
Adobe Flash Platform.


FlowElement LinkElement EventMirrors TLF


InlineGraphicElement , :

float InlineGraphicElement
clearFloats FlowElement
float . clearFloats
float.
float.
,
.
<flow:p paragraphSpaceAfter="15" >Images in a flow are a good thing. For example, here is a
float. It should show on the left: <flow:img float="left" height="50" width="19"
source="../assets/bulldog.jpg"></flow:img> Don't you agree? Another sentence here. Another
sentence here. Another sentence here. Another sentence here. Another sentence here. Another
sentence here. Another sentence here. Another sentence here.</flow:p>

float: left, right, start, end none ( ).


Float. none.
clearFloats ,
, . , , ,
. ,
clearFloats.
, .
, clearFloats
end.
<flow:p paragraphSpaceAfter="15" >Here is another float, it should show up on the right:
<flow:img float="right" height="50" elementHeight="200" width="19"
source="../assets/bulldog.jpg"></flow:img>We'll add another paragraph that should clear past
it.</flow:p><flow:p clearFloats="end" >This should appear after the previous float on the
right.</flow:p>

clearFloats: left, right, end, start, none both.


ClearFloats. clearFloats inherit,
, FormatValue. none.


TLF

23.11.2012.

472

473

24.
Flash Player 9 , Adobe AIR 1.0
ActionScript .
, .
,
, , mp3-, ,
.
, SWF-.
,
.


flash.media
flash.events.SampleDataEvent


Flash Player 9 , Adobe AIR 1.0
(
), .
Adobe Flash Player Adobe AIR ActionScript.
, ,
, - . ActionScript
: , ,
.
ActionScript,
Flash Player AIR. Flash Player
AIR, , ActionScript.

SWF (, mp3).
SFW- .
, .
.
.
,
, .
, ActionScript 3.0, Flash Player
AIR , mp3.
, WAV AIFF.

23.11.2012.

ACTIONSCRIPT 3.0

ActionScript flash.media. Sound


:
, , .
Flash Player AIR
SoundChannel. ,
,
SoundChannel.
SoundChannel. SoundChannel
. , ,
SoundMixer.
ActionScript
. , , .
474.

, .
() .
, .
mp3- (/).
, .
.
mp3 MPEG-1 Audio Layer 3 mp3 .

.
.
,

. 44,1
44100 .
,

.
.
,


Flash Player 9 , Adobe AIR 1.0
, , :

, ;
, SWF- ;
, , ;
23.11.2012.

474

ACTIONSCRIPT 3.0

, ,
Flash Media Server;

, sampleData.
, ,
.
ActionScript 3.0 , mp3.
, WAV AIFF.
Flash Player 9.0.115.0 AAC
NetStream. .
. 507.
Adobe Flash Professional WAV- AIFF- , SWF mp3. Flash
, , .
. Flash.
ActionScript 3.0 flash.media.

flash.media.Sound

Sound ,
.

flash.media.SoundChannel

Sound,
SoundChannel. SoundChannel
.
SoundChannel.

flash.media.SoundLoaderContext

SoundLoaderContext ,
, Flash Player AIR ,
. SoundLoaderContext
Sound.load().

flash.media.SoundMixer

SoundMixer ,
. ,
SoundMixer, SoundMixer
SoundChannel, .

flash.media.SoundTransform

SoundTransform ,
. SoundTransform , ,
SoundChannel, SoundMixer Microphone.

flash.media.ID3Info

ID3Info , ID3,
mp3.

flash.media.Microphone

Microphone ,
.
. Microphone ,
- .

flash.media.AudioPlaybackMode

AudioPlaybackMode audioPlaybackMode
SoundMixer.

Sound
SoundChannel. SoundChannel
SoundMixer .
Sound, SoundChannel SoundMixer ,
, Flash Media Server.

23.11.2012.

475

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Sound
. Sound .
, Sound.
, ,
Sound, , .
var req:URLRequest = new URLRequest("click.mp3");
var s:Sound = new Sound(req);

Sound() URLRequest.
URLRequest, Sound
.
, ,
. , ,
, ,
. .
,
, .
Sound .
,
. , Sound.

open (Event.OPEN)

progress (ProgressEvent.PROGRESS)
.
id3 (Event.ID3)

, mp3 ID3.

complete (Event.COMPLETE)

ioError (IOErrorEvent.IO_ERROR)

,
.

23.11.2012.

476

ACTIONSCRIPT 3.0

import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
var s:Sound = new Sound();
s.addEventListener(Event.COMPLETE, onSoundLoaded);
var req:URLRequest = new URLRequest("bigSound.mp3");
s.load(req);
function onSoundLoaded(event:Event):void
{
var localSound:Sound = event.target as Sound;
localSound.play();
}

Sound, URLRequest.
Event.COMPLETE, Sound
onSoundLoaded() .
Sound.load() URLRequest .
onSoundLoaded() . target Event
Sound. play() Sound,
.


Flash Player 9 , Adobe AIR 1.0
.
Flash Player AIR , ,
, .
Sound ,
: ProgressEvent.PROGRESS Event.COMPLETE.
.

23.11.2012.

477

ACTIONSCRIPT 3.0

import
import
import
import

flash.events.Event;
flash.events.ProgressEvent;
flash.media.Sound;
flash.net.URLRequest;

var s:Sound = new Sound();


s.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
s.addEventListener(Event.COMPLETE, onLoadComplete);
s.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var req:URLRequest = new URLRequest("bigSound.mp3");
s.load(req);
function onLoadProgress(event:ProgressEvent):void
{
var loadedPct:uint = Math.round(100 * (event.bytesLoaded / event.bytesTotal));
trace("The sound is " + loadedPct + "% loaded.");
}
function onLoadComplete(event:Event):void
{
var localSound:Sound = event.target as Sound;
localSound.play();
}
function onIOError(event:IOErrorEvent)
{
trace("The sound could not be loaded: " + event.text);
}

Sound,
ProgressEvent.PROGRESS Event.COMPLETE. Sound.load()
ProgressEvent.PROGRESS,
onSoundLoadProgress().
bytesLoaded ProgressEvent,
bytesTotal. bytesLoaded bytesTotal
Sound. ,
bytesLoaded bytesTotal
, , Adobe Flex Adobe Flash.
,
. , , Sound
Event.IO_ERROR. onIOError(),
.


Flash Player 9 , Adobe AIR 1.0

,
, , .

23.11.2012.

478

ACTIONSCRIPT 3.0

, SWF-
. ,
SWF-.
SWF- .

Flash
Flash Player 9 , Adobe AIR 1.0
Flash
.
, ActionScript.
, , ActionScript
Flash. Flash .
Flash.
Flash
1 > > ,

.
2

. ActionScript.
3 ,

ActionScript. , .
, DrumSound.mp3, , , DrumSound;
ActionScript .
flash.media.Sound.
4 . , , .

, . ,
, ,
flash.media.Sound.
5 , ActionScript. ,

DrumSound.
var drum:DrumSound = new DrumSound();
var channel:SoundChannel = drum.play();

DrumSound flash.media.Sound
, play(), .

Flex
Flash Player 9 , Adobe AIR 1.0
Flex, :

[Embed];
@Embed MXML
, Button SoundEffect;

@Embed CSS-.
23.11.2012.

479

ACTIONSCRIPT 3.0

, ActionScript Flex
[Embed].
ActionScript, [Embed].
, .
Embed, .
Class, [Embed].
smallSound.mp3 soundClass
, .
, Sound play().
package
{
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundChannel;
public class EmbeddedSoundExample extends Sprite
{
[Embed(source="smallSound.mp3")]
public var soundClass:Class;
public function EmbeddedSoundExample()
{
var smallSound:Sound = new soundClass() as Sound;
smallSound.play();
}
}
}

Flex,
mx.core.SoundAsset, Sound.
SoundAsset .
ActionScript 3.0.


Flash Player 9 , Adobe AIR 1.0
, .
, , ,
, .
SoundMixer.bufferTime ,
Flash Player AIR .
, bufferTime 5000, Flash Player AIR
5000 ,
. SoundMixer.bufferTime 1000.

23.11.2012.

480

ACTIONSCRIPT 3.0

SoundMixer.bufferTime ,
bufferTime .
, SoundLoaderContext,
bufferTime, Sound.load(), .
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;
var s:Sound = new Sound();
var req:URLRequest = new URLRequest("bigSound.mp3");
var context:SoundLoaderContext = new SoundLoaderContext(8000, true);
s.load(req, context);
s.play();

Flash Player AIR


. ,
. , -
, . ,
.
- , Flash Player AIR
, Sound.isBuffering.


Flash Player 10 , Adobe AIR 1.5
. , Flash Player
10 Adobe AIR 1.5.
,
. ,
sampleData Sound. ( sampleData SampleDataEvent
flash.events.) Sound .
, ,
.
Sound sampleData,
. ,
Sound. play() Sound,
sampleData, . ( , Sound
mp3 .)
SampleDataEvent data. data
ByteArray.
, Sound. ,
-1 1.
( ) . ()
44100 . ,
.

23.11.2012.

481

ACTIONSCRIPT 3.0

ByteArray.writeFloat() data
sampleData. , .
var mySound:Sound = new Sound();
mySound.addEventListener(SampleDataEvent.SAMPLE_DATA, sineWaveGenerator);
mySound.play();
function sineWaveGenerator(event:SampleDataEvent):void
{
for (var i:int = 0; i < 8192; i++)
{
var n:Number = Math.sin((i + event.position) / Math.PI / 4);
event.data.writeFloat(n);
event.data.writeFloat(n);
}
}

Sound.play(), ,
.
SoundChannel.stop().

Flash Player AIR. , .
, :
(SampleDataEvent.position / 44.1) - SoundChannelObject.position

2048 8192 data SampleDataEvent (


). ( 8192).
,
. - ,
, . ,
2048 , .
, .
2048 ( sampleData),
SoundChannel
SoundComplete.

, mp3
Flash Player 10 , Adobe AIR 1.5
Sound Sound.extract().
( ) Sound
. , MP3-
, upOctave().

23.11.2012.

482

ACTIONSCRIPT 3.0

var mySound:Sound = new Sound();


var sourceSnd:Sound = new Sound();
var urlReq:URLRequest = new URLRequest("test.mp3");
sourceSnd.load(urlReq);
sourceSnd.addEventListener(Event.COMPLETE, loaded);
function loaded(event:Event):void
{
mySound.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound);
mySound.play();
}
function processSound(event:SampleDataEvent):void
{
var bytes:ByteArray = new ByteArray();
sourceSnd.extract(bytes, 8192);
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;
}


Flash Player 10 , Adobe AIR 1.5
sampleData Sound
Sound Sound.extract() Sound.play().
. SoundChannel
.


Flash Player 9 , Adobe AIR 1.0
, Sound.play() Sound,
.
var snd:Sound = new Sound(new URLRequest("smallSound.mp3"));
snd.play();

ActionScript 3.0, :

;
23.11.2012.

483

ACTIONSCRIPT 3.0

;
;
;
.
SoundChannel,
SoundMixer SoundTransform.
SoundChannel . SoundChannel.position
,
.
Sound.play(), SoundChannel
.
, .
startTime Sound.play().
, loops
Sound.play().
Sound.play() startTime loops,
, , .
var snd:Sound = new Sound(new URLRequest("repeatingSound.mp3"));
snd.play(1000, 3);

, ,
.


Flash Player 9 , Adobe AIR 1.0
, , ,

. ActionScript ,
. .
, , .
, , .
var snd:Sound = new Sound(new URLRequest("bigSound.mp3"));
var channel:SoundChannel = snd.play();

SoundChannel.position ,
. ,
, .
var pausePosition:int = channel.position;
channel.stop();

, ,
, .
channel = snd.play(pausePosition);

23.11.2012.

484

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, , ,
, .
SoundChannel Event.SOUND_COMPLETE, .
, , ,
.
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
var snd:Sound = new Sound();
var req:URLRequest = new URLRequest("smallSound.mp3");
snd.load(req);
var channel:SoundChannel = snd.play();
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
public function onPlaybackComplete(event:Event)
{
trace("The sound has finished playing.");
}

SoundChannel progress .
,
.
, ,
SoundChannel.position .
var playbackPercent:uint = 100 * (channel.position / snd.length);

,
. Sound.length
, .
, ,
.
bytesLoaded bytesTotal Sound, .
var estimatedLength:int =
Math.ceil(snd.length / (snd.bytesLoaded / snd.bytesTotal));
var playbackPercent:uint = 100 * (channel.position / estimatedLength);

Event.ENTER_FRAME
.
, ,
.

23.11.2012.

485

ACTIONSCRIPT 3.0

import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
var snd:Sound = new Sound();
var req:URLRequest = new
URLRequest("http://av.adobe.com/podcast/csbu_dev_podcast_epi_2.mp3");
snd.load(req);
var channel:SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
function onEnterFrame(event:Event):void
{
var estimatedLength:int =
Math.ceil(snd.length / (snd.bytesLoaded / snd.bytesTotal));
var playbackPercent:uint =
Math.round(100 * (channel.position / estimatedLength));
trace("Sound playback is " + playbackPercent + "% complete.");
}
function onPlaybackComplete(event:Event)
{
trace("The sound has finished playing.");
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}

snd.play()
SoundChannel channel.
Event.ENTER_FRAME, SoundChannel
Event.SOUND_COMPLETE, .
, , onEnterFrame().
onEnterFrame()
, .
onPlaybackComplete(),
Event.ENTER_FRAME,
.
Event.ENTER_FRAME .
.
flash.util.Timer. .
1.

23.11.2012.

486

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
:
. SoundChannel.stop()
SoundChannel, , ,
. ,
.
, Sound.close().

Flash Player 9 , Adobe AIR 1.0



Flash Player AIR.
: (
) , (
). AIR
, , .
,
Flash Player. Flash Player
. 1120.

id3 SoundMixer.computeSpectrum().
.

. , , SWF-
, .
,
.
SoundLoaderContext checkPolicyFile
Sound.load(). checkPolicyFile true, Flash
Player AIR , .
SWF-, SWF-
id3 Sound SoundMixer.computeSpectrum() .
.
,
.
SoundMixer.stopAll() SoundChannel,
, :

23.11.2012.

487

ACTIONSCRIPT 3.0

, ,
, SoundMixer.stopAll().
AIR
(, AIR).
, SoundMixer.stopAll() ,
SoundMixer.areSoundsInaccessible().
true,
SoundMixer.stopAll().
SoundMixer.stopAll() ,
. , FLA-
Flash, , .


Flash Player 9 , Adobe AIR 1.0
SoundChannel , . mp3 , SoundChannel
.
leftPeak rightPeak
SoundChannel. .
.
, SoundChannel
SoundMixer.
pan SoundChannel
. pan -1 1,
-1 , , 1
, . -1 1
, 0 ,
.
SoundTransform 0,6 -1 (
). SoundTransform
play(), SoundChannel,
.
var snd:Sound = new Sound(new URLRequest("bigSound.mp3"));
var trans:SoundTransform = new SoundTransform(0.6, -1);
var channel:SoundChannel = snd.play(0, 1, trans);

,
pan volume SoundTransform
soundTransform SoundChannel.

soundTransform SoundMixer, .
SoundMixer.soundTransform = new SoundTransform(1, -1);

23.11.2012.

488

ACTIONSCRIPT 3.0

, SoundTransform
Microphone (. 494), Sprite
SimpleButton.

.
import
import
import
import
import

flash.events.Event;
flash.media.Sound;
flash.media.SoundChannel;
flash.media.SoundMixer;
flash.net.URLRequest;

var snd:Sound = new Sound();


var req:URLRequest = new URLRequest("bigSound.mp3");
snd.load(req);
var panCounter:Number = 0;
var trans:SoundTransform;
trans = new SoundTransform(1, 0);
var channel:SoundChannel = snd.play(0, 1, trans);
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event):void
{
trans.pan = Math.sin(panCounter);
channel.soundTransform = trans; // or SoundMixer.soundTransform = trans;
panCounter += 0.05;
}
function onPlaybackComplete(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}

, SoundTransform 1 (
) 0 ( ).
snd.play(), SoundTransform.
onEnterFrame(). onEnterFrame()
Math.sin(), -1 1.
SoundTransform.pan. pan SoundTransform
, soundTransform .
, bigSound.mp3 mp3-.
. , , .
, soundTransform SoundMixer.
, ,
SoundChannel.

23.11.2012.

489

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
mp3 ID3.
mp3- ID3. Sound mp3,
Event.ID3, ID3. ,
Event.ID3, Sound.id3
.
, , ID3 .
import flash.events.Event;
import flash.media.ID3Info;
import flash.media.Sound;
var s:Sound = new Sound();
s.addEventListener(Event.ID3, onID3InfoReceived);
s.load("mySound.mp3");
function onID3InfoReceived(event:Event)
{
var id3:ID3Info = event.target.id3;
trace("Received ID3 Info:");
for (var propName:String in id3)
{
trace(propName + " = " + id3[propName]);
}
}

Sound Event.ID3.
ID3 onID3InfoReceived().
Event, onID3InfoReceived() Sound,
id3, , .


Flash Player 9 , Adobe AIR 1.0
SoundMixer.computeSpectrum()
.
SoundChannel, SoundMixer.computeSpectrum()
SoundChannel.
ByteArray, 512 ,
-1 1.
. , 256 :
, .

23.11.2012.

490

491

ACTIONSCRIPT 3.0

FFTMode true, SoundMixer.computeSpectrum()


, . :
. (FFT)
. 0
1,414 ( 2).
, computeSpectrum()
FFTMode true false. , ,
.
Left Channel

Right Channel

Left Channel

Right Channel

, SoundMixer.computeSpectrum()
A. fftMode=true . fftMode=false

computeSpectrum() ,
. ,
. stretchFactor ,
computeSpectrum(). stretchFactor 0 (
), 44,1 .
stretchFactor, 1 22,05 ,
2 11,025 .. computeSpectrum() 256
, stretchFactor.
SoundMixer.computeSpectrum() .

RTMP- SoundMixer,
SoundMixer.computeSpectrum() .


, SoundMixer.computeSpectrum() -
.
SoundMixer.computeSpectrum() .
487 1148.

23.11.2012.

ACTIONSCRIPT 3.0

AIR
(, AIR).


Flash Player 9 , Adobe AIR 1.0
SoundMixer.computeSpectrum()
.
import
import
import
import
import
import

flash.display.Graphics;
flash.events.Event;
flash.media.Sound;
flash.media.SoundChannel;
flash.media.SoundMixer;
flash.net.URLRequest;

const PLOT_HEIGHT:int = 200;


const CHANNEL_LENGTH:int = 256;
var snd:Sound = new Sound();
var req:URLRequest = new URLRequest("bigSound.mp3");
snd.load(req);
var channel:SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
var bytes:ByteArray = new ByteArray();
function onEnterFrame(event:Event):void
{
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;
// left channel
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);

23.11.2012.

492

ACTIONSCRIPT 3.0

g.endFill();
// right channel
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();
}
function onPlaybackComplete(event:Event)
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}

,
Event.ENTER_FRAME, onEnterFrame() .
onEnterFrame() SoundMixer.computeSpectrum(),
ByteArray bytes.
API- .
for 256 ( )
Graphics.lineTo(). for 256 ,
, .
, .

23.11.2012.

493

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Microphone ,
,
, Flash Media Server.
.

. , , Speex
Nellymoser. ( Speex , Flash Player 10 Adobe AIR 1.5.)


(Michael Chaize): AIR, Android
(Christophe Coenraets): Android


Flash Player 9 , Adobe AIR 1.0
Microphone .
Microphone.getMicrophone(), Microphone,
.
var mic:Microphone = Microphone.getMicrophone();

Microphone.getMicrophone() ,
.
.
Microphone.names, .
Microphone.getMicrophone() index,
.
, .
Microphone.names Microphone.getMicrophone() ,

. , names
, getMicrophone() null.
Microphone.getMicrophone(), Flash Player
Flash Player, Flash
Player . ,
, StatusEvent. code StatusEvent
, , .

23.11.2012.

494

ACTIONSCRIPT 3.0

import flash.media.Microphone;
var mic:Microphone = Microphone.getMicrophone();
mic.addEventListener(StatusEvent.STATUS, this.onMicStatus);
function onMicStatus(event:StatusEvent):void
{
if (event.code == "Microphone.Unmuted")
{
trace("Microphone access was allowed.");
}
else if (event.code == "Microphone.Muted")
{
trace("Microphone access was denied.");
}
}

StatusEvent.code Microphone.Unmuted, ,
Microphone.Muted, .
Microphone.muted true false,
. muted Microphone
StatusEvent,
StatusEvent.STATUS, Microphone.muted.
Flash Player ,
( 215 x 138 ).
.
, AIR,
. , status
. ,
AIR , ,
status .


Flash Player 9 , Adobe AIR 1.0
, ,
Microphone.setLoopback(), true.
,
,
. Microphone.setUseEchoSuppression() true
, . Adobe
Microphone.setUseEchoSuppression(true)
Microphone.setLoopback(true), ,
, .
.
var mic:Microphone = Microphone.getMicrophone();
mic.setUseEchoSuppression(true);
mic.setLoopBack(true);

23.11.2012.

495

ACTIONSCRIPT 3.0

,
Flash Player 9 , Adobe AIR 1.0
, , . -,
, ,
. Microphone.gain 0 100
. 50 1 . 0
0 . 50 .
.
, , ,
. Microphone.rate
(). 8 .
, Microphone.rate 8 .
, Microphone.rate 11, 11
, 22 22 .
. Nellymoser , 5, 8, 11, 16, 22
44 . Speex (, Flash Player 10 Adobe AIR
1.5) 16 .


Flash Player 9 , Adobe AIR 1.0
Flash Player
, .
, Flash Player
ActivityEvent. Speex (, Flash Player
10 Adobe AIR 1.5) ,
. Speex
.
. Microphone activity,
. , setLoopBack( true ) ,
NetStream.
activity .
Microphone .

activityLevel, , ,
, 0 100.

silenceLevel ,
ActivityEvent.ACTIVITY. silenceLevel 0 100,
10.

silenceTimeout ,
,
ActivityEvent.ACTIVITY, , .
silenceTimeout 2000.

Microphone.silenceLevel, Microphone.silenceTimeout
, Microphone.setSilenceLevel().

23.11.2012.

496

ACTIONSCRIPT 3.0


.
. Microphone.setSilenceLevel()
silenceLevel 0, Flash Player
, . ,
silenceLevel 100, .
, activity status,
Microphone.
import flash.events.ActivityEvent;
import flash.events.StatusEvent;
import flash.media.Microphone;
var deviceArray:Array = Microphone.names;
trace("Available sound input devices:");
for (var i:int = 0; i < deviceArray.length; i++)
{
trace(" " + deviceArray[i]);
}
var mic:Microphone = Microphone.getMicrophone();
mic.gain = 60;
mic.rate = 11;
mic.setUseEchoSuppression(true);
mic.setLoopBack(true);
mic.setSilenceLevel(5, 1000);
mic.addEventListener(ActivityEvent.ACTIVITY, this.onMicActivity);
mic.addEventListener(StatusEvent.STATUS, this.onMicStatus);
var micDetails:String = "Sound input device name: " + mic.name + '\n';
micDetails += "Gain: " + mic.gain + '\n';
micDetails += "Rate: " + mic.rate + " kHz" + '\n';
micDetails += "Muted: " + mic.muted + '\n';
micDetails += "Silence level: " + mic.silenceLevel + '\n';
micDetails += "Silence timeout: " + mic.silenceTimeout + '\n';
micDetails += "Echo suppression: " + mic.useEchoSuppression + '\n';
trace(micDetails);
function onMicActivity(event:ActivityEvent):void
{
trace("activating=" + event.activating + ", activityLevel=" +
mic.activityLevel);
}
function onMicStatus(event:StatusEvent):void
{
trace("status: level=" + event.level + ", code=" + event.code);
}

,
trace .

23.11.2012.

497

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
ActionScript , Flash Media
Server, .
, Microphone NetStream
.
MovieClip Video.
Speex , Flash Player 10 Adobe AIR 1.5. ,
- , codec
Microphone. , SoundCodec.
codec SoundCodec.SPEEX, Speex.
SoundCodec.NELLYMOSER ( ), Nellymoser.
. Flash Media Server
www.adobe.com/go/learn_fms_docs_ru.


Flash Player 10.1 , Adobe AIR 2
Flash Player 10.1 AIR 2
.
.
, sampleData
Microphone. Microphone sampleData ,
. SampleDataEvent data,
.
, .
ByteArray soundBytes:
var mic:Microphone = Microphone.getMicrophone();
mic.setSilenceLevel(0, DELAY_LENGTH);
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
function micSampleDataHandler(event:SampleDataEvent):void {
while(event.data.bytesAvailable) {
var sample:Number = event.data.readFloat();
soundBytes.writeFloat(sample);
}
}

Sound.
rate Microphone 44,
, Sound. ,
, 44 , Sound. ,
Microphone , Sound .
, Microphone, Sound .
4
Sound:

23.11.2012.

498

ACTIONSCRIPT 3.0

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();
function micSampleDataHandler(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
soundBytes.writeFloat(sample);
}
}
var sound:Sound = new Sound();
var channel:SoundChannel;
function timerHandler(event:TimerEvent):void
{
mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
timer.stop();
soundBytes.position = 0;
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playbackSampleHandler);
channel.addEventListener( Event.SOUND_COMPLETE, playbackComplete );
channel = sound.play();
}
function playbackSampleHandler(event:SampleDataEvent):void
{
for (var i:int = 0; i < 8192 && soundBytes.bytesAvailable > 0; i++)
{
trace(sample);
var sample:Number = soundBytes.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
function playbackComplete( event:Event ):void
{
trace( "Playback finished.");
}

.
481.

23.11.2012.

499

ACTIONSCRIPT 3.0

: Podcast Player
Flash Player 9 , Adobe AIR 1.0
, .
, , .
,
. , ,
mp3. ,
, mp3-.
. ,

.
.
PodcastPlayer ActionScript:

RSS XML-;
SoundFacade ;
;
.

www.adobe.com/go/learn_programmingAS3samples_flash_ru. Podcast Player
Samples/PodcastPlayer. .
File

PodcastPlayer.mxml

Flex (MXML) Flash (FLA).

PodcastPlayer.fla
comp/example/progra , (
mmingas3/podcastplay Flash).
er/PodcastPlayer.as
SoundPlayer.mxml

MXML, ,
, Flex.

main.css

( Flex).

images/

( Flex).

comp/example/progra SoundPlayer,
mmingas3/podcastplay ( Flash).
er/SoundPlayer.as
comp/example/progra ,
mmingas3/podcastplay DataGrid ( Flash).
er/PlayButtonRenderer.
as
com/example/program , RSSChannel RSSItem.
mingas3/podcastplayer
/RSSBase.as

23.11.2012.

500

ACTIONSCRIPT 3.0

File

com/example/program ActionScript, RSS.


mingas3/podcastplayer
/RSSChannel.as
com/example/program ActionScript, RSS.
mingas3/podcastplayer
/RSSItem.as
com/example/program ActionScript . Sound SoundChannel
mingas3/podcastplayer .
/SoundFacade.as
com/example/program ActionScript, URL-.
mingas3/podcastplayer
/URLService.as
playerconfig.xml

XML-, RSS, .

comp/example/progra , ( Flash).
mmingas3/utils/DateUt
il.as

RSS
Flash Player 9 , Adobe AIR 1.0
Podcast Player
.
1. XML- ,
.
2. , RSS
.
URLLoader
. Podcast Player URLLoader,
RSS XML playerconfig.xml. ,
, URLLoader RSS
URL- .


SoundFacade
Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 . ,
, ,
, .
.
SoundFacade :

Sound, SoundLoaderContext SoundMixer;


Sound SoundChannel;

23.11.2012.

501

ACTIONSCRIPT 3.0

;
Sound SoundChannel.
SoundFacade ActionScript,
.
, SoundFacade().
public class SoundFacade extends EventDispatcher
{
public var s:Sound;
public var sc:SoundChannel;
public var url:String;
public var bufferTime:int = 1000;
public
public
public
public
public
public

var
var
var
var
var
var

isLoaded:Boolean = false;
isReadyToPlay:Boolean = false;
isPlaying:Boolean = false;
isStreaming:Boolean = true;
autoLoad:Boolean = true;
autoPlay:Boolean = true;

public var pausePosition:int = 0;


public static const PLAY_PROGRESS:String = "playProgress";
public var progressInterval:int = 1000;
public var playTimer:Timer;
public function SoundFacade(soundUrl:String, autoLoad:Boolean = true,
autoPlay:Boolean = true, streaming:Boolean = true,
bufferTime:int = -1):void
{
this.url = soundUrl;
// Sets Boolean values that determine the behavior of this object
this.autoLoad = autoLoad;
this.autoPlay = autoPlay;
this.isStreaming = streaming;
// Defaults to the global bufferTime value
if (bufferTime < 0)
{
bufferTime = SoundMixer.bufferTime;
}
// Keeps buffer time reasonable, between 0 and 30 seconds
this.bufferTime = Math.min(Math.max(0, bufferTime), 30000);
if (autoLoad)
{
load();
}
}

23.11.2012.

502

ACTIONSCRIPT 3.0

SoundFacade EventDispatcher,
. Sound SoundChannel.
URL- bufferTime
. , ,
.

autoLoad ,
.

autoPlay , ,
. , ,
, bufferTime.

streaming ,
.
bufferTime -1.
bufferTime, bufferTime SoundMixer.bufferTime.
SoundMixer.bufferTime
.
autoLoad true, load()
.
public function load():void
{
if (this.isPlaying)
{
this.stop();
this.s.close();
}
this.isLoaded = false;
this.s = new Sound();
this.s.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);
this.s.addEventListener(Event.OPEN, onLoadOpen);
this.s.addEventListener(Event.COMPLETE, onLoadComplete);
this.s.addEventListener(Event.ID3, onID3);
this.s.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
this.s.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onIOError);
var req:URLRequest = new URLRequest(this.url);
var context:SoundLoaderContext = new SoundLoaderContext(this.bufferTime, true);
this.s.load(req, context);
}

load() Sound
. Sound , SoundLoaderContext
bufferTime.
url , SoundFacade
:
url load(), .

23.11.2012.

503

ACTIONSCRIPT 3.0

, SoundFacade
.
public function onLoadOpen(event:Event):void
{
if (this.isStreaming)
{
this.isReadyToPlay = true;
if (autoPlay)
{
this.play();
}
}
this.dispatchEvent(event.clone());
}
public function onLoadProgress(event:ProgressEvent):void
{
this.dispatchEvent(event.clone());
}
public function onLoadComplete(event:Event):void
{
this.isReadyToPlay = true;
this.isLoaded = true;
this.dispatchEvent(evt.clone());
if (autoPlay && !isPlaying)
{
play();
}
}

onLoadOpen() .
, onLoadComplete() isReadyToPlay true.
isReadyToPlay , , ,
, Play (). SoundChannel
, ,
, play().
onLoadProgress() .
ProgressEvent , SoundFacade.
onLoadComplete(),
play() . play() .

23.11.2012.

504

ACTIONSCRIPT 3.0

public function play(pos:int = 0):void


{
if (!this.isPlaying)
{
if (this.isReadyToPlay)
{
this.sc = this.s.play(pos);
this.sc.addEventListener(Event.SOUND_COMPLETE, onPlayComplete);
this.isPlaying = true;
this.playTimer = new Timer(this.progressInterval);
this.playTimer.addEventListener(TimerEvent.TIMER, onPlayTimer);
this.playTimer.start();
}
}
}

play() Sound.play(), .
SoundChannel sc. play() Timer,
.


Flash Player 9 , Adobe AIR 1.0
Timer ,
. Timer ,
SoundFacade,
, .
Timer, SoundFacade.play(), TimerEvent.
onPlayTimer() TimerEvent.
public function onPlayTimer(event:TimerEvent):void
{
var estimatedLength:int =
Math.ceil(this.s.length / (this.s.bytesLoaded / this.s.bytesTotal));
var progEvent:ProgressEvent =
new ProgressEvent(PLAY_PROGRESS, false, false, this.sc.position, estimatedLength);
this.dispatchEvent(progEvent);
}

onPlayTimer() ,
485. ProgressEvent
SoundFacade.PLAY_PROGRESS, bytesLoaded
SoundChannel, bytesTotal .


Flash Player 9 , Adobe AIR 1.0
SoundFacade.play(), , pos,
. pos 0, .
SoundFacade.stop() pos, .

23.11.2012.

505

ACTIONSCRIPT 3.0

public function stop(pos:int = 0):void


{
if (this.isPlaying)
{
this.pausePosition = pos;
this.sc.stop();
this.playTimer.stop();
this.isPlaying = false;
}
}

SoundFacade.stop() pausePosition,
,
.
SoundFacade.pause() SoundFacade.resume(), ,
SoundFacade.stop() SoundFacade.play() , pos.
public function pause():void
{
stop(this.sc.position);
}
public function resume():void
{
play(this.pausePosition);
}

pause() SoundChannel.position play(),


pausePosition. resume() ,
pausePosition.

Podcast Player
Flash Player 9 , Adobe AIR 1.0
Podcast Player,
SoundFacade . ,
, :


SharedObject, .

RSS .
, ,
.

mp3- ,
.

,
.

API-
, Odeo.com.

23.11.2012.

506

507

25.
Flash Player 9 , Adobe AIR 1.0
Flash- .

. ActionScript
, , .


Flash Player 9 , Adobe AIR 1.0
Adobe Flash Player Adobe AIR
ActionScript ,
, , , . Flash Video (FLV)
Adobe Flash CS4 Professional, ,
. . ActionScript
,
,
. ActionScript
.

Video : Video.
Video , ,
, , , ,
.

StageVideo: Video .
,
,
StageVideo. API- StageVideo , ,
StageVideo Video. StageVideo
.
, API- StageVideo. .
551.

NetStream: ActionScript, NetStream


, .
NetStream NetConnection, .
, .

Camera: , ,
Camera ,
. Flash Player 11.4 AIR 3.4 ,
StageVideo.
-
, Adobe Flash Media Server.

23.11.2012.

508

ACTIONSCRIPT 3.0


, .
,
, .
, ,

,
.
. ,

.
.
, . , ,
,
.
, .
-,
, .
, .
.

,
( ).
. ,
.
, ,
.


Flash Player 9 , Adobe AIR 1.0
Adobe FLV, Flash Player Adobe AIR ,
H.264 HE-AAC MPEG-4.
.
, Adobe Premiere Pro Adobe After Effects,
.

H.264

MPEG-4: MP4, M4V, F4V, 3GPP

Sorenson Spark

FLV-

ON2 VP6

FLV-

AAC+ / HE-AAC / AAC v1 / AAC v2

MPEG-4:MP4, M4V, F4V, 3GPP

23.11.2012.

509

ACTIONSCRIPT 3.0

Mp3

Mp3

Nellymoser

FLV-

Speex

FLV-


Flash Media Server:
HTML Adobe


AIR Android H.264 .
H.264 . ,
. Adobe
Flash Player H.264, .
.
H.264 .
.
, .
.
, .
, ,
.
, , ,
.

4:3

640 480

512 384

480 360

16:9

640 360

512 x 288

480 272

. Flash Player H.264. ,



. .
Adobe Media Encoder CS5 .
H.264 Flash Player 10.1 .
. iOS Video ,
Sorenson Spark On2 VP6. H.264
URL- flash.net.navigateToURL(). H.264
, <video> HTML-,
StageWebView.

23.11.2012.

510

ACTIONSCRIPT 3.0

Flash Player AIR


Flash Player 9 , Adobe AIR 1.0
Flash Player 7 FLV-, Sorenson Spark. Flash
Player 8 FLV-, Sorenson Spark On2 VP6 Flash
Professional 8. On2 VP6 -.
Flash Player 9.0.115.0 ,
MPEG-4. F4V, MP4, M4A, MOV, MP4V, 3GP 3G2,
H.264 HE-AAC v2 .
Sorenson On2, H.264
. HE-AAC v2 AAC, ,
MPEG-4. HE-AAC v2 (SBR)
(PS) .
.
SWF- Flash Player AIR, .

SWF-
(

)

Flash Player AIR ( ,


)

Sorenson Spark

Flash Player 6, Flash Lite 3

On2 VP6

Flash Player 8, Flash Lite 3.


On2 VP6
Flash Player 8 .

H.264 (MPEG-4 Part 10)

Flash Player 9 3, AIR 1.0

ADPCM

Flash Player 6, Flash Lite 3

Mp3

Flash Player 6, Flash Lite 3

AAC (MPEG-4 Part 3)

Flash Player 9 3, AIR 1.0

Speex ()

10

Flash Player 10, AIR 1.5

Nellymoser

Flash Player 6

Adobe F4V FLV


Flash Player 9 , Adobe AIR 1.0
Adobe F4V FLV Flash Player AIR.
. www.adobe.com/go/video_file_format_ru.

23.11.2012.

ACTIONSCRIPT 3.0

F4V
Flash Player 9 , Adobe AIR 1.0
Flash Player Update 3 (9.0.115.0) AIR 1.0 Adobe F4V,
ISO MP4. . Flash Player
F4V-, .

ftyp
ftyp ,
.

moov
moov F4V-.
, , F4V-. F4V-
moov.

mdat
mdat F4V-. FV- mdat.
moov, mdat.
F4V- ,
.

FLV
Flash Player 9 , Adobe AIR 1.0
Adobe FLV - Flash
Player. QuickTime Windows Media FLV-
, Adobe Media Encoder Sorenson Squeeze.
. FLV- Flash
FLV-. FLV-
FLV- .
FLV- - MIME-.
. FLV- MIME- video/x-flv.
. FLV- 541.
FLV- .
540.


Flash Player 9 , Adobe AIR 1.0
,
.

, .
,
, F4V- FLV-
, .

23.11.2012.

511

ACTIONSCRIPT 3.0

, SWF-,
. , SWF- 30 (/),
21 /.
.
, ,
SWF-.

SWF-
. (, ). SWF-,
.

FLV-,
.

Video
Flash Player 9 , Adobe AIR 1.0
Video SWF.
Camera.getCamera(). , Video
HTTP .
Video .

NetConnection NetStream
Video.

. .
558.

FLVPlayback.
VideoDisplay.
. Video Video.
, Video flash.media,
flash.display.DisplayObject. ,
, Video.
. 186,
226 288.

23.11.2012.

512

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
NetStream NetConnection .
Video ,
NetStream Video play() NetStream
.
1 NetConnection.

, , Adobe Flash Media Server 2, null


connect() HTTP- .
URI- ,
.
var nc:NetConnection = new NetConnection();
nc.connect(null);

2 Video, ,

, .
var vid:Video = new Video();
addChild(vid);

3 NetStream, NetConnection.

NetStream NetConnection
.
var ns:NetStream = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandler);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
function netStatusHandler(event:NetStatusEvent):void
{
// handle netStatus events, described later
}
function asyncErrorHandler(event:AsyncErrorEvent):void
{
// ignore error
}

4 NetStream Video attachNetStream() Video,

.
vid.attachNetStream(ns);

5 play() NetStream, URL ,

. video.mp4,
, SWF-.
ns.play("video.mp4");


Flex: Spark VideoPlayer
spark.components.VideoDisplay

23.11.2012.

513

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
NetStream .
pause(): . ,

.
resume(): , .

, .
seek(): , (
, ).
togglePause(): .

. stop() . ,
.
. play() , .
.
, Button (pauseBtn,
playBtn, stopBtn togglePauseBtn).

23.11.2012.

514

ACTIONSCRIPT 3.0

var nc:NetConnection = new NetConnection();


nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play("video.flv");
function asyncErrorHandler(event:AsyncErrorEvent):void
{
// ignore error
}
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
pauseBtn.addEventListener(MouseEvent.CLICK, pauseHandler);
playBtn.addEventListener(MouseEvent.CLICK, playHandler);
stopBtn.addEventListener(MouseEvent.CLICK, stopHandler);
togglePauseBtn.addEventListener(MouseEvent.CLICK, togglePauseHandler);
function pauseHandler(event:MouseEvent):void
{
ns.pause();
}
function playHandler(event:MouseEvent):void
{
ns.resume();
}
function stopHandler(event:MouseEvent):void
{
// Pause the stream and move the playhead back to
// the beginning of the stream.
ns.pause();
ns.seek(0);
}
function togglePauseHandler(event:MouseEvent):void
{
ns.togglePause();
}

pauseBtn .
, . playBtn ,
. , .


Flash Player 9 , Adobe AIR 1.0
, netStatus
NetStream.
.

23.11.2012.

515

ACTIONSCRIPT 3.0

ns.addEventListener(NetStatusEvent.NET_STATUS, statusHandler);
function statusHandler(event:NetStatusEvent):void
{
trace(event.info.code)
}

:
NetStream.Play.Start
NetStream.Buffer.Empty
NetStream.Buffer.Full
NetStream.Buffer.Empty
NetStream.Buffer.Full
NetStream.Buffer.Empty
NetStream.Buffer.Full
NetStream.Buffer.Flush
NetStream.Play.Stop
NetStream.Buffer.Empty
NetStream.Buffer.Flush

, : NetStream.Play.Start NetStream.Play.Stop,
. switch,
.
function statusHandler(event:NetStatusEvent):void
{
switch (event.info.code)
{
case "NetStream.Play.Start":
trace("Start [" + ns.time.toFixed(3) + " seconds]");
break;
case "NetStream.Play.Stop":
trace("Stop [" + ns.time.toFixed(3) + " seconds]");
break;
}
}

netStatus (NetStatusEvent.NET_STATUS), ,

.


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR
.
AIR ,
,
.
. 179.

23.11.2012.

516

ACTIONSCRIPT 3.0

Flash Player
Flash Player
, . ,
, <object> <embed>,
allowFullScreen. allowFullScreen <embed>.
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="fullScreen" width="100%" height="100%"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
...
<param name="allowFullScreen" value="true" />
<embed src="fullScreen.swf" allowFullScreen="true" quality="high" bgcolor="#869ca7"
width="100%" height="100%" name="fullScreen" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
...
</object>

Flash > HTML


Flash .
Flex , HTML <object> <embed>,
.

Flash Player
. ,
,
. ,
, .
,
.
var fullScreenButton:Button = new Button();
fullScreenButton.label = "Full Screen";
addChild(fullScreenButton);
fullScreenButton.addEventListener(MouseEvent.CLICK, fullScreenButtonHandler);
function fullScreenButtonHandler(event:MouseEvent)
{
stage.displayState = StageDisplayState.FULL_SCREEN;
}

, Stage.displayState
StageDisplayState.FULL_SCREEN. ,
.

23.11.2012.

517

ACTIONSCRIPT 3.0

fullScreenSourceRect
. ,
. Stage.fullScreenSourceRect.
fullScreenButtonHandler() ,
.
private function fullScreenButtonHandler(event:MouseEvent)
{
var screenRectangle:Rectangle = new Rectangle(video.x, video.y, video.width, video.height);
stage.fullScreenSourceRect = screenRectangle;
stage.displayState = StageDisplayState.FULL_SCREEN;
}

, ,
Flash Player AIR. ,
, Stage.displayState.
. c ActionScript 3.0 Adobe Flash Platform.
, , ,
NetStream .
package
{
import
import
import
import
import
import
import
import
import

flash.net.NetConnection;
flash.net.NetStream;
flash.media.Video;
flash.display.StageDisplayState;
fl.controls.Button;
flash.display.Sprite;
flash.events.MouseEvent;
flash.events.FullScreenEvent;
flash.geom.Rectangle;

public class FullScreenVideoExample extends Sprite


{
var fullScreenButton:Button = new Button();
var video:Video = new Video();
public function FullScreenVideoExample()
{
var videoConnection:NetConnection = new NetConnection();
videoConnection.connect(null);
var videoStream:NetStream = new NetStream(videoConnection);
videoStream.client = this;
addChild(video);
video.attachNetStream(videoStream);
videoStream.play("http://www.helpexamples.com/flash/video/water.flv");
fullScreenButton.x = 100;

23.11.2012.

518

ACTIONSCRIPT 3.0

fullScreenButton.y = 270;
fullScreenButton.label = "Full Screen";
addChild(fullScreenButton);
fullScreenButton.addEventListener(MouseEvent.CLICK, fullScreenButtonHandler);
}
private function fullScreenButtonHandler(event:MouseEvent)
{
var screenRectangle:Rectangle = new Rectangle(video.x, video.y, video.width,
video.height);
stage.fullScreenSourceRect = screenRectangle;
stage.displayState = StageDisplayState.FULL_SCREEN;
}
public function onMetaData(infoObject:Object):void
{
// stub for callback function
}
}
}

onMetaData() ,
. ,
. onMetaData() ,
. .
521

, ,
Esc. ActionScript,
displayState StageDisplayState.NORMAL. ,
netStatus NetStream.Play.Stop.
videoStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
private function netStatusHandler(event:NetStatusEvent)
{
if(event.info.code == "NetStream.Play.Stop")
stage.displayState = StageDisplayState.NORMAL;
}


Flash Player
AIR , .

. Flash Player
StageVideo Video ( Camera; Flash Player 11.4/AIR 3.4
).
.
179. StageVideo .
StageVideo 548.

23.11.2012.

519

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Flash Media Server, NetConnection
NetStream, .
RTMP, NetConnection.connect() null
RTMP URL, rtmp://localhost/appName/appInstance.
Flash Media Server ()
, NetStream.publish(),
NetStream.play().


Flash Player 9 , Adobe AIR 1.0
Video Camera, Flash Media Server

.
, , , Mp3-, , .
. Flash Media Server
www.adobe.com/go/learn_fms_docs_ru.


Flash Player 9 , Adobe AIR 1.0
Adobe F4V FLV .
, ,
. Adobe F4V FLV
.
Flash- . ActionScript
, .

:
. .

:
. ,
.

23.11.2012.

520

ACTIONSCRIPT 3.0

ActionScript: Flash FLVPlayback.


ActionScript ,
ActionScript. .
, ( ),
. ,
,
, ActionScript. FLV-,
.
,
. ,
. , ,
.
Adobe .
Flash.
ActionScript.
, .
, FLV- ,
NetStream.onCuePoint.
F4V,
onMetaData() onXMPData()
Timer ActionScript 3.0. F4V .
onXMPData() 533.
.
521.



Flash Player 9 , Adobe AIR 1.0
,
. ,
. NetStream
, : onCuePoint ( FLV), onImageData, onMetaData, onPlayStatus, onTextData onXMPData.
, Flash
. , FLV- video.flv,
, SWF-.

23.11.2012.

521

522

ACTIONSCRIPT 3.0

var nc:NetConnection = new NetConnection();


nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play("video.flv");
function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace(event.text);
}
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

video.flv asyncError
(AsyncErrorEvent.ASYNC_ERROR). ,
. ,
, .
asyncError , ,
. FLV- , trace()
:
Error
Error
Error
Error

#2095:
#2095:
#2095:
#2095:

flash.net.NetStream
flash.net.NetStream
flash.net.NetStream
flash.net.NetStream

was
was
was
was

unable
unable
unable
unable

to
to
to
to

invoke
invoke
invoke
invoke

callback
callback
callback
callback

onMetaData.
onCuePoint.
onCuePoint.
onCuePoint.

, NetStream onMetaData
onCuePoint. .


Flash Media Server:

Object client NetStream


Flash Player 9 , Adobe AIR 1.0
client Object NetStream,
onMetaData onCuePoint .
, Object ,
asyncError.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var customClient:Object = new Object();
var ns:NetStream = new NetStream(nc);
ns.client = customClient;
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

23.11.2012.

ACTIONSCRIPT 3.0

onMetaData onCuePoint,
, .
var customClient:Object = new Object();
customClient.onMetaData = metaDataHandler;
function metaDataHandler(infoObject:Object):void
{
trace("metadata");
}

onMetaData metaDataHandler(),
. Flash ,
, onCuePoint.



Flash Player 9 , Adobe AIR 1.0
client NetStream , CustomClient,
.
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.client = new CustomClient();
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

CustomClient :
package
{
public class CustomClient
{
public function onMetaData(infoObject:Object):void
{
trace("metadata");
}
}
}

CustomClient onMetaData.
onCuePoint, asyncError
(AsyncErrorEvent.ASYNC_ERROR) flash.net.NetStream was unable to invoke callback onCuePoint
( flash.net.NetStream onCuePoint).
, onCuePoint CustomClient
asyncError.

23.11.2012.

523

ACTIONSCRIPT 3.0

NetStream

Flash Player 9 , Adobe AIR 1.0
CustomNetStream, .
var ns:CustomNetStream = new CustomNetStream();
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

CustomNetStream, NetStream,
NetConnection onMetaData onCuePoint.
package
{
import flash.net.NetConnection;
import flash.net.NetStream;
public class CustomNetStream extends NetStream
{
private var nc:NetConnection;
public function CustomNetStream()
{
nc = new NetConnection();
nc.connect(null);
super(nc);
}
public function onMetaData(infoObject:Object):void
{
trace("metadata");
}
public function onCuePoint(infoObject:Object):void
{
trace("cue point");
}
}
}

onMetaData() onCuePoint() CustomNetStream,


:

23.11.2012.

524

ACTIONSCRIPT 3.0

package
{
import flash.net.NetConnection;
import flash.net.NetStream;
public class CustomNetStream extends NetStream
{
private var nc:NetConnection;
public var onMetaData:Function;
public var onCuePoint:Function;
public function CustomNetStream()
{
onMetaData = metaDataHandler;
onCuePoint = cuePointHandler;
nc = new NetConnection();
nc.connect(null);
super(nc);
}
private function metaDataHandler(infoObject:Object):void
{
trace("metadata");
}
private function cuePointHandler(infoObject:Object):void
{
trace("cue point");
}
}
}

NetStream
Flash Player 9 , Adobe AIR 1.0
NetStream ,
onCuePoint onMetaData . .
var ns:DynamicCustomNetStream = new DynamicCustomNetStream();
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

DynamicCustomNetStream :

23.11.2012.

525

ACTIONSCRIPT 3.0

package
{
import flash.net.NetConnection;
import flash.net.NetStream;
public dynamic class DynamicCustomNetStream extends NetStream
{
private var nc:NetConnection;
public function DynamicCustomNetStream()
{
nc = new NetConnection();
nc.connect(null);
super(nc);
}
}
}

onMetaData onCuePoint,
, DynamicCustomNetStream .
onMetaData onCuePoint, :
var ns:DynamicCustomNetStream = new DynamicCustomNetStream();
ns.onMetaData = metaDataHandler;
ns.onCuePoint = cuePointHandler;
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
function metaDataHandler(infoObject:Object):void
{
trace("metadata");
}
function cuePointHandler(infoObject:Object):void
{
trace("cue point");
}

this client NetStream


Flash Player 9 , Adobe AIR 1.0
client this, onMetaData() onCuePoint()
. .
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.client = this;
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);

23.11.2012.

526

527

ACTIONSCRIPT 3.0

onMetaData onCuePoint ,
. ,
onMetaData() onCuePoint(), :
function onMetaData(infoObject:Object):void
{
trace("metadata");
}
function onCuePoint(infoObject:Object):void
{
trace("cue point");
}


Flash Player 9 , Adobe AIR 1.0
NetStream
.


Flash Player 9 , Adobe AIR 1.0
,
F4V- FLV- Flash Player AIR.

F4V

FLV

Flash Player 9/ AIR1.0

OnCuePoint
OnMetaData

Flash Player 10

OnCuePoint
OnMetaData

OnMetaData

OnXMPData

OnXMPData

for..in,
infoObject, onCuePoint().
trace() .

23.11.2012.

ACTIONSCRIPT 3.0

var nc:NetConnection = new NetConnection();


nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.client = this;
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
function onCuePoint(infoObject:Object):void
{
var key:String;
for (key in infoObject)
{
trace(key + ": " + infoObject[key]);
}
}

:
parameters:
name: point1
time: 0.418
type: navigation

,
. . .
521.


Flash Player 9 , Adobe AIR 1.0
OnMetaData() OnXMPData() ,
.

OnMetaData()
Flash Player 9 , Adobe AIR 1.0
, , ,
. , , ,
.

23.11.2012.

528

ACTIONSCRIPT 3.0

var nc:NetConnection = new NetConnection();


nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.client = this;
ns.play("video.flv");
var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);
function onMetaData(infoObject:Object):void
{
var key:String;
for (key in infoObject)
{
trace(key + ": " + infoObject[key]);
}
}

:
width: 320
audiodelay: 0.038
canSeekToEnd: true
height: 213
cuePoints: ,,
audiodatarate: 96
duration: 16.334
videodatarate: 400
framerate: 15
videocodecid: 4
audiocodecid: 2

, , (, audiodatarate)
undefined,
.
.
, ,
Object.

23.11.2012.

529

ACTIONSCRIPT 3.0

function traceObject(obj:Object, indent:uint = 0):void


{
var indentString:String = "";
var i:uint;
var prop:String;
var val:*;
for (i = 0; i < indent; i++)
{
indentString += "\t";
}
for (prop in obj)
{
val = obj[prop];
if (typeof(val) == "object")
{
trace(indentString + " " + prop + ": [Object]");
traceObject(val, indent + 1);
}
else
{
trace(indentString + " " + prop + ": " + val);
}
}
}

infoObject onMetaData(),
:
width: 320
audiodatarate: 96
audiocodecid: 2
videocodecid: 4
videodatarate: 400
canSeekToEnd: true
duration: 16.334
audiodelay: 0.038
height: 213
framerate: 15
cuePoints: [Object]
0: [Object]
parameters: [Object]
lights: beginning
name: point1
time: 0.418
type: navigation
1: [Object]
parameters: [Object]
lights: middle
name: point2
time: 7.748
type: navigation
2: [Object]
parameters: [Object]
lights: end
name: point3
time: 16.02
type: navigation

23.11.2012.

530

ACTIONSCRIPT 3.0

MP4.
TextArea metaDataOut,
package
{
import
import
import
import
import
import
import
import

flash.net.NetConnection;
flash.net.NetStream;
flash.events.NetStatusEvent;
flash.media.Video;
flash.display.StageDisplayState;
flash.display.Loader;
flash.display.Sprite;
flash.events.MouseEvent;

public class onMetaDataExample extends Sprite


{
var video:Video = new Video();
public function onMetaDataExample():void
{
var videoConnection:NetConnection = new NetConnection();
videoConnection.connect(null);
var videoStream:NetStream = new NetStream(videoConnection);
videoStream.client = this;
addChild(video);
video.x = 185;
video.y = 5;
video.attachNetStream(videoStream);
videoStream.play("video.mp4");
videoStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
}
public function onMetaData(infoObject:Object):void
{
for(var propName:String in infoObject)
{
metaDataOut.appendText(propName + "=" + infoObject[propName] + "\n");
}
}
private function netStatusHandler(event:NetStatusEvent):void
{
if(event.info.code == "NetStream.Play.Stop")
stage.displayState = StageDisplayState.NORMAL;
}
}
}

onMetaData() :

23.11.2012.

531

ACTIONSCRIPT 3.0

moovposition=731965
height=352
avclevel=21
videocodecid=avc1
duration=2.36
width=704
videoframerate=25
avcprofile=88
trackinfo=[object Object]


,
onMetaData() Object, .

aacaot

AAC; 0, 1 2.

avclevel

AVC IDC, 10, 11, 20, 21 . .

avcprofile

AVC, 55, 77, 100 . .

audiocodecid

, ( /),
Mp3 mp4a.

audiodatarate

, , ( ).

audiodelay

, , time 0 FLV-.
.

canSeekToEnd

true, FLV-
, .
false, FLV- .

cuePoints

, , FLV-. ,
FLV- . :

type: , : navigation ( )
event ( ).

name: , .

time: ,
().

parameters: , -,

.
duration

, ( ).

framerate

FLV-.

height

, FLV-, .

seekpoints

, , .
.

tags

-, ilst, ID3
MP4-. iTunes. ,
.

trackinfo

, MP4-,
.

23.11.2012.

532

ACTIONSCRIPT 3.0

videocodecid

, , , avc1
VP6F.

videodatarate

FLV-.

videoframerate

MP4.

width

, FLV-, .

videocodecid.
videocodecid

Sorenson H.263

Screen video ( SWF 7 )

VP6 ( SWF 8 )

VP6- - ( SWF 8 )

audiocodecid.
audiocodecid

ADPCM

Mp3

Nellymoser, 16 ,

Nellymoser, 8 ,

Nellymoser

10

AAC

11

Speex

onXMPData()
Flash Player 10 , Adobe AIR 1.5
onXMPData()
Adobe Extensible Metadata Platform (XMP), Adobe F4V FLV. XMP
. XMP
Flash Player 10 Adobe AIR 1.5 .
XMP.

23.11.2012.

533

ACTIONSCRIPT 3.0

package
{
import
import
import
import

flash.display.*;
flash.net.*;
flash.events.NetStatusEvent;
flash.media.Video;

public class onXMPDataExample extends Sprite


{
public function onXMPDataExample():void
{
var videoConnection:NetConnection = new NetConnection();
videoConnection.connect(null);
var videoStream:NetStream = new NetStream(videoConnection);
videoStream.client = this;
var video:Video = new Video();
addChild(video);
video.attachNetStream(videoStream);
videoStream.play("video.f4v");
}
public function onMetaData(info:Object):void {
trace("onMetaData fired");
}
public function onXMPData(infoObject:Object):void
{
trace("onXMPData Fired\n");
//trace("raw XMP =\n");
//trace(infoObject.data);
var cuePoints:Array = new Array();
var cuePoint:Object;
var strFrameRate:String;
var nTracksFrameRate:Number;
var strTracks:String = "";
var onXMPXML = new XML(infoObject.data);
// Set up namespaces to make referencing easier
var xmpDM:Namespace = new Namespace("http://ns.adobe.com/xmp/1.0/DynamicMedia/");
var rdf:Namespace = new Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
for each (var it:XML in onXMPXML..xmpDM::Tracks)
{

23.11.2012.

534

ACTIONSCRIPT 3.0

var strTrackName:String =
it.rdf::Bag.rdf::li.rdf::Description.@xmpDM::trackName;
var strFrameRateXML:String =
it.rdf::Bag.rdf::li.rdf::Description.@xmpDM::frameRate;
strFrameRate = strFrameRateXML.substr(1,strFrameRateXML.length);
nTracksFrameRate = Number(strFrameRate);
strTracks += it;
}
var onXMPTracksXML:XML = new XML(strTracks);
var strCuepoints:String = "";
for each (var item:XML in onXMPTracksXML..xmpDM::markers)
{
strCuepoints += item;
}
trace(strCuepoints);
}
}
}

startrekintro.f4v :
XMP.

23.11.2012.

535

ACTIONSCRIPT 3.0

onMetaData fired
onXMPData Fired
<xmpDM:markers xmlns:xmp="http://ns.adobe.com/xap/1.0/"
xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/"
xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#"
xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/"
xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#"
xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdfsyntax-ns#" xmlns:x="adobe:ns:meta/">
<rdf:Seq>
<rdf:li>
<rdf:Description xmpDM:startTime="7695905817600" xmpDM:name="Title1"
xmpDM:type="FLVCuePoint" xmpDM:cuePointType="Navigation">
<xmpDM:cuePointParams>
<rdf:Seq>
<rdf:li xmpDM:key="Title" xmpDM:value="Star Trek"/>
<rdf:li xmpDM:key="Color" xmpDM:value="Blue"/>
</rdf:Seq>
</xmpDM:cuePointParams>
</rdf:Description>
</rdf:li>
<rdf:li>
<rdf:Description xmpDM:startTime="10289459980800" xmpDM:name="Title2"
xmpDM:type="FLVCuePoint" xmpDM:cuePointType="Event">
<xmpDM:cuePointParams>
<rdf:Seq>
<rdf:li xmpDM:key="William Shatner" xmpDM:value="First Star"/>
<rdf:li xmpDM:key="Color" xmpDM:value="Light Blue"/>
</rdf:Seq>
</xmpDM:cuePointParams>
</rdf:Description>
</rdf:li>
</rdf:Seq>
</xmpDM:markers>
onMetaData fired

. XMP , DVA.
, . , 7695905817600,
254016000000 30:30.
XMP, ,
( //) trace()
onXMPData().
XMP . :

partners.adobe.com/public/developer/xmp/topic.html
www.adobe.com/devnet/xmp/

23.11.2012.

536

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
onImageData AMF0.
JPEG, PNG GIF. onImageData()
, onCuePoint onMetaData.
onImageData() .
public function onImageData(imageData:Object):void
{
// display track number
trace(imageData.trackid);
var loader:Loader = new Loader();
//imageData.data is a ByteArray object
loader.loadBytes(imageData.data);
addChild(loader);
}


Flash Player 9 , Adobe AIR 1.0
onTextData AMF0.
UTF-8
3GP. .
onTextData() ,
onCuePoint onMetaData. onTextData()
.
public function onTextData(textData:Object):void
{
// display the track number
trace(textData.trackid);
// displays the text, which can be a null string, indicating old text
// that should be erased
trace(textData.text);
}

NetStream
Flash Player 10.3 , Adobe AIR 2.7
NetStream ,
. ,
,
, ,
, .
.
NetMonitor NetStream .
NetMonitor NetStream, ,
, NetStream.

23.11.2012.

537

538

ACTIONSCRIPT 3.0

NetStream , ,
.

RTMP-

HTTP-

NetStream.Play.Start

NetStream.Play.Stop

NetStream.Play.Complete

NetStream.SeekStart.Notify

NetStream.Seek.Notify

NetStream.Unpause.Notify

NetStream.Unpause.Notify

NetStream.Play.Transition

NetStream.Play.TransitionComplete

NetStream.Buffer.Full

NetStream.Buffer.Flush

NetStream.Buffer.Empty

NetStreamInfo, NetStream,
XMP, .
HTTP-, NetStream.Play.Start,
NetStream.Play.Stop NetStream.Play.Complete ,
. HTTP.
, NetStream.Play.Transition NetStream.Play.TransitionComplete
, HTTP-.
RTMP-. ,
HTTP-, , .


Adobe Developer Connection: Flash

NetStream
: netStatus mediaTypeData.
,
NetStream.
netStatus , ,
. RTMFP-
netStatus.
mediaTypeData XMP-. Netstream.Play.Complete
mediaTypeData. , ,
, mediaTypeData.

23.11.2012.

ACTIONSCRIPT 3.0

, ,
NetStream . ,
, , .
package com.adobe.example
{
import flash.events.NetDataEvent;
import flash.events.NetMonitorEvent;
import flash.events.NetStatusEvent;
import flash.net.NetMonitor;
import flash.net.NetStream;
public class NetStreamEventMonitor
{
private var netmon:NetMonitor;
private var heartbeat:Timer = new Timer( 5000 );
public function NetStreamEventMonitor()
{
//Create NetMonitor object
netmon = new NetMonitor();
netmon.addEventListener( NetMonitorEvent.NET_STREAM_CREATE, newNetStream );
//Start the heartbeat timer
heartbeat.addEventListener( TimerEvent.TIMER, onHeartbeat );
heartbeat.start();
}
//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
{
var netStream:NetStream = event.target as NetStream;
trace( "Data event from " + netStream.info.uri + " at " + event.timestamp );
switch( event.info.handler )
{
case "onMetaData":
//handle metadata;
break;
case "onXMPData":
//handle XMP;
break;
case "onPlayStatus":
//handle NetStream.Play.Complete
case "onImageData":
//handle image
break;
case "onTextData":

23.11.2012.

539

ACTIONSCRIPT 3.0

//handle text
break;
default:
//handle other events
}
}
//On status events from a NetStream object
private function onStatus( event:NetStatusEvent ):void
{
trace( "Status event from " + event.target.info.uri + " at " + event.target.time );
//handle status events
}
//On heartbeat timer
private function onHeartbeat( event:TimerEvent ):void
{
var streams:Vector.<NetStream> = netmon.listStreams();
for( var i:int = 0; i < streams.length; i++ )
{
trace( "Heartbeat on " + streams[i].info.uri + " at " + streams[i].time );
//handle heartbeat event
}
}
}
}


URL- -, ,
. -, ,
ExternalInterface URL-. -,
, ExternalInterface.
- pageDomain Security. URL .
pageDomain Security:
var domain:String = Security.pageDomain;


Flash Player 9 , Adobe AIR 1.0
FLV-.

23.11.2012.

540

ACTIONSCRIPT 3.0

FLV-
Flash Player 9 , Adobe AIR 1.0
FLV-
FLV. MIME (Multipurpose Internet Mail Extensions, )
, ,
ASCII-. -
MIME-, , ,
. FLV- -,
MIME- -,
-. FLV- MIME- video/x-flv.
FLV- :

Mime-: video/x-flv
: .flv
:
:
: FLV- ;
/

:
: www.adobe.com/go/video_file_format_ru
Microsoft - Microsoft
Internet Information Services (IIS) 6.0 ( ). IIS
Flash. IIS 6.0, -
Windows 2003, MIME-, FLV-
.
SWF-, FLV-, Microsoft Windows
Server 2003 , SWF- , FLV-
. FLV-, Windows Server 2003,
Flash Macromedia Flash Video Kit
Dreamweaver MX 2004 Adobe.
.
Microsoft Windows 2003 Microsoft IIS Server 6.0 FLV
. www.adobe.com/go/tn_19439_ru.

FLV- Macintosh
Flash Player 9 , Adobe AIR 1.0
FLV- Apple Macintosh
(/), . ,
, -, , ,
.
. ,
Flash Player AIR.

23.11.2012.

541

ACTIONSCRIPT 3.0

FLV- Macintosh,
(:), (/).

: myDrive/myFolder/myFLV.flv
: (Mac OS) myDrive:myFolder:myFLV.flv

: Video Jukebox
Flash Player 9 , Adobe AIR 1.0
(Video Jukebox),
. ,
,
, .
ActionScript 3.0:

;
;
;
, , FLV-;
Video .

www.adobe.com/go/learn_programmingAS3samples_flash_ru. VideoJukebox
Samples/VideoJukebox. .
File

VideoJukebox.fla

Flex (MXML) Flash (FLA).

VideoJukebox.mxml
VideoJukebox.as

, .

playlist.xml

, , .


Flash Player 9 , Adobe AIR 1.0
playlist.xml ,
. XML- URLLoader URLRequest,
.
uldr = new URLLoader();
uldr.addEventListener(Event.COMPLETE, xmlCompleteHandler);
uldr.load(new URLRequest(PLAYLIST_XML_URL));

23.11.2012.

542

ACTIONSCRIPT 3.0

VideoJukebox,
. XML-
xmlCompleteHandler(), XML, .
private function xmlCompleteHandler(event:Event):void
{
playlist = XML(event.target.data);
videosXML = playlist.video;
main();
}

XML playlist XML ,


XML XMLList, .
playlist.xml .
<videos>
<video url="video/caption_video.flv" />
<video url="video/cuepoints.flv" />
<video url="video/water.flv" />
</videos>

, xmlCompleteHandler() main(),
, NetConnection NetStream,
FLV-.


Flash Player 9 , Adobe AIR 1.0
Button
, : playButton, pauseButton, stopButton, backButton
forwardButton.
Button click,
.
playButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);
pauseButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);
stopButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);
backButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);
forwardButton.addEventListener(MouseEvent.CLICK, buttonClickHandler);

buttonClickHandler() switch, , Button,


, .

23.11.2012.

543

ACTIONSCRIPT 3.0

private function buttonClickHandler(event:MouseEvent):void


{
switch (event.currentTarget)
{
case playButton:
ns.resume();
break;
case pauseButton:
ns.togglePause();
break;
case stopButton:
ns.pause();
ns.seek(0);
break;
case backButton:
playPreviousVideo();
break;
case forwardButton:
playNextVideo();
break;
}
}

Slider volumeSlider.
liveDragging Slider true
change.
volumeSlider.value = volumeTransform.volume;
volumeSlider.minimum = 0;
volumeSlider.maximum = 1;
volumeSlider.snapInterval = 0.1;
volumeSlider.tickInterval = volumeSlider.snapInterval;
volumeSlider.liveDragging = true;
volumeSlider.addEventListener(SliderEvent.CHANGE, volumeChangeHandler);

ProgressBar positionBar.
mode manual (), .
positionBar.mode = ProgressBarMode.MANUAL;

, Label positionLabel.
Label Timer.

Video
Flash Player 9 , Adobe AIR 1.0
Flash Player ,
onMetaData() client NetStream.
Object .
client = new Object();
client.onMetaData = metadataHandler;

23.11.2012.

544

ACTIONSCRIPT 3.0

metadataHandler() meta, .
.
Video , .
, ProgressBar positionBar
.
metadataHandler().
private function metadataHandler(metadataObj:Object):void
{
meta = metadataObj;
vid.width = meta.width;
vid.height = meta.height;
positionBar.move(vid.x, vid.y + vid.height);
positionBar.width = vid.width;
}


Flash Player 9 , Adobe AIR 1.0
NetConnection
NetStream. NetConnection null connect().
null, Flash Player , ,
Flash Media Server.
NetConnection NetStream,
netStatus Object client client.
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
ns.client = client;

netStatusHandler() , ,
, , .
netStatusHandler().

23.11.2012.

545

ACTIONSCRIPT 3.0

private function netStatusHandler(event:NetStatusEvent):void


{
try
{
switch (event.info.code)
{
case "NetStream.Play.Start":
t.start();
break;
case "NetStream.Play.StreamNotFound":
case "NetStream.Play.Stop":
t.stop();
playNextVideo();
break;
}
}
catch (error:TypeError)
{
// Ignore any errors.
}
}

code info NetStream.Play.Start,


NetStream.Play.StreamNotFound NetStream.Play.Stop.
, Timer, .
, Timer
.
Timer ProgressBar positionBar
, setProgress() ProgressBar, Label
positionLabel, .
private function timerHandler(event:TimerEvent):void
{
try
{
positionBar.setProgress(ns.time, meta.duration);
positionLabel.text = ns.time.toFixed(1) + " of " meta.duration.toFixed(1) + " seconds";
}
catch (error:Error)
{
// Ignore this error.
}
}


Flash Player 9 , Adobe AIR 1.0
soundTransform
NetStream. VideoJukebox
Slider volumeSlider.
Slider SoundTransform,
soundTransform NetStream.

23.11.2012.

546

ACTIONSCRIPT 3.0

private function volumeChangeHandler(event:SliderEvent):void


{
volumeTransform.volume = event.value;
ns.soundTransform = volumeTransform;
}


Flash Player 9 , Adobe AIR 1.0
,
.
URL- XMLList
.
private function getVideo():String
{
return videosXML[idx].@url;
}

playVideo() play() NetStream,


.
private function playVideo():void
{
var url:String = getVideo();
ns.play(url);
}

playPreviousVideo() , playVideo()
.
private function playPreviousVideo():void
{
if (idx > 0)
{
idx--;
playVideo();
positionBar.visible = true;
}
}

, playNextVideo(), playVideo().
, clear() Video,
visible ProgressBar false.

23.11.2012.

547

ACTIONSCRIPT 3.0

private function playNextVideo():void


{
if (idx < (videosXML.length() - 1))
{
idx++;
playVideo();
positionBar.visible = true;
}
else
{
idx++;
vid.clear();
positionBar.visible = false;
}
}

StageVideo

Flash Player 10.2 , Adobe AIR 2.5
Flash Player
H.264.
API StageVideo. StageVideo
.
, API- StageVideo:

Flash Player 10.2


Adobe AIR 2.5
Adobe AIR 2.5 Adobe Flash Player Beta Google TV
API-.
. .
Flash Platform .
. Flash Player 11.4 AIR 3.4
StageVideo.
.
.
StageVideo . .

23.11.2012.

548

ACTIONSCRIPT 3.0

StageVideo
, ,
, . ,
() ,
flash.media.StageVideo .
,
. ,
Video .
, .

.

.
StageVideo Video .
, ,
.
StageVideo Video
.
StageVideo . StageVideo
, .
, StageVideo Flash Player
. . 551.

: Flash
Flash Player .
Flash Player Z:
.

. ,
. ActionScript StageVideo
, .
Flash Flash ,

. ,
,
. ,
Video.
Flash.

23.11.2012.

549

ACTIONSCRIPT 3.0

ash
1
(

Fl

1

h
2
s

2
a
l

StageVideo .
.
Flash.
,
. ,
,
.

H.264
Flash Player :
1 H.264
2 API- StageVideo

. H.264
: .

.
.

.
, .

23.11.2012.

550

ACTIONSCRIPT 3.0


508


,
. Flash Player .
wmode.
, wmode="direct".
wmode , .
,
. ,
, . wmode
"direct", .
Flash Player
. API- StageVideo Video
, .
, .
:

SWF- Flash Player StageVideo


. ,
. AIR for TV
StageVideo.

,
.

.
, , .

.
BitmapData,
.

.
.
.
, ,
.

.
,
, 100 % .
- .

. ,
709 , H.264.
BT.601.

23.11.2012.

551

ACTIONSCRIPT 3.0

WMODE, , ,
, . WMODE=direct
, . WMODE Safari 4 , IE 9
, AIR for TV.
.
, .


179

API- StageVideo
,
.
. ,
.
,
, . ,
, StageVideo Stage.stageVideos.
Vector, StageVideo.
Video
StageVideo.
Flash Player ,
, Video. AIR 2.5
.
. StageVideo .

Stage.stageVideos
Stage.stageVideos Vector, StageVideo.
StageVideo,
. AIR for TV StageVideo.
.
, .
, ,
StageVideoAvailability, .

StageVideo
API- StageVideo :
StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY ( AIR 2.5 )

Stage.stageVideos. StageVideoAvailabilityEvent.availability
AVAILABLE UNAVAILABLE. , ,
stageVideos StageVideo, ,
Stage.stageVideos.
StageVideoEvent.RENDER_STATE , NetStream Camera

StageVideo . : ,

23.11.2012.

552

ACTIONSCRIPT 3.0

( ). videoWidth
videoHeight, .
. , StageVideo,
, .
VideoEvent.RENDER_STATE ( AIR 2.5 ) ,
Video. : .
, StageVideo,
. videoWidth videoHeight,
.

StageVideo
StageVideo .
1 StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, ,

Stage.stageVideos . .
StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY 554. ( AIR
2.5 .)
2 StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY

, Vector Stage.stageVideos
StageVideo. AIR 2.5 Stage.stageVideos
SWF.
3 NetStream StageVideo.attachNetStream()

Camera StageVideo.attachCamera().
4 NetStream.play ().
5 StageVideoEvent.RENDER_STATE StageVideo,

. ,
. .
StageVideoEvent.RENDER_STATE VideoEvent.RENDER_STATE 556.
6 VideoEvent.RENDER_STATE Video.

, StageVideoEvent.RENDER_STATE. ,
.
, .
( AIR 2.5 .) .
StageVideoEvent.RENDER_STATE VideoEvent.RENDER_STATE 556.

StageVideo
StageVideoAvailabilityEvent VideoEvent
. ,
flash.events.Event.ADDED_TO_STAGE. ,
:

23.11.2012.

553

ACTIONSCRIPT 3.0

public class SimpleStageVideo extends Sprite


private var nc:NetConnection;
private var ns:NetStream;
public function SimpleStageVideo()
{
// Constructor for SimpleStageVideo class
// Make sure the app is visible and stage available
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(event:Event):void
{
//...
// Connections
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
ns.client = this;
// Screen
video = new Video();
video.smoothing = true;
// Video Events
// the StageVideoEvent.STAGE_VIDEO_STATE informs you whether
// StageVideo is available
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY,
onStageVideoState);
// in case of fallback to Video, listen to the VideoEvent.RENDER_STATE
// event to handle resize properly and know about the acceleration mode running
video.addEventListener(VideoEvent.RENDER_STATE, videoStateChange);
//...
}

StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY
StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY , , Video
StageVideo, StageVideo.
StageVideoAvailabilityEvent.availability StageVideoAvailability.AVAILABLE,
StageVideo. , Stage.stageVideos
StageVideo. StageVideo Stage.stageVideos
NetStream. StageVideo ,
Video ( ).
StageVideoEvent.RENDER_STATE.
StageVideoAvailabilityEvent.availability
StageVideoAvailability.UNAVAILABLE, StageVideo
Stage.stageVideos. NetStream Video.

StageVideo Video NetStream.play().


,
StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY.

23.11.2012.

554

ACTIONSCRIPT 3.0

private var sv:StageVideo;


private var video:Video;
private function onStageVideoState(event:StageVideoAvailabilityEvent):void
{
// Detect if StageVideo is available and decide what to do in toggleStageVideo
toggleStageVideo(event.availability == StageVideoAvailability.AVAILABLE);
}
private function toggleStageVideo(on:Boolean):void
{
// To choose StageVideo attach the NetStream to StageVideo
if (on)
{
stageVideoInUse = true;
if ( sv == null )
{
sv = stage.stageVideos[0];
sv.addEventListener(StageVideoEvent.RENDER_STATE, stageVideoStateChange);
sv.attachNetStream(ns);
}
if (classicVideoInUse)
{
// If you use StageVideo, remove from the display list the
// Video object to avoid covering the StageVideo object
// (which is always in the background)
stage.removeChild ( video );
classicVideoInUse = false;
}
} else
{
// Otherwise attach it to a Video object
if (stageVideoInUse)
stageVideoInUse = false;
classicVideoInUse = true;
video.attachNetStream(ns);
stage.addChildAt(video, 0);
}
if ( !played )
{
played = true;
ns.play(FILE_NAME);
}
}

. Stage.stageVideos[0]
rect 0,0,0,0, pan zoom
. . videoWidth
videoHeight StageVideoEvent.RENDER_STATE VideoEvent.RENDER_STATE
.
Stage
Video.

23.11.2012.

555

556

ACTIONSCRIPT 3.0

StageVideoEvent.RENDER_STATE VideoEvent.RENDER_STATE
StageVideo Video ,
. StageVideoEvent.RENDER_STATE VideoEvent.RENDER_STATE.
StageVideo Video ,
NetStream .
, . ,
videoHeight videoWidth
.
:

RENDER_STATUS_UNAVAILABLE

RENDER_STATUS_SOFTWARE

RENDER_STATUS_ACCELERATED

,
( ). StageVideoEvent.status
. unavailable,
StageVideo . ,
NetStream Video.
.
StageVideoEvent
VideoEvent Flash Player.
VideoStatus.ACCELERATED

VideoStatus.SOFTWARE

VideoStatus.UNAVAILABLE

StageVideoEvent

.
(
.)


,

.
(
.)



,
.
Video.

VideoEvent


.
(
.

.)

(/)


,

. (


.

.)

. AIR 2.5 VideoStatus H.264 .


AIR 2.5 TV . StageVideoEvent
ActionScript 3.

23.11.2012.

ACTIONSCRIPT 3.0



. SWF-
.
. ,
.
, Flash Player
.
, ,
StageVideo.colorSpaces.
String:
var colorSpace:Vector.<String> = stageVideo.colorSpaces();

, ,
StageVideoEvent.colorSpace.
StageVideoEvent.RENDER_STATE:
var currColorSpace:String;
//StageVideoEvent.RENDER_STATE event handler
private function stageVideoRenderState(event:Object):void
{
//...
currColorSpace = (event as StageVideoEvent).colorSpace;
//...
}

Flash Player ,
BT.601. , H.264
BT.709. BT.709 , colorSpace
"BT601". StageVideoEvent.colorSpace "unknown", ,
.
. AIR 2.5 StageVideo
. StageVideoEvent.colorSpace BT709,
, BT601, .
,
StageVideo Video. Video
.

23.11.2012.

557

558

26.
Flash Player 9 , Adobe AIR 1.0
ActionScript
, . Camera
, ActionScript .
CameraUI. CameraUI
,
.
MediaPromise.


(Christian Cantrell): CameraUI
(Michal CHAIZE): Android, AIR

Camera
Flash Player 9 , Adobe AIR 1.0
Camera (
) ( Flash Media Server).
Camera :

, ,
;
Flash Player ;
;
.
Camera . ,
Camera.names ,
.
name.
. .
, .

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
NetConnection NetStream. Camera ,
Flash Player , ,
.
, Camera
.
var cam:Camera = Camera.getCamera();
var vid:Video = new Video();
vid.attachCamera(cam);
addChild(vid);

. Camera . Camera
Camera.getCamera().


Flash Player 9 , Adobe AIR 1.0
, , .

, . ,
.

Flash Player: , .
, Flash Player,
.
Flash Player ,
. ,
. ,
. .

AIR , Camera ,
.

Camera .
Camera AIR ,
.


(Christophe Coenraets):
(Mark Doherty): Android Radar ()

23.11.2012.

559

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, -, Camera,
Camera , Camera.getCamera().
-, Video Camera.
-, Video . 2 3
, Camera DisplayObject
. , ,
Video, attachCamera().
.
var cam:Camera = Camera.getCamera();
var vid:Video = new Video();
vid.attachCamera(cam);
addChild(vid);

, ,
.
.
. 560
561.


(Lee Brimelow): Android


Flash Player 9 , Adobe AIR 1.0
Camera, ,
. .

Camera.names, .
, ,
. Camera.names, ,
.
if (Camera.names.length > 0)
{
trace("User has at least one camera installed.");
var cam:Camera = Camera.getCamera(); // Get default camera.
}
else
{
trace("User has no cameras installed.");
}

23.11.2012.

560

ACTIONSCRIPT 3.0

, Camera.getCamera().
, null,
Camera. Camera.getCamera(), ,
.
var cam:Camera = Camera.getCamera();
if (cam == null)
{
trace("User has no cameras installed.");
}
else
{
trace("User has at least 1 camera installed.");
}

Camera DisplayObject,
addChild(). , ,
Video attachCamera().
, ; .
var cam:Camera = Camera.getCamera();
if (cam != null)
{
var vid:Video = new Video();
vid.attachCamera(cam);
addChild(vid);
}


Camera Flash Player .
AIR
. ,
. (
.)
iOS, Android .


Flash Player 9 , Adobe AIR 1.0
AIR
. Android
Android CAMERA .
Flash Player ,
. attachCamera(), Flash Player
Flash Player, Flash
Player . , Flash Player
Video .
, Flash Player , Video .

23.11.2012.

561

ACTIONSCRIPT 3.0

, Flash Player,
status (StatusEvent.STATUS), .
var cam:Camera = Camera.getCamera();
if (cam != null)
{
cam.addEventListener(StatusEvent.STATUS, statusHandler);
var vid:Video = new Video();
vid.attachCamera(cam);
addChild(vid);
}
function statusHandler(event:StatusEvent):void
{
// This event gets dispatched when the user clicks the "Allow" or "Deny"
// button in the Flash Player Settings dialog box.
trace(event.code); // "Camera.Muted" or "Camera.Unmuted"
}

statusHandler() ,
. , , :

event statusHandler() code Camera.Muted


Camera.Unmuted. Camera.Muted,
Flash Player .
.
function statusHandler(event:StatusEvent):void
{
switch (event.code)
{
case "Camera.Muted":
trace("User clicked Deny.");
break;
case "Camera.Unmuted":
trace("User clicked Accept.");
break;
}
}

Camera muted, ,
(true) (false) Flash Player.
.
function statusHandler(event:StatusEvent):void
{
if (cam.muted)
{
trace("User clicked Deny.");
}
else
{
trace("User clicked Accept.");
}
}

23.11.2012.

562

ACTIONSCRIPT 3.0

status,
, . ,
, ,
, Video , .
AIR Camera status,
.

Flash Player 9 , Adobe AIR 1.0


Video 320 240 .
, , Video
, Camera. Camera
width height, width height
Video ,
Video, .
var cam:Camera = Camera.getCamera();
if (cam != null)
{
var vid:Video = new Video(cam.width, cam.height);
vid.attachCamera(cam);
addChild(vid);
}

getCamera() Camera ( null,


), , .
Video .

23.11.2012.

563

ACTIONSCRIPT 3.0

var vid:Video;
var cam:Camera = Camera.getCamera();
if (cam == null)
{
trace("Unable to locate available cameras.");
}
else
{
trace("Found camera: " + cam.name);
cam.addEventListener(StatusEvent.STATUS, statusHandler);
vid = new Video();
vid.attachCamera(cam);
}
function statusHandler(event:StatusEvent):void
{
if (cam.muted)
{
trace("Unable to connect to active camera.");
}
else
{
// Resize Video object to match camera settings and
// add the video to the display list.
vid.width = cam.width;
vid.height = cam.height;
addChild(vid);
}
// Remove the status event listener.
cam.removeEventListener(StatusEvent.STATUS, statusHandler);
}

.
177.


Flash Player 9 , Adobe AIR 1.0
Camera ,
Camera. , Camera
Timer TextField .

23.11.2012.

564

ACTIONSCRIPT 3.0

var vid:Video;
var cam:Camera = Camera.getCamera();
var tf:TextField = new TextField();
tf.x = 300;
tf.autoSize = TextFieldAutoSize.LEFT;
addChild(tf);
if (cam != null)
{
cam.addEventListener(StatusEvent.STATUS, statusHandler);
vid = new Video();
vid.attachCamera(cam);
}
function statusHandler(event:StatusEvent):void
{
if (!cam.muted)
{
vid.width = cam.width;
vid.height = cam.height;
addChild(vid);
t.start();
}
cam.removeEventListener(StatusEvent.STATUS, statusHandler);
}
var t:Timer = new Timer(100);
t.addEventListener(TimerEvent.TIMER, timerHandler);
function timerHandler(event:TimerEvent):void
{
tf.text = "";
tf.appendText("activityLevel: " + cam.activityLevel + "\n");
tf.appendText("bandwidth: " + cam.bandwidth + "\n");
tf.appendText("currentFPS: " + cam.currentFPS + "\n");
tf.appendText("fps: " + cam.fps + "\n");
tf.appendText("keyFrameInterval: " + cam.keyFrameInterval + "\n");
tf.appendText("loopback: " + cam.loopback + "\n");
tf.appendText("motionLevel: " + cam.motionLevel + "\n");
tf.appendText("motionTimeout: " + cam.motionTimeout + "\n");
tf.appendText("quality: " + cam.quality + "\n");
}

(100 ) Timer timer,


timerHandler() .

23.11.2012.

565

566

27.
(DRM)
Flash Player 10.1 , Adobe AIR 1.5
Adobe Access .
,
. Adobe Access
, . Adobe Flash Player Adobe AIR
DRM Adobe Access.
Adobe Access .
, , Adobe Access
Flash Media Server.
Adobe Access ,
. , .
.
.

. AIR.

AIR - .
AIR
.
, ( 3.0).
Adobe Access ,
. ,
.
.
, .
Flash Player
Adobe AIR, API- DRM. API- DRM
.
Adobe Access .
.
.
, , Adobe
Access. Adobe
Access. ,
Adobe Access. ,
, , Adobe Access.
Adobe Access, , . ,
Adobe Access.

23.11.2012.

ACTIONSCRIPT 3.0
(DRM)


flash.net.drm
flash.net.NetConnection
flash.net.NetStream

Flash Player 10.1 , Adobe AIR 2.0


. Flash Player 11.5 Adobe Access,
( SystemUpdater.update(SystemUpdaterType.DRM)) .
:

Flash Player 11.5 ActiveX , Internet Explorer Windows 8


Intel

Flash Player 11.5 ;


Adobe AIR ( ).
, :

Internet Explorer Windows 8; Intel


Flash Player 11.4 , Google Chrome 22
( ) 21 ( Windows).
. SystemUpdater.update(SystemUpdaterType.DRM) Flash Player 11.5
, .
,
. ,
, Adobe Access:
1 .
2 Flash Player.
3 , . , 7. ,

4.
4 , . , 7.
5 ,

.
6 , ( AIR 3.0 ).
7 .
8 .

23.11.2012.

567

ACTIONSCRIPT 3.0
(DRM)

,
NetStream DRMStatusEvent. .
DRMStatusEvent ,
. , ,
, .
. ,
, .
,
. ,
. detail "DRM.voucherObtained".
, , .
DRMManager.
. AIR, Flash
Player. AIR.
. ,
, , , .
, , , ,
. ,
, .
.
.

API-
Flash Player 10.1 , AIR 2.0

. API-,
, Adobe Access.
1 URLLoader .

, metadata_bytes.
, Adobe Access, Adobe Access.

(.metadata) . . Adobe Access.
2 DRMContentData. try-catch:
new DRMContentData(metadata_bytes)

metadata_bytes URLLoader, 1.
3 ( Flash Player) Adobe Access.

, IllegalOperationError, DRMErrorEvent
3344 DRMErrorEvent 3343.
Adobe Access API- SystemUpdater.
SystemUpdater COMPLETE.
, 2 .
:

23.11.2012.

568

ACTIONSCRIPT 3.0
(DRM)

flash.system.SystemUpdater.addEventListener(Event.COMPLETE, updateCompleteHandler);
flash.system.SystemUpdater.update(flash.system.SystemUpdaterType.DRM)
private function updateCompleteHandler (event:Event):void {
/*redo step 2*/
drmContentData = new DRMContentData(metadata_bytes);
}

, .
.
584.
. AIR AIR Adobe Access
.
4 DRMStatusEvent DRMErrorEvent,

DRMManager:
DRMManager.addEventListener(DRMStatusEvent.DRM_STATUS, onDRMStatus);
DRMManager.addEventListener(DRMErrorEvent.DRM_ERROR, onDRMError);

DRMStatusEvent , ( ).
DRMErrorEvent DRMErrorEvent. .
DRMStatusEvent 576 DRMErrorEvent 581.
5 (), .

:
DRMManager.loadvoucher(drmContentData, LoadVoucherSetting.LOCAL_ONLY)

DRMManager DRMStatusEvent.DRM_Status.
6 DRMVoucher , . 13.
7 DRMVoucher , ,

. DRMContentData.authenticationMethod.
8 ANONYMOUS, 13.
9 USERNAME_AND_PASSWORD,

, .
:
DRMManager.authenticate(metadata.serverURL, metadata.domain, username, password)

DRMManager DRMAuthenticationErrorEvent,
, DRMAuthenticationCompleteEvent,
. .
10 UNKNOWN,

.
API- ActionScript 3.0.
,
DRMManager.setAuthenticationToken().
11 ,

9. ,
. ,
.

23.11.2012.

569

ACTIONSCRIPT 3.0
(DRM)

12 ,

DRMManager.setAuthenticationToken().
, 8.
13 () , ,

, .
DRMAuthenticationCompleteEvent.token.
,
. ,
.
14 :
DRMManager.loadvoucher(drmContentData, LoadVoucherSetting.FORCE_REFRESH)

DRMManager DRMStatusEvent.DRM_STATUS.
, .
15 . NetStream play():
stream = new NetStream(connection);
stream.addEventListener(DRMStatusEvent.DRM _STATUS, drmStatusHandler);
stream.addEventListener(DRMErrorEvent.DRM_ERROR, drmErrorHandler);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.client = new CustomClient();
video.attachNetStream(stream);
stream.play(videoURL);

DRMContentData
DRMContentData, , Flash
Player DRM. API- DRMManager, DRMContentData
DRM. API- DRMManager,
DRMContentData. .
1 authenticate()
2 setAuthenticationToken()

DRMContentData, API- DRMManager


DRM . ,
DRM DRM.
.
1 DRMContentData contentData1, DRM

AdobeCP1.
2 DRMManager.authenticate(contentData1.serverURL,...).
3 DRMManager.loadVoucher(contentData1, ...).

DRM , 2,
DRMManager.authenticate() DRM

AdobeCP2. loadVoucher() 3 , -
DRM AdobeCP1. ,
DRM. , DRM
.

23.11.2012.

570

ACTIONSCRIPT 3.0
(DRM)

, DRM
,
:

DRMDeviceGroupErrorEvent ( AIR), DRMManager


DRMAuthenticateEvent ( AIR), NetStream
DRMAuthenticationCompleteEvent, DRMManager
DRMAuthenticationErrorEvent, DRMManager
DRMErrorEvent, NetStream DRMManager
DRMStatusEvent, NetStream DRMManager
StatusEvent
NetStatusEvent. . 584.
, Adobe Access,
DRM.


Adobe AIR 1.5
(), ,
Adobe Access.
. (
.)
preloadEmbeddedMetadata() NetStream DRMManager. AIR
2.0
DRMContentData. ,
DRMContentData . ( preloadEmbeddedData()
DRMContentData .)

DRMContentData
Adobe AIR 2.0

DRMContentData.
1 .

Java Adobe Access .metadata.


, , URLLoader.
2 DRMContentData, :
var drmData:DRMContentData = new DRMContentData( metadata );

3 ,

567.

23.11.2012.

571

ACTIONSCRIPT 3.0
(DRM)

preloadEmbeddedMetadata()
Adobe AIR 1.5
DRM-
preloadEmbeddedMetadata().
1 . ( DRM

.)
2 NetConnection NetStream,
onDRMContentData() onPlayStatus() NetStream.

3 NetStreamPlayOptions stream URL

.
4 preloadEmbeddedMetadata() NetStream, NetStreamPlayOptions,

.
5 DRM, onDRMContentData().

DRMContentData.
6 DRMContentData loadVoucher()

DRMManager.
authenticationMethod DRMContentData
flash.net.drm.AuthenticationMethod.USERNAME_AND_PASSWORD,
.
serverURL domain DRMContentData authenticate()
DRMManager .
7 onPlayStatus() , .
onDRMContentData() , ,

. , , , Adobe Access.
AIR
:
package
{
import flash.display.Sprite;
import flash.events.DRMAuthenticationCompleteEvent;
import flash.events.DRMAuthenticationErrorEvent;
import flash.events.DRMErrorEvent;
import flash.ev ents.DRMStatusEvent;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.NetStreamPlayOptions;
import flash.net.drm.AuthenticationMethod;
import flash.net.drm.DRMContentData;
import flash.net.drm.DRMManager;
import flash.net.drm.LoadVoucherSetting;
public class DRMPreloader extends Sprite
{
private var videoURL:String = "app-storage:/video.flv";
private var userName:String = "user";
private var password:String = "password";
private var preloadConnection:NetConnection;

23.11.2012.

572

ACTIONSCRIPT 3.0
(DRM)

private var preloadStream:NetStream;


private var drmManager:DRMManager = DRMManager.getDRMManager();
private var drmContentData:DRMContentData;
public function DRMPreloader():void {
drmManager.addEventListener(
DRMAuthenticationCompleteEvent.AUTHENTICATION_COMPLETE,
onAuthenticationComplete);
drmManager.addEventListener(DRMAuthenticationErrorEvent.AUTHENTICATION_ERROR,
onAuthenticationError);
drmManager.addEventListener(DRMStatusEvent.DRM_STATUS, onDRMStatus);
drmManager.addEventListener(DRMErrorEvent.DRM_ERROR, onDRMError);
preloadConnection = new NetConnection();
preloadConnection.addEventListener(NetStatusEvent.NET_STATUS, onConnect);
preloadConnection.connect(null);
}
private function onConnect( event:NetStatusEvent ):void
{
preloadMetadata();
}
private function preloadMetadata():void
{
preloadStream = new NetStream( preloadConnection );
preloadStream.client = this;
var options:NetStreamPlayOptions = new NetStreamPlayOptions();
options.streamName = videoURL;
preloadStream.preloadEmbeddedData( options );
}
public function onDRMContentData( drmMetadata:DRMContentData ):void
{
drmContentData = drmMetadata;
if ( drmMetadata.authenticationMethod == AuthenticationMethod.USERNAME_AND_PASSWORD )
{
authenticateUser();
}
else
{
getVoucher();
}
}
private function getVoucher():void
{
drmManager.loadVoucher( drmContentData, LoadVoucherSetting.ALLOW_SERVER );
}
private function authenticateUser():void
{
drmManager.authenticate( drmContentData.serverURL, drmContentData.domain, userName,
password );
}
private function onAuthenticationError( event:DRMAuthenticationErrorEvent ):void
{
trace( "Authentication error: " + event.errorID + ", " + event.subErrorID );
}
private function onAuthenticationComplete( event:DRMAuthenticationCompleteEvent ):void
{

23.11.2012.

573

ACTIONSCRIPT 3.0
(DRM)

trace( "Authenticated to: " + event.serverURL + ", domain: " + event.domain );


getVoucher();
}
private function onDRMStatus( event:DRMStatusEvent ):void
{
trace( "DRM Status: " + event.detail);
trace("--Voucher allows offline playback = " + event.isAvailableOffline );
trace("--Voucher already cached
= " + event.isLocal );
trace("--Voucher required authentication = " + !event.isAnonymous );
}
private function onDRMError( event:DRMErrorEvent ):void
{
trace( "DRM error event: " + event.errorID + ", " + event.subErrorID + ", " + event.text );
}
public function onPlayStatus( info:Object ):void
{
preloadStream.close();
}
}
}

DRM
NetStream
Flash Player 10.1 , Adobe AIR 1.0
NetStream
Flash Player AIR Flash Media . (
NetStream .) NetStream
NetConnection. NetStream DRM :

drmAuthenticate

DRMAuthenticateEvent. , NetStream
,
.

( AIR)

header, usernamePrompt, passwordPrompt urlPrompt


. ,
NetStream .

23.11.2012.

574

ACTIONSCRIPT 3.0
(DRM)

drmError

DRMErrorEvent , NetStream
DRM . , DRM
.
, .
.

drmStatus

DRMStatusEvent. ,
(
). DRMStatusEvent ,
. ,
,
.

status

events.StatusEvent ,
NetStream.play(). - status
DRM.encryptedFLV.

NetStream DRM , AIR:

resetDRMVouchers()

DRM.
,
.
, :
NetStream.resetDRMVouchers();

setDRMAuthenticationCredentials()

, ,
, NetStream
. "drm" "proxy".
"drm"
Adobe Access. proxy
-;
, -. ,
, , . proxy
. ,
-
Adobe Access,
.
setDRMAuthenticationCredentials() "drm"
Adobe Access.

preloadEmbeddedMetadata()

.
DRM , AIR
onDRMContentData().

, AIR NetStream onDRMContentData()


onPlayStatus() preloadEmbeddedMetaData().
onDRMContentData() , DRM.
onPlayStatus() .
onDRMContentData() onPlayStatus() client,
NetStream.
NetStream, onPlayStatus(),
preloadEmbeddedMetaData(), .

23.11.2012.

575

ACTIONSCRIPT 3.0
(DRM)

AIR
(administrator), (password) drm.
setDRMAuthenticationCredentials() ,
, .
, .
.
var connection:NetConnection = new NetConnection();
connection.connect(null);
var videoStream:NetStream = new NetStream(connection);
videoStream.addEventListener(DRMAuthenticateEvent.DRM_AUTHENTICATE,
drmAuthenticateEventHandler)
private function drmAuthenticateEventHandler(event:DRMAuthenticateEvent):void
{
videoStream.setDRMAuthenticationCredentials("administrator", "password", "drm");
}

DRMStatusEvent
Flash Player 10.1, Adobe AIR 1.0
NetStream DRMStatusEvent,
, Adobe Access. ( ,
).
DRMStatusEvent , .
, ,
, .
. ,
.
DRMStatusEvent , .
, ,
.
.

DRMStatusEvent
Flash Player 10.1, Adobe AIR 1.0
DRMStatusEvent . AIR,
1.0. . ActionScript 3.0
Adobe Flash Professional CS5.
, Flash Player 10.1, DRMVoucher
Flash Player.

23.11.2012.

576

ACTIONSCRIPT 3.0
(DRM)

contentData

DRMContentData DRM, .

detail ( AIR)

, status. DRM 1.0


DRM.voucherObtained.

isAnonymous (
AIR)

, , Adobe Access,
(true) (false). false ,
, ,
.

isAvailableOffline (
AIR)

, , Adobe Access, .
, true, false.
, .

isLocal

, , , .

offlineLeasePeriod ( , .
AIR)
policies ( AIR)

, DRM.

voucher

DRM.

voucherEndDate (
AIR)

, .

DRMStatusEvent
Flash Player 10.1, Adobe AIR 1.0
, , DRM
NetStream, . NetStream,
.
function drmStatusEventHandler(event:DRMStatusEvent):void
{
trace(event);
}
function drmStatusEventHandler(event:DRMStatusEvent):void
{
trace(event);
}

DRMAuthenticateEvent
Adobe AIR 1.0
DRMAuthenticateEvent , NetStream
, .

23.11.2012.

577

ACTIONSCRIPT 3.0
(DRM)

DRMAuthenticateEvent ( , , )
NetStream.setDRMAuthenticationCredentials() .
AIR . ,

.
.

DRMAuthenticateEvent
Adobe AIR 1.0
DRMAuthenticateEvent :

authenticationType

, :
Adobe Access (drm) - (proxy). , proxy
-,
. ,
-
Adobe Access, .
setDRMAuthenticationCredentials() "drm"
Adobe Access.

header

, .
.
Flash,
.
. ,
.

netstream

NetStream, .

passwordPrompt

, .
.

urlPrompt

URL, . ,
.

usernamePrompt

, .
. ,
.

FMRMS. Adobe Access Server


.

DRMAuthenticateEvent
Adobe AIR 1.0
,
NetStream, . (
.)

23.11.2012.

578

ACTIONSCRIPT 3.0
(DRM)

var connection:NetConnection = new NetConnection();


connection.connect(null);
var videoStream:NetStream = new NetStream(connection);
videoStream.addEventListener(DRMAuthenticateEvent.DRM_AUTHENTICATE,
drmAuthenticateEventHandler)
private function drmAuthenticateEventHandler(event:DRMAuthenticateEvent):void
{
videoStream.setDRMAuthenticationCredentials("administrator", "password", "drm");
}


Adobe AIR 1.0
, , AIR
.
Flex.
panel TextInput: .
, credentials().
<mx:Panel x="236.5" y="113" width="325" height="204" layout="absolute" title="Login">
<mx:TextInput x="110" y="46" id="uName"/>
<mx:TextInput x="110" y="76" id="pWord" displayAsPassword="true"/>
<mx:Text x="35" y="48" text="Username:"/>
<mx:Text x="35" y="78" text="Password:"/>
<mx:Button x="120" y="115" label="Login" click="credentials()"/>
</mx:Panel>

credentials() ,
setDRMAuthenticationCredentials(). credentials()
TextInput.
<mx:Script>
<![CDATA[
public function credentials():void
{
videoStream.setDRMAuthenticationCredentials(uName, pWord, "drm");
uName.text = "";
pWord.text = "";
}
]]>
</mx:Script>

.
DRMAuthenticateEvent.
VideoDisplay source, FLV-.
credentials() , .
TextInput.

23.11.2012.

579

ACTIONSCRIPT 3.0
(DRM)

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
width="800"
height="500"
title="DRM FLV Player"
creationComplete="initApp()" >
<mx:states>
<mx:State name="LOGIN">
<mx:AddChild position="lastChild">
<mx:Panel x="236.5" y="113" width="325" height="204" layout="absolute"
title="Login">
<mx:TextInput x="110" y="46" id="uName"/>
<mx:TextInput x="110" y="76" id="pWord" displayAsPassword="true"/>
<mx:Text x="35" y="48" text="Username:"/>
<mx:Text x="35" y="78" text="Password:"/>
<mx:Button x="120" y="115" label="Login" click="credentials()"/>
<mx:Button x="193" y="115" label="Reset" click="uName.text='';
pWord.text='';"/>
</mx:Panel>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Script>
<![CDATA[
import flash.events.DRMAuthenticateEvent;
private function initApp():void
{
videoStream.addEventListener(DRMAuthenticateEvent.DRM_AUTHENTICATE,
drmAuthenticateEventHandler);
}
public function credentials():void
{
videoStream.setDRMAuthenticationCredentials(uName, pWord, "drm");
uName.text = "";
pWord.text = "";
currentState='';
}
private function drmAuthenticateEventHandler(event:DRMAuthenticateEvent):void
{
currentState='LOGIN';
}
]]>
</mx:Script>
<mx:VideoDisplay id="video" x="50" y="25" width="700" height="350"
autoPlay="true"
bufferTime="10.0"
source="http://www.example.com/flv/Video.flv" />
</mx:WindowedApplication>

23.11.2012.

580

ACTIONSCRIPT 3.0
(DRM)

DRMErrorEvent
Flash Player 10.1 , Adobe AIR 1.0
Adobe Flash Player Adobe AIR DRMErrorEvent, NetStream,
, DRM .
AIR, DRMAuthenticateEvent ,

. DRM, ,
.
,
. , ,
. ,
.
DRMErrorEvent.
,
.
.

DRMErrorEvent
Flash Player 10.1 , Adobe AIR 1.0
. ActionScript 3.0
Adobe Flash Professional CS5. DRM 3300.

DRMErrorEvent
Flash Player 10.1 , Adobe AIR 1.0
, NetStream,
. , NetStream
. ,
.
.
private function drmErrorEventHandler(event:DRMErrorEvent):void
{
trace(event.toString());
}

DRMManager
Flash Player 10.1 , Adobe AIR 1.5
DRMManager
.

23.11.2012.

581

ACTIONSCRIPT 3.0
(DRM)

( AIR)
,
, .
,
AIR. ,
.
preloadEmbeddedMetadata() DRMManager NetStream .
, . ,
, ,
.
preloadEmbeddedMetadata() NetStream,
DRMContentData. DRMContentData URL
, ,
, .
loadVoucher() DRMManager, .

571.

DRMManager
.
authenticate() DRMManager,
. ,
DRMManager DRMAuthenticationComplete. .
,
.
setAuthenticationToken(), . (
, . AIR
,
AIR.)
. ,
AIR. .
763.

DRMStatus
Flash Player 10.1 , Adobe AIR 1.5
DRMManager DRMStatusEvent ,
loadVoucher().
, detail ( AIR)
DRM.voucherObtained, voucher DRMVoucher.
, detail ( AIR) -
DRM.voucherObtained, voucher null.
, , , LoadVoucherSetting localOnly
.

23.11.2012.

582

ACTIONSCRIPT 3.0
(DRM)

loadVoucher() (,
), DRMManager DRMErrorEvent
DRMAuthenticationErrorEvent.

DRMAuthenticationComplete
Flash Player 10.1 , Adobe AIR 1.5
DRMManager DRMAuthenticationCompleteEvent,
authenticate() .
DRMAuthenticationCompleteEvent ,
.
setAuthenticationToken() DRMManager, . (
, . Adobe API .)

DRMAuthenticationError
Flash Player 10.1 , Adobe AIR 1.5
DRMManager DRMAuthenticationErrorEvent,
authenticate() setAuthenticationToken().

DRMContentData
Flash Player 10.1 , Adobe AIR 1.5
DRMContentData , Adobe Access.
DRMContentData ,
. DRMContentData ,
, API-
568.
. DRMContentData c ActionScript 3.0
Adobe Flash Platform.

23.11.2012.

583

ACTIONSCRIPT 3.0
(DRM)

Flash Player
Adobe Access
Flash Player 10.1
. Flash Player 11.5 Adobe Access,
( SystemUpdater.update(SystemUpdaterType.DRM)) .
:

Flash Player 11.5 ActiveX control , Internet Explorer


Windows 8;

Flash Player 11.5 ;


Adobe AIR ( ).
, :

Internet Explorer Windows 8;


Flash Player 11.4 , Google Chrome 22
( ) 21 ( Windows).
. SystemUpdater.update(SystemUpdaterType.DRM) Flash Player 11.5
, .
Adobe Access Flash Player Adobe Access.
Flash Player , ,
Flash Player.
Flash Player SWF .
SWF
Adobe Access .
API- SystemUpdater,
Adobe Access Flash Player.
API- SystemUpdater .
2202 , .
, Flash Player Internet Explorer,
Flash Player Firefox .
API- SystemUpdater .
. Flash Player, 10.1, ,
(
www.adobe.com ExpressInstall). , AIR
Adobe Access API- SystemUpdater.


Flash Player 10.1
Adobe Access, NetStream NetStatusEvent
DRM.UpdateNeeded. , NetStream
-
Adobe Access. :

23.11.2012.

584

ACTIONSCRIPT 3.0
(DRM)

SystemUpdater.update(flash.system.SystemUpdaterType.DRM)

Adobe Access, .
.
Adobe Access , . . 3
API- 568.
. play() ,
10.1, NetStatusEvent
NetStream.Play.StreamNotFound. ,
( www.adobe.com
ExpressInstall).
, SystemUpdater StatusEvent
DRM.UpdateNeededButIncompatible.
. ,
. StatusEvent :
SystemUpdater.update(flash.system.SystemUpdaterType.SYSTEM);

.
SystemUpdater c ActionScript 3.0
Adobe Flash Platform.
,
. Adobe Access , .


Flash Player 11 , Adobe AIR 3.0
( Adobe Access).
() storeVoucher.
Flash Player AIR,
DRM . DRM
Adobe Access, .
Flash Player/AIR, , ,
Adobe Access, DRM ( DRMContentData). Flash/AIR
, DRMManager.loadVoucher().
Flash Player/AIR
, .
Flash/AIR Adobe Access.
DRMManager.storeVoucher() Flash/AIR DRM
Flash Player/AIR.
. DRM
Adobe Access,
. HTTP,
Adobe Access .

23.11.2012.

585

ACTIONSCRIPT 3.0
(DRM)

DRMManager.storeVoucher()
DRM . Adobe Access 3.0 .
,
DRMManager.addToDeviceGroup().
, , , AIR
DRM DRMVoucher.toByteArray(),
DRMManager.storeVoucher().


DRM . Flash/AIR
,
DRM. .
, :

Adobe Access Server SDK;


HTTP- ;
Flash .
.
1 Flash .
2 Flash DRMManager.authenticate().

. ,
.
3 , . 2, , Adobe Access

. .
a .
b ,

, .
4 .
5 Flash LSO (

).
Flash ,
.
1 Flash LSO.
2 , Flash

. Flash Adobe
Access DRMManager.storeVoucher().
3 , Flash

23.11.2012.

586

ACTIONSCRIPT 3.0
(DRM)


,
. , Flash
. Flash
, Adobe Access ,
.


Flash Player 11 , Adobe AIR 3.0
, , AIR
API- .
, .
, ,
.
DRMContentDataVoucherAccessInfo,
,
.



Adobe Access
.
1 VoucherAccessInfo.deviceGroup, , .
2
a DeviceGroupInfo.authenticationMethod, ,

.
b ,

.
DRMManager.authenticate(deviceGroup.serverURL, deviceGroup.domain, username,
password).

,
DRMManager.setAuthenticationToken().
c DRMManager.addToDeviceGroup().
3 , .
a DRMManager.loadVoucher().
b , .

DRMManager DRMManager.storeVoucher().

23.11.2012.

587

ACTIONSCRIPT 3.0
(DRM)

4 NetStream.play().

,
DRMVoucher.toByteArray()
Adobe Access. , ,
. ,
DRMManager.removeFromDeviceGroup() ,
.


Flash , ,
,
, , ,
.
( , ),
( ).
, , , ,
/DRM, DRM.
/ DRM
,
. ,
, .
. ,
.


Adobe Access , Flash Player
Adobe Access. ,
HTTP, HTTP Dynamic Streaming, RTMP RTMPE.
,
( .metadata), Adobe Access
. ,
RTMP/RTMPE Flash Media Server (FMS) FLV
F4V. .
, -
HTTP
.

23.11.2012.

588

ACTIONSCRIPT 3.0
(DRM)

private function getMetadata():void{


extrapolated-path-to-metadata = "http://metadatas.mywebserver.com/" + videoname;
var urlRequest : URLRequest = new URLRequest(extrapolated-path-to-the-metadata + ".metadata");
var urlStream : URLStream = new URLStream();
urlStream.addEventListener(Event.COMPLETE, handleMetadata);
urlStream.addEventListener(IOErrorEvent.NETWORK_ERROR, handleIOError);
urlStream.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
urlStream.addEventListener(IOErrorEvent.VERIFY_ERROR, handleIOError);
try{
urlStream.load(urlRequest);
}catch(se:SecurityError){
videoLog.text += se.toString() + "\n";
}catch(e:Error){
videoLog.text += e.toString() + "\n";
}
}

Open Source Media Framework


OSMF (Open Source Media Framework) ActionScript
.
OSMF . OSMF.


1 MediaPlayer.
player = new MediaPlayer();

2 MediaPlayerCapabilityChangeEvent.HAS_DRM_CHANGE .

, DRM.
player.addEventListener(MediaPlayerCapabilityChangeEvent.HAS_DRM_CHANGE,
onDRMCapabilityChange);

3 DRMTrait. DRMTrait ,

, DRM, authenticate(). ,
DRM OSMF DRM
. DRMEvent.DRM_STATE_CHANGE DRMTrait.
private function onDRMCapabilityChange
(event :MediaPlayerCapabilityChangeEvent) :void
{
if (event.type == MediaPlayerCapabilityChangeEvent.HAS_DRM_CHANGE
&& event.enabled)
{
drmTrait = player.media.getTrait(MediaTraitType.DRM) as DRMTrait;
drmTrait.addEventListener
(DRMEvent.DRM_STATE_CHANGE, onDRMStateChange);
}
}

4 DRM onDRMStateChange().

23.11.2012.

589

ACTIONSCRIPT 3.0
(DRM)

private function onDRMStateChange(event :DRMEvent) :void


{
trace ( "DRMState: ",event.drmState);
switch(event.drmState)
{
case DRMState.AUTHENTICATION_NEEDED:
// Identity-based content
var authPopup :AuthWindow = AuthWindow.create(_parentWin);
authPopup.serverURL = event.serverURL;
authPopup.addEventListener("dismiss", function () :void {
trace ("Authentication dismissed");
if(_drmTrait != null)
{
//Ignore authentication. Just
//try to acquire a license.
_drmTrait.authenticate(null, null);
}
});
authPopup.addEventListener("authenticate",
function (event :AuthWindowEvent) :void {
if(_drmTrait != null)
{
_drmTrait.authenticate(event.username, event.password);
}
});
authPopup.show();
break;
case DRMState.AUTHENTICATING:
//Display any authentication message.
trace("Authenticating...");
break;
case DRMState.AUTHENTICATION_COMPLETE:
// Start to retrieve voucher and playback.
// You can display the voucher information at this point.
if(event.token)
// You just received the authentication token.
{
trace("Authentication success. Token: \n", event.token);
}
else
// You have got the voucher.
{
trace("DRM License:");
trace("Playback window period: ",
!isNaN(event.period) ? event.period == 0 ?
"<unlimited>" : event.period : "<none>");

23.11.2012.

590

ACTIONSCRIPT 3.0
(DRM)

trace("Playback window end date: ",


event.endDate != null ? event.endDate : "<none>");
trace("Playback window start date: ",
event.startDate != null ? event.startDate : "<none>");
}
break;
case DRMState.AUTHENTICATION_ERROR:
trace ("DRM Error:", event.mediaError.errorID +
"[" + DRMErrorEventRef.getDRMErrorMnemonic
(event.mediaError.errorID) + "]");
//Stop everything.
player.media = null;
break;
case DRMState.DRM_SYSTEM_UPDATING:
Logger.log("Downloading DRM module...");
break;
case DRMState.UNINITIALIZED:
break;
}
}

23.11.2012.

591

592

28. PDF-
AIR
Adobe AIR 1.0
Adobe AIR SWF- HTML-, PDF. AIR PDF HTMLLoader,
WebKit Adobe Reader . AIR PDF-
, - .
Adobe Reader PDF- AIR. ,
Reader (, ,
), PDF- AIR .
. PDF AIR Adobe Reader
Adobe Acrobat 8.1 .

PDF
Adobe AIR 1.0
Adobe Reader Adobe Acrobat 8.1 ,
PDF- AIR. ,
PDF, HTMLLoader.pdfCapability.
HTMLPDFCapability:

HTMLPDFCapability.STATUS_OK

(8.1 ) Adobe
Reader, PDF-
HTMLLoader.

HTMLPDFCapability.ERROR_INSTALLED_READER_NOT_FOUND

Adobe Reader . HTMLLoader


PDF-.

HTMLPDFCapability.ERROR_INSTALLED_READER_TOO_OLD

Adobe Reader , .
HTMLLoader PDF-.

HTMLPDFCapability.ERROR_PREFERRED_READER_TOO_OLD

(8.1 ) Adobe
Reader, Adobe Reader, PDF, , 8.1. HTMLLoader
PDF-.

23.11.2012.

ACTIONSCRIPT 3.0
PDF- AIR

Windows Adobe Acrobat Adobe Reader 7.x


, , ,
PDF. , pdfCapability HTMLPDFCapability.STATUS_OK, ,
AIR PDF, Acrobat Reader
( AIR ). ,
, Acrobat
. , , PDF-
.
AIR, Linux, Adobe Reader, (PATH),
( acroread), /opt/Adobe/Reader.
, PDF- AIR.
PDF, ,
HTMLPDFCapability.
if(HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK)
{
trace("PDF content can be displayed");
}
else
{
trace("PDF cannot be displayed. Error code:", HTMLLoader.pdfCapability);
}

PDF-
Adobe AIR 1.0
PDF AIR HTMLLoader,
PDF-.
, PDF . URLRequest
PDF-.
var request:URLRequest = new URLRequest("http://www.example.com/test.pdf");
pdf = new HTMLLoader();
pdf.height = 800;
pdf.width = 600;
pdf.load(request);
container.addChild(pdf);

URL- AIR URL, app app-storage. , , test.pdf PDFs


:
app:/js_api_reference.pdf
URL AIR . URI 873.

23.11.2012.

593

ACTIONSCRIPT 3.0
PDF- AIR

PDF
Adobe AIR 1.0
JavaScript PDF- , -
.
JavaScript Acrobat, , :




JavaScript Adobe Acrobat . Adobe Acrobat
http://www.adobe.com/devnet/acrobat/javascript.html.

HTML PDF
Adobe AIR 1.0
JavaScript HTML- JavaScript PDF-,
postMessage() DOM, PDF. , PDF:
<object id="PDFObj" data="test.pdf" type="application/pdf" width="100%" height="100%"/>

JavaScript HTML- JavaScript PDF-:


pdfObject = document.getElementById("PDFObj");
pdfObject.postMessage(["testMsg", "hello"]);

PDF- JavaScript. JavaScript


PDF-, , , , .
,
PDF- .
PDF- hostContainer messageHandler. messageHandler
, , . ,
, PDF- (. .
HTML-, PDF-):
this.hostContainer.messageHandler = {onMessage: myOnMessage};
function myOnMessage(aMessage)
{
if(aMessage[0] == "testMsg")
{
app.alert("Test message: " + aMessage[1]);
}
else
{
app.alert("Error");
}
}

23.11.2012.

594

ACTIONSCRIPT 3.0
PDF- AIR

JavaScript HTML- postMessage() PDF,


. ("Hello from HTML") JavaScript PDF-
:
<html>
<head>
<title>PDF Test</title>
<script>
function init()
{
pdfObject = document.getElementById("PDFObj");
try {
pdfObject.postMessage(["alert", "Hello from HTML"]);
}
catch (e)
{
alert( "Error: \n name = " + e.name + "\n message = " + e.message );
}
}
</script>
</head>
<body onload='init()'>
<object
id="PDFObj"
data="test.pdf"
type="application/pdf"
width="100%" height="100%"/>
</body>
</html>

Acrobat 8 JavaScript PDF- .


PDF- Adobe AIR.

PDF ActionScript
Adobe AIR 1.0
ActionScript ( SWF-) JavaScript PDF-.
ActionScript JavaScript HTML-, HTMLLoader,
PDF, JavaScript JavaScript PDF-.
. HTML JavaScript AIR 1053.

PDF AIR
Adobe AIR 1.0
PDF- Adobe AIR :

PDF- ( NativeWindow), (. .
transparent true).

23.11.2012.

595

ACTIONSCRIPT 3.0
PDF- AIR

PDF- , AIR.
PDF- , HTML,
AIR.

HTMLLoader, PDF, PDF- . : filters, alpha,


rotation scaling. PDF- ,
.
, HTMLLoader.

PDF- , scaleMode Stage


NativeWindow, PDF-,
StageScaleMode.NO_SCALE. - , PDF- .

PDF- PDF .
PDF- HTMLLoader, PDF,
( ).

PDF AIR.

23.11.2012.

596

597

29.

Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0
. ,
ActionScript 3.0. .
134.


Flash Player 9 , Adobe AIR 1.0
, ,
. ActionScript 3.0
.
InteractiveObject, DisplayObject,
, . InteractiveObject
. , SimpleButton, Sprite, TextField
Flash Flex,
. , ,
, InteractiveObject,
.

, ,
.
, ( ,

). , D d ,
.
,

.
, . ,

.
,

.
, .

23.11.2012.

ACTIONSCRIPT 3.0


InteractiveObject
Keyboard
Mouse
ContextMenu


Flash Player 9 , Adobe AIR 1.0

. , tabEnabled true,
. ,
tabEnabled = false, .

SimpleButton true.
true.
Sprite MovieClip buttonMode = true true.
FocusEvent.FOCUS_IN
FocusEvent.FOCUS_OUT, .

, ,
, InteractiveObject. ,
.
.
. Flash Professional ,
SWF-
AIR, Flash.
var
var
var
var
var
var
for
{

rows:uint = 10;
cols:uint = 10;
rowSpacing:uint = 25;
colSpacing:uint = 25;
i:uint;
j:uint;
(i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
{
createSquare(j * colSpacing, i * rowSpacing, (i * cols) + j);
}

}
function createSquare(startX:Number, startY:Number, tabNumber:uint):void
{
var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000);
square.graphics.drawRect(0, 0, colSpacing, rowSpacing);
square.graphics.endFill();

23.11.2012.

598

ACTIONSCRIPT 3.0

square.x = startX;
square.y = startY;
square.tabEnabled = true;
square.tabIndex = tabNumber;
square.addEventListener(FocusEvent.FOCUS_IN, changeColor);
addChild(square);
}
function changeColor(event:FocusEvent):void
{
event.target.transform.colorTransform = getRandomColor();
}
function getRandomColor():ColorTransform
{
// Generate random values for the red, green, and blue color channels.
var red:Number = (Math.random() * 512) - 255;
var green:Number = (Math.random() * 512) - 255;
var blue:Number = (Math.random() * 512) - 255;
// Create and return a ColorTransform object with the random colors.
return new ColorTransform(1, 1, 1, 1, red, green, blue, 0);
}


Flash Player 10.1 , Adobe AIR 2
Flash Player 10.1 Adobe AIR 2
. ActionScript
, ,
:

(
).

( ).
( , , ,
).
API- ActionScript :

flash.system.Capabilities.touchScreenType: ,
, .

flash.system.TouchScreenType:
Capabilities.touchScreenType.

flash.ui.Mouse.supportsCursor: ,
.

flash.ui.Keyboard.physicalKeyboardType: ,

.

23.11.2012.

599

600

ACTIONSCRIPT 3.0

flash.ui.KeyboardType:
flash.ui.Keyboard.physicalKeyboardType.

flash.ui.Keyboard.hasVirtualKeyboard: ,
(
).
API-
, . API
. , ,
,
, .
, createStylusUI(),
.
, createTouchUI(),
:
if(Capabilities.touchscreenType == TouchscreenType.STYLUS ){
//Construct the user interface using small buttons for a stylus
//and allow more screen space for other visual content
createStylusUI();
} else if(Capabilities.touchscreenType = TouchscreenType.FINGER){
//Construct the user interface using larger buttons
//to capture a larger point of contact with the device
createTouchUI();
}

supportsCursor

touchscreenType == FINGER

touchscreenType == STYLUS touchscreenType == NONE

true

false

false

23.11.2012.

true

601

ACTIONSCRIPT 3.0

supportsCursor

touchscreenType == FINGER

touchscreenType == STYLUS touchscreenType == NONE

false

(,
,

,
Apple iPhone Palm
Pre)

true

false

false


false

(,
,

,
HTC Fuze)

false

true

false



(
,

,
,

false

false

true

false

. .
.

23.11.2012.

602

30.
Flash Player 9 , Adobe AIR 1.0
,
IME, , ASCII,
. ,
ActionScript 3.0. .
134.
(, , ,
- 12- ) .
599.
(. Input Method Editor, IME)
. IME
.


flash.events.KeyboardEvent
flash.system.IME


Flash Player 9 , Adobe AIR 1.0
, InteractiveObject,
. . ,
.
, ,
:
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (character code: " +
event.charCode + ")");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);

, Ctrl, ,
.
.
.
, .
,
TextField. Shift TextField
.

23.11.2012.

ACTIONSCRIPT 3.0

TextField tf.
tf.border = true;
tf.type = "input";
tf.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
tf.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " + event.charCode + ")");
if (event.keyCode == Keyboard.SHIFT) tf.borderColor = 0xFF0000;
}
function reportKeyUp(event:KeyboardEvent):void
{
trace("Key Released: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " + event.charCode + ")");
if (event.keyCode == Keyboard.SHIFT)
{
tf.borderColor = 0x000000;
}
}

TextField textInput,
. . 408.
. AIR . Flash Player
.


Flash Player 9 , Adobe AIR 1.0
, ,
keyCode charCode . keyCode ,
. charCode
. ( UTF-8 ASCII.)
,
(1 1 , ,
1 !, ), (R
r ).
. ASCII .
flash.ui.Keyboard c ActionScript 3.0 Adobe Flash Platform.
.
.
Keyboard keyCode. ,
Shift, Keyboard.SHIFT (
).

23.11.2012.

603

ACTIONSCRIPT 3.0

KeyboardEvent
Flash Player 9 , Adobe AIR 1.0
,
, , addEventListener() .
, tf container
:
container.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
container.tf.border = true;
container.tf.type = "input";
container.tf.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
function reportKeyDown(event:KeyboardEvent):void
{
trace(event.currentTarget.name + " hears key press: " + String.fromCharCode(event.charCode)
+ " (key code: " + event.keyCode + " character code: " + event.charCode + ")");
}

, ,
reportKeyDown() TextField.
, ,
container.
- ,
Adobe Flash Player AIR. , Internet Explorer Ctrl+W,
, SWF-
.

IME
Flash Player 9 , Adobe AIR 1.0
IME (IME) Flash Player
Adobe AIR.
ActionScript :

IME (Capabilities.hasIME);
IME (IME.enabled);
IME (IME.conversionMode).
IME.
, IME (),
, , ..
IME ,
ASCII, , , .

23.11.2012.

604

ACTIONSCRIPT 3.0

IME . ,
. -:

http://www.msdn.microsoft.com/goglobal/
http://developer.apple.com/library/mac/navigation/
http://www.java.sun.com/
. IME ,
IME, Capabilities.hasIME, .
IME , ActionScript IME
. , IME
, , IME.

IME
Flash Player 9 , Adobe AIR 1.0
IME, ,
IME . ,
, IME, .
if (Capabilities.hasIME)
{
if (IME.enabled)
{
trace("IME is installed and enabled.");
}
else
{
trace("IME is installed but not enabled. Please enable your IME and try again.");
}
}
else
{
trace("IME is not installed. Please install an IME and try again.");
}

, IME,
Capabilities.hasIME. true, , IME
, IME.enabled.

IME
Flash Player 9 , Adobe AIR 1.0
,
IME. ,
, IME , , .

23.11.2012.

605

ACTIONSCRIPT 3.0

if (Capabilities.hasIME)
{
switch (IME.conversionMode)
{
case IMEConversionMode.ALPHANUMERIC_FULL:
tf.text = "Current conversion mode is alphanumeric (full-width).";
break;
case IMEConversionMode.ALPHANUMERIC_HALF:
tf.text = "Current conversion mode is alphanumeric (half-width).";
break;
case IMEConversionMode.CHINESE:
tf.text = "Current conversion mode is Chinese.";
break;
case IMEConversionMode.JAPANESE_HIRAGANA:
tf.text = "Current conversion mode is Japananese Hiragana.";
break;
case IMEConversionMode.JAPANESE_KATAKANA_FULL:
tf.text = "Current conversion mode is Japanese Katakana (full-width).";
break;
case IMEConversionMode.JAPANESE_KATAKANA_HALF:
tf.text = "Current conversion mode is Japanese Katakana (half-width).";
break;
case IMEConversionMode.KOREAN:
tf.text = "Current conversion mode is Korean.";
break;
default:
tf.text = "Current conversion mode is " + IME.conversionMode + ".";
break;
}
}
else
{
tf.text = "Please install an IME and try again.";
}

, IME.
IME IME.conversionMode IMEConversionMode.

IME
Flash Player 9 , Adobe AIR 1.0
IME
try..catch, conversionMode
, IME .
try..catch IME.conversionMode.

23.11.2012.

606

ACTIONSCRIPT 3.0

var statusText:TextField = new TextField;


statusText.autoSize = TextFieldAutoSize.LEFT;
addChild(statusText);
if (Capabilities.hasIME)
{
try
{
IME.enabled = true;
IME.conversionMode = IMEConversionMode.KOREAN;
statusText.text = "Conversion mode is " + IME.conversionMode + ".";
}
catch (error:Error)
{
statusText.text = "Unable to set conversion mode.\n" + error.message;
}
}


. , IME ,
. IME, Flash Player
AIR , try..catch. try..catch
, .

IME
Flash Player 9 , Adobe AIR 1.0
IME . ,
, , , IME
.
, FocusEvent.FOCUS_IN
FocusEvent.FOCUS_OUT IME .

23.11.2012.

607

ACTIONSCRIPT 3.0

var phoneTxt:TextField = new TextField();


var nameTxt:TextField = new TextField();
phoneTxt.type = TextFieldType.INPUT;
phoneTxt.addEventListener(FocusEvent.FOCUS_IN, focusInHandler);
phoneTxt.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
phoneTxt.restrict = "0-9";
phoneTxt.width = 100;
phoneTxt.height = 18;
phoneTxt.background = true;
phoneTxt.border = true;
addChild(phoneTxt);
nameField.type = TextFieldType.INPUT;
nameField.x = 120;
nameField.width = 100;
nameField.height = 18;
nameField.background = true;
nameField.border = true;
addChild(nameField);
function focusInHandler(event:FocusEvent):void
{
if (Capabilities.hasIME)
{
IME.enabled = false;
}
}
function focusOutHandler(event:FocusEvent):void
{
if (Capabilities.hasIME)
{
IME.enabled = true;
}
}

, phoneTxt nameTxt,
phoneTxt.
phoneTxt, FocusEvent.FOCUS_IN, IME .
phoneTxt , FocusEvent.FOCUS_OUT, IME .

IME
Flash Player 9 , Adobe AIR 1.0
IME . ,
IME , IMEEvent.IME_COMPOSITION
, .
IMEEvent.IME_COMPOSITION, ime
System (flash.system.System.ime.addEventListener(...)), .

23.11.2012.

608

ACTIONSCRIPT 3.0

var inputTxt:TextField;
var outputTxt:TextField;
inputTxt = new TextField();
inputTxt.type = TextFieldType.INPUT;
inputTxt.width = 200;
inputTxt.height = 18;
inputTxt.border = true;
inputTxt.background = true;
addChild(inputTxt);
outputTxt = new TextField();
outputTxt.autoSize = TextFieldAutoSize.LEFT;
outputTxt.y = 20;
addChild(outputTxt);
if (Capabilities.hasIME)
{
IME.enabled = true;
try
{
IME.conversionMode = IMEConversionMode.JAPANESE_HIRAGANA;
}
catch (error:Error)
{
outputTxt.text = "Unable to change IME.";
}
System.ime.addEventListener(IMEEvent.IME_COMPOSITION, imeCompositionHandler);
}
else
{
outputTxt.text = "Please install IME and try again.";
}
function imeCompositionHandler(event:IMEEvent):void
{
outputTxt.text = "you typed: " + event.text;
}

. ,
inputTxt, , . ,
outputTxt, ,
, inputTxt.


Flash Player 10.2 , AIR 2.6
, ,
. API- Flash :

;
;

23.11.2012.

609

ACTIONSCRIPT 3.0

, ;
, , . (
AIR iOS.)

( AIR.) ,
.


,
.

, .
:
C softKeyboardActivating
. preventDefault() ,
.
C softKeyboardActivate
softKeyboardActivating. , softKeyboardRect

Stage , .
.
. , , ,
softKeyboardActivate.
C softKeyboardDeactivate
. .
TextField. TextField
, .
TextField .
, .
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.events.SoftKeyboardEvent;
public class SoftKeyboardEventExample extends Sprite
{
private var tf1:TextField = new TextField();
private var tf2:TextField = new TextField();
public function SoftKeyboardEventExample()
{
tf1.width = this.stage.stageWidth;
tf1.type = TextFieldType.INPUT;
tf1.border = true;
this.addChild( tf1 );
tf1.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING, preventSoftKe
yboard );

23.11.2012.

610

ACTIONSCRIPT 3.0

tf1.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, preventSoftKe


yboard );
tf1.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, preventSoftKeyboard
);
tf2.border = true;
tf2.type = TextFieldType.INPUT;
tf2.width = this.stage.stageWidth;
tf2.y = tf1.y + tf1.height + 30;
this.addChild( tf2 );
tf2.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATING, allowSoftKeyboard );
tf2.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE, allowSoftKeyboard );
tf2.addEventListener( SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE, allowSoftKeyboard);
}
private function preventSoftKeyboard( event:SoftKeyboardEvent ):void
{
event.preventDefault();
this.stage.focus = null; //close the keyboard, if raised
trace( "tf1 dispatched: " + event.type + " -- " + event.triggerType );
}
private function allowSoftKeyboard( event:SoftKeyboardEvent )
:void
{
trace( "tf2 dispatched: " + event.type + " -- " + event.triggerType );
}
}
}

Flash Player 10.2 , AIR 2.6 ( iOS)


TextField.
InteractiveObject , .
InteractiveObject ,
needsSoftKeyboard true. focus
. ,
requestSoftKeyboard() InteractiveObject.
, InteractiveObject
. TextInput, , needsSoftKeyboard ,
. keyDown
.
Flash
.
.

23.11.2012.

611

ACTIONSCRIPT 3.0

package {
import
import
import
import
import
import
import
import
import
import

flash.geom.Rectangle;
flash.display.Sprite;
flash.text.engine.TextElement;
flash.text.engine.TextBlock;
flash.events.MouseEvent;
flash.events.FocusEvent;
flash.events.KeyboardEvent;
flash.text.engine.TextLine;
flash.text.engine.ElementFormat;
flash.events.Event;

public class TextInput extends Sprite


{
public var text:String = " ";
public var textSize:Number = 24;
public var textColor:uint = 0x000000;
private var _bounds:Rectangle = new Rectangle( 0, 0, 100, textSize );
private var textElement: TextElement;
private var textBlock:TextBlock = new TextBlock();
public function TextInput( text:String = "" )
{
this.text = text;
this.scrollRect = _bounds;
this.focusRect= false;
//Enable keyboard support
this.needsSoftKeyboard = true;
this.addEventListener(MouseEvent.MOUSE_DOWN, onSelect);
this.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
this.addEventListener(FocusEvent.FOCUS_OUT, onFocusOut);
//Setup text engine
textElement = new TextElement( text, new ElementFormat( null, textSize, textColor ) );
textBlock.content = textElement;
var firstLine:TextLine = textBlock.createTextLine( null, _bounds.width - 8 );
firstLine.x = 4;
firstLine.y = 4 + firstLine.totalHeight;
this.addChild( firstLine );
}
private function onSelect( event:MouseEvent ):void
{
stage.focus = this;
}
private function onFocusIn( event:FocusEvent ):void
{
this.addEventListener( KeyboardEvent.KEY_DOWN, onKey );
}
private function onFocusOut( event:FocusEvent ):void
{
this.removeEventListener( KeyboardEvent.KEY_UP, onKey );
}

23.11.2012.

612

ACTIONSCRIPT 3.0

private function onKey( event:KeyboardEvent ):void


{
textElement.replaceText( textElement.text.length, textElement.text.length,
String.fromCharCode( event.charCode ) );
updateText();
}
public function set bounds( newBounds:Rectangle ):void
{
_bounds = newBounds.clone();
drawBackground();
updateText();
this.scrollRect = _bounds;
//force update to focus rect, if needed
if( this.stage!= null && this.focusRect && this.stage.focus == this )
this.stage.focus = this;
}
private function updateText():void
{
//clear text lines
while( this.numChildren > 0 ) this.removeChildAt( 0 );
//and recreate them
var textLine:TextLine = textBlock.createTextLine( null, _bounds.width - 8);
while ( textLine)
{
textLine.x = 4;
if( textLine.previousLine != null )
{
textLine.y = textLine.previousLine.y +
textLine.previousLine.totalHeight + 2;
}
else
{
textLine.y = 4 + textLine.totalHeight;
}
this.addChild(textLine);
textLine = textBlock.createTextLine(textLine, _bounds.width - 8 );
}
}
private function drawBackground():void
{
//draw background and border for the field
this.graphics.clear();
this.graphics.beginFill( 0xededed );
this.graphics.lineStyle( 1, 0x000000 );
this.graphics.drawRect( _bounds.x + 2, _bounds.y + 2, _bounds.width - 4,
_bounds.height - 4);
this.graphics.endFill();
}
}
}

23.11.2012.

613

ACTIONSCRIPT 3.0

TextInput
.
TextInput .
TextInput
. , TextInput,
, .
,
. , .
package

import
import
import
import
import
import

flash.display.MovieClip;
flash.events.SoftKeyboardEvent;
flash.geom.Rectangle;
flash.events.Event;
flash.display.StageScaleMode;
flash.display.StageAlign;

public class CustomTextField extends MovieClip {


private var customField:TextInput = new TextInput("Input text: ");
public function CustomTextField() {
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
this.addChild( customField );
customField.bounds = new Rectangle( 0, 0, this.stage.stageWidth,
this.stage.stageHeight );
//track soft keyboard and stage resize events
customField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE,
onDisplayAreaChange );
customField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE,
onDisplayAreaChange );
this.stage.addEventListener( Event.RESIZE, onDisplayAreaChange );
}
private function onDisplayAreaChange( event:Event ):void
{
//Fill the stage if possible, but avoid the area covered by a keyboard
var desiredBounds = new Rectangle( 0, 0, this.stage.stageWidth,
this.stage.stageHeight );
if( this.stage.stageHeight - this.stage.softKeyboardRect.height <
desiredBounds.height )
desiredBounds.height = this.stage.stageHeight this.stage.softKeyboardRect.height;
customField.bounds = desiredBounds;
}
}
}

.
, scaleMode noScale.
, .

23.11.2012.

614

ACTIONSCRIPT 3.0


AIR 2.6
AIR ,
, softKeyboardBehavior
none.
<softKeyboardBehavior>none</softKeyboardBehavior>


. softKeyboardActivate , .
softKeyboardActivate softKeyboardRect
, .
, , . (
softKeyboardRect .)
softKeyboardDeactivate,
.
package {
import
import
import
import
import
import
import
import

flash.display.MovieClip;
flash.events.SoftKeyboardEvent;
flash.events.Event;
flash.display.StageScaleMode;
flash.display.StageAlign;
flash.display.InteractiveObject;
flash.text.TextFieldType;
flash.text.TextField;

public class PanningExample extends MovieClip {


private var textField:TextField = new TextField();
public function PanningExample() {
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
textField.y = this.stage.stageHeight - 201;
textField.width = this.stage.stageWidth;
textField.height = 200;
textField.type = TextFieldType.INPUT;
textField.border = true;
textField.wordWrap = true;
textField.multiline = true;
this.addChild( textField );
//track soft keyboard and stage resize events
textField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_ACTIVATE,
onKeyboardChange );
textField.addEventListener(SoftKeyboardEvent.SOFT_KEYBOARD_DEACTIVATE,
onKeyboardChange );
this.stage.addEventListener( Event.RESIZE, onDisplayAreaChange );
}
private function onDisplayAreaChange( event:Event ):void

23.11.2012.

615

ACTIONSCRIPT 3.0

{
textField.y = this.stage.stageHeight - 201;
textField.width = this.stage.stageWidth;
}
private function onKeyboardChange( event:SoftKeyboardEvent ):void
{
var field:InteractiveObject = textField;
var offset:int = 0;
//if the softkeyboard is open and the field is at least partially covered
if( (this.stage.softKeyboardRect.y != 0) && (field.y + field.height >
this.stage.softKeyboardRect.y) )
offset = field.y + field.height - this.stage.softKeyboardRect.y;
//but don't push the top of the field above the top of the screen
if( field.y - offset < 0 ) offset += field.y - offset;
this.y = -offset;
}
}
}

. Android , ,
.
. ,
IME ( ). IME
.
, .

23.11.2012.

616

617

31.
Flash Player 9 , Adobe AIR 1.0

. ,
ActionScript 3.0. . 134.
(, ,
) . 599.


flash.ui.Mouse
flash.events.MouseEvent
, 624


Flash Player 9 , Adobe AIR 1.0
,
. ,
, SWF-.
, InteractiveObject (, Sprite
MovieClip). .
, .
square Stage,
square, Stage:
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF0000);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.addEventListener(MouseEvent.CLICK, reportClick);
square.x =
square.y = 50;
addChild(square);
stage.addEventListener(MouseEvent.CLICK, reportClick);
function reportClick(event:MouseEvent):void
{
trace(event.currentTarget.toString() + " dispatches MouseEvent. Local coords [" +
event.localX + "," + event.localY + "] Stage coords [" + event.stageX + "," + event.stageY + "]");
}

23.11.2012.

ACTIONSCRIPT 3.0

. localX
localY . ,
square [0,0],
square. stageX stageY
. [50,50],
square . ,
.
. ,
. , .
. 179.
MouseEvent altKey, ctrlKey shiftKey.
, Alt, Ctrl Shift.


Flash Player 9 , Adobe AIR 1.0
Sprite
startDrag() Sprite. :

23.11.2012.

618

ACTIONSCRIPT 3.0

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);
}

.
187.
AIR
Adobe AIR ,
. . AIR
654.


Flash Player 9 , Adobe AIR 1.0
() .
, Mouse.hide(). , Mouse.hide(),
MouseEvent.MOUSE_MOVE,
( ) stageX stageY.
:

23.11.2012.

619

ACTIONSCRIPT 3.0

var cursor:Sprite = new Sprite();


cursor.graphics.beginFill(0x000000);
cursor.graphics.drawCircle(0,0,20);
cursor.graphics.endFill();
addChild(cursor);
stage.addEventListener(MouseEvent.MOUSE_MOVE,redrawCursor);
Mouse.hide();
function redrawCursor(event:MouseEvent):void
{
cursor.x = event.stageX;
cursor.y = event.stageY;
}

: WordSearch
Flash Player 9 , Adobe AIR 1.0
.
. ,
, .
ActionScript 3.0:

;
;
.

www.adobe.com/go/learn_programmingAS3samples_flash_ru. WordSearch
Samples/WordSearch. .
File

WordSearch.as

, .

WordSearch.fla

Flex (MXML) Flash (FLA).

WordSearch.mxml
dictionary.txt

, .

23.11.2012.

620

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
.
dictionary.txt, , . words
loadDictionary() ,
. split(),
( 10) ( 13).
dictionaryLoaded():
words = dictionaryText.split(String.fromCharCode(13, 10));


Flash Player 9 , Adobe AIR 1.0
. Button:
, ,
.
MouseEvent.CLICK, , . setupUI()
:
submitWordButton.addEventListener(MouseEvent.CLICK,submitWord);
clearWordButton.addEventListener(MouseEvent.CLICK,clearWord);


Flash Player 9 , Adobe AIR 1.0
. generateBoard() ,
. ,
. , , .

23.11.2012.

621

ACTIONSCRIPT 3.0

private function generateBoard(startX:Number, startY:Number, totalRows:Number,


totalCols:Number, buttonSize:Number):void
{
buttons = new Array();
var colCounter:uint;
var rowCounter:uint;
for (rowCounter = 0; rowCounter < totalRows; rowCounter++)
{
for (colCounter = 0; colCounter < totalCols; colCounter++)
{
var b:Button = new Button();
b.x = startX + (colCounter*buttonSize);
b.y = startY + (rowCounter*buttonSize);
b.addEventListener(MouseEvent.CLICK, letterClicked);
b.label = getRandomLetter().toUpperCase();
b.setSize(buttonSize,buttonSize);
b.name = "buttonRow"+rowCounter+"Col"+colCounter;
addChild(b);
buttons.push(b);
}
}
}

MouseEvent.CLICK ,
for, Button. ,
, .


Flash Player 9 , Adobe AIR 1.0
, , ,
. :
, , , ,
. , .
isLegalContinuation().
private
{
var
3));
var
3));
var
3));
var
3));

function isLegalContinuation(prevButton:Button, currButton:Button):Boolean


currButtonRow:Number = Number(currButton.name.charAt(currButton.name. indexOf("Row") +
currButtonCol:Number = Number(currButton.name.charAt(currButton.name.indexOf("Col") +
prevButtonRow:Number = Number(prevButton.name.charAt(prevButton.name.indexOf("Row") +
prevButtonCol:Number = Number(prevButton.name.charAt(prevButton.name.indexOf("Col") +

return ((prevButtonCol == currButtonCol && Math.abs(prevButtonRow - currButtonRow) <= 1) ||


(prevButtonRow == currButtonRow && Math.abs(prevButtonCol - currButtonCol) <= 1));
}

23.11.2012.

622

ACTIONSCRIPT 3.0

charAt() indexOf() String


. isLegalContinuation() true,
, , .
, ,
. :
return (Math.abs(prevButtonRow - currButtonRow) <= 1) && Math.abs(prevButtonCol currButtonCol) <= 1));


Flash Player 9 , Adobe AIR 1.0
:
. searchForWord() :
private function searchForWord(str:String):Number
{
if (words && str)
{
var i:uint = 0
for (i = 0; i < words.length; i++)
{
var thisWord:String = words[i];
if (str == words[i])
{
return i;
}
}
return -1;
}
else
{
trace("WARNING: cannot find words, or string supplied is null");
}
return -1;
}

, . ,
, , .
submitWord() , .

Flash Player 9 , Adobe AIR 1.0


. , . ,
, , TOTAL_TIME.
PERCENT_VOWELS,
.

23.11.2012.

623

624

32.
,

Flash Player 10.1 , Adobe AIR 2
Flash Platform
, . , Flash
, .
, Flash :
, ,
, , .
.
Multitouch .
,

. ,
,
. ,
. , ,
.

. ActionScript API-
, .
.

( ). ,
, , .

, ,
, . ,
, .


flash.ui.Multitouch
flash.events.TouchEvent
flash.events.GestureEvent
flash.events.TransformGestureEvent
flash.events.GesturePhase
flash.events.PressAndTapGestureEvent

23.11.2012.

625

ACTIONSCRIPT 3.0
,

(Paul Trani):
(Mike Jones):


Flash Player 10.1 , Adobe AIR 2
Flash Platform , ,
InteractiveObject . ,
, ,
ActionScript ( ActionScript .
134).
, Flash ,
,
. . 599 ,
. ,
(, ), .
Multitouch,
, Flash, .
.

:

(,
)

Flash

Flash Platform

, API- ActionScript , ,
,
. API-,
, API-
.

, ,
:
API- ,

.
, , ,

23.11.2012.

ACTIONSCRIPT 3.0
,

.
,
.
,

. ,
.
Multitouch , , ,

(, ).
, ,
. ,

.
(, ).
.

, . .
, ,
.
,
,
.
Multitouch.

API-
API- ActionScript ,
, Flash. API ,
: , . API-
;
.

API- .
, , ,
Flash . ,
( ,
). .
627.

ActionScript
, .
:


: .

23.11.2012.

626

ACTIONSCRIPT 3.0
,

(, ) ,
, .
MouseEvent. ,
. ,
.


.
API-
. ,

. ,
, .
. 628
633.

, ,
.
ActionScript ,
, . ,
,
. .

.
.
.
.


Flash Player 10.1 , Adobe AIR 2
Multitouch ,
. , ,
ActionScript. , .
: , (
).
Multitouch, ,
, , .
(, )
.
. Multitouch . Multitouch., :
var touchSupport:Boolean = Multitouch.supportsTouchEvents;

23.11.2012.

627

ACTIONSCRIPT 3.0
,


Flash ,
.
, ? ?
? ,
, ,
Flash. Multitouch.inputMode
. :
. :
Multitouch.inputMode=MultitouchInputMode.NONE MouseEvent .

. :
Multitouch.inputMode=MultitouchInputMode.TOUCH_POINT TouchEvent

.
. : Multitouch.inputMode=MultitouchInputMode.GESTURE
TransformGestureEvent, PressAndTapGestureEvent GestureEvent .
. 628 ,
Multitouch.inputMode .


Multitouch
. Flash
.
, ,
, . ,
, .
API- , . .
599.
.
637.


Flash Player 10.1 , Adobe AIR 2
ActionScript , ,
. ,
TouchEvent.
. (,
) .

23.11.2012.

628

ACTIONSCRIPT 3.0
,

:
1 ,
flash.ui.Multitouch.inputMode MultitouchInputMode.TOUCH_POINT.

2 ,

InteractiveObject, Sprite TextField.


3 .
4 .

, , ,
mySprite, :
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(evt:TouchEvent): void {
myTextField.text = "I've been tapped";
myTextField.y = 50;
addChild(myTextField);
}


, . TouchEvent
.
.
, TouchEvent evt, stageX
( X , ) :
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(evt:TouchEvent): void {
myTextField.text = evt.stageX.toString;
myTextField.y = 50;
addChild(myTextField);
}

. TouchEvent , .

23.11.2012.

629

ACTIONSCRIPT 3.0
,

. TouchEvent . ,
.
TouchEvent.pressure .
.
637 .


InteractiveObject ,
. , ,
. TouchEvent touchBegin, touchMove
touchEnd.
, touchBegin, touchMove touchEnd
:
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();
myTextField.width = 200;
myTextField.height = 20;
addChild(myTextField);
mySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin);
stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove);
stage.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);
function onTouchBegin(event:TouchEvent) {
myTextField.text = "touch begin" + event.touchPointID;
}
function onTouchMove(event:TouchEvent) {
myTextField.text = "touch move" + event.touchPointID;
}
function onTouchEnd(event:TouchEvent) {
myTextField.text = "touch end" + event.touchPointID;
}

. mySprite,
.
,
.


TouchEvent.touchPointID .
. Flash
touchPointID.
, touchPointID .
Sprite touchPointID ,

23.11.2012.

630

ACTIONSCRIPT 3.0
,

. touchPointID
.
(, touchMove) ,
. ,
.
touchPointID .
touchBegin,
touchMove touchEnd, touchPointID.
touchMoveID touchPointID
.
. ,
, .
, .
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);

23.11.2012.

631

ACTIONSCRIPT 3.0
,

}
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;
}


Flash Player 10.1 , Adobe AIR 2
Sprite ,
: Sprite.startTouchDrag() Sprite.stopTouchDrag().
Sprite.startDrag() Sprite.stopDrag() .
, Sprite.startTouchDrag() Sprite.stopTouchDrag()
touchPointID .
touchPointID .
,
( ).
touchPointID .
630.

. bg ,
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");
}

23.11.2012.

632

ACTIONSCRIPT 3.0
,

,
:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(0,0,40,40);
addChild(mySprite);
mySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin);
mySprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove);
mySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);
function onTouchBegin(evt:TouchEvent) {
evt.target.startTouchDrag(evt.touchPointID);
evt.target.scaleX *= 1.5;
evt.target.scaleY *= 1.5;
}
function onTouchMove(evt:TouchEvent) {
evt.target.alpha = 0.5;
}
function onTouchEnd(evt:TouchEvent) {
evt.target.stopTouchDrag(evt.touchPointID);
evt.target.width = 40;
evt.target.height = 40;
evt.target.alpha = 1;
}


Flash Player 10.1 , Adobe AIR 2
, .
,
TransformGestureEvent, GestureEvent PressAndTapGestureEvent.
:
1 , flash.ui.Multitouch.inputMode

MultitouchInputMode.GESTURE.
2 ,

InteractiveObject, Sprite TextField.


3 .
4 .

, , ,
mySprite, :

23.11.2012.

633

ACTIONSCRIPT 3.0
,

Multitouch.inputMode=MultitouchInputMode.GESTURE;
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(TransformGestureEvent.GESTURE_SWIPE, swipehandler);
function swipehandler(evt:TransformGestureEvent): void {
myTextField.text = "I've been swiped";
myTextField.y = 50;
addChild(myTextField);
}

, GestureEvent:
Multitouch.inputMode=MultitouchInputMode.GESTURE;
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(GestureEvent.GESTURE_TWO_FINGER_TAP, taphandler);
function taphandler(evt:GestureEvent): void {
myTextField.text = "I've been two-finger tapped";
myTextField.y = 50;
addChild(myTextField);
}

,
PressAndTapGestureEvent:
Multitouch.inputMode=MultitouchInputMode.GESTURE;
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(PressAndTapGestureEvent.GESTURE_PRESS_AND_TAP, taphandler);
function taphandler(evt:PressAndTapGestureEvent): void {
myTextField.text = "I've been press-and-tapped";
myTextField.y = 50;
addChild(myTextField);
}

23.11.2012.

634

ACTIONSCRIPT 3.0
,

. GestureEvent, TransformGestureEvent PressAndTapGestureEvent


. ,
. gestureSwipe InteractiveObject
.
. 637
.


, .
: .
, mySprite,
. , (
):
Multitouch.inputMode=MultitouchInputMode.GESTURE;
var mySprite:Sprite = new Sprite();
var mySpriteCon:Sprite = new Sprite();
var myTextField:TextField = new TextField();
myTextField.y = 50;
addChild(myTextField);
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(-20,-20,40,40);
mySpriteCon.addChild(mySprite);
mySprite.x = 20;
mySprite.y = 20;
addChild(mySpriteCon);
mySprite.addEventListener(TransformGestureEvent.GESTURE_ROTATE, rothandler);
function rothandler(evt:TransformGestureEvent): void {
evt.target.parent.rotationZ += evt.target.rotation;
myTextField.text = evt.target.parent.rotation.toString();
}

. TransformGestureEvent . ,
.
TransformGestureEvent.rotation .
.
637 .


, ,
. , ,
. ,
, .
.
.

23.11.2012.

635

ACTIONSCRIPT 3.0
,

Multitouch.inputMode = MultitouchInputMode.GESTURE;
var mySprite = new Sprite();
mySprite.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan);
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(0, 0, 40, 40);
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";
evt.target.scaleX *= 1.5;
evt.target.scaleY *= 1.5;
}
if (evt.phase==GesturePhase.UPDATE) {
myTextField.text = "Update";
evt.target.alpha = 0.5;
}
if (evt.phase==GesturePhase.END) {
myTextField.text = "End";
evt.target.width = 40;
evt.target.height = 40;
evt.target.alpha = 1;
}
}

. , .
.


all
.
. phase
InteractiveObject listening gestureSwipe gestureTwoFingerTap
all :

23.11.2012.

636

ACTIONSCRIPT 3.0
,

Multitouch.inputMode = MultitouchInputMode.GESTURE;
var mySprite = new Sprite();
mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipe);
mySprite.addEventListener(GestureEvent.GESTURE_TWO_FINGER_TAP, onTwoTap);
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(0, 0, 40, 40);
var myTextField = new TextField();
myTextField.y = 200;
addChild(mySprite);
addChild(myTextField);
function onSwipe(swipeEvt:TransformGestureEvent):void {
myTextField.text = swipeEvt.phase // Output is "all"
}
function onTwoTap(tapEvt:GestureEvent):void {
myTextField.text = tapEvt.phase // Output is "all"
}


Flash Player 10.1 , Adobe AIR 2
.
,
, Multitouch.
API- , ,
Multitouch, ActionScript.
Flash , ,
- (, ) .
Multitouch.
.
?
?
.
,
. ,
.
:
Flash Player, ,
.
API- ,
. API-,
Multitouch: http://help.adobe.com/ru_RU/FlashPlatform/reference/actionscript/3/flash/ui/Multitouch.html.
:
.

23.11.2012.

637

ACTIONSCRIPT 3.0
,

, (

).
.
, , .
,
.
,

.

. ,
.
, :
1 , ,

InteractiveObject? InteractiveObject
.
2 Flash Professional CS5? ,

, Flash Professional
.
3 ( API-

Multitouch.inputMode:
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, taplistener);
function taplistener(e:TouchEvent): void {
myTextField.text = "I've been tapped";
myTextField.y = 50;
addChild(myTextField);
}

. , ,
. .
.
.
.

23.11.2012.

638

ACTIONSCRIPT 3.0
,

Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom);
var myTextField = new TextField();
myTextField.y = 200;
myTextField.text = "Perform a zoom gesture";
addChild(myTextField);
function onZoom(evt:TransformGestureEvent):void {
myTextField.text = "Zoom is supported";
}

, Zoom is
supported ( ). ,
.
.
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_PAN , onPan);
var myTextField = new TextField();
myTextField.y = 200;
myTextField.text = "Perform a pan gesture";
addChild(myTextField);
function onPan(evt:TransformGestureEvent):void {
myTextField.text = "Pan is supported";
}

,
Pan is supported ( ).
, .
,
, .
.


:
1 Mobile Internet Explorer Windows Mobile

SWF-:
Internet Explorer
HTML, SWF-:
<head>
<meta name="viewport" content="width=device-width, height=device-height, initialscale=1.0">
</head>

2 Windows 7 (, , )

( ) . ,
:

23.11.2012.

639

ACTIONSCRIPT 3.0
,

.
.
3 Windows 7 (, , )

, .
4 Windows 7 Starter Edition Multitouch. . AIR Labs Forum

: http://forums.adobe.com/thread/579180?tstart=0
5 Mac OS 10.5.3 Multitouch.supportsGestureEvents

true, .

23.11.2012.

640

641

33.
Flash Player 10 , Adobe AIR 1.0
API-
. ,
Adobe Flash Player Adobe AIR.


HTML
RTF (Rich Text Format)

( )
( AIR)
( AIR)
URL ( AIR)


Flash Player 10 , Adobe AIR 1.0
API- .

flash.desktop

Clipboard

ClipboardFormats

ClipboardTransferMode

Clipboard.generalClipboard . Clipboard
.
HTMLLoader ( AIR) TextField
.
.
, ,
.
Clipboard ,
, . ,
, .
( ), ,
, .

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 10 , Adobe AIR 1.0
getData()
Clipboard.generalClipbooard :
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
if(Clipboard.generalClipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)){
var text:String = Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT);
}

. , Flash Player AIR


, getData() paste.
, , AIR,
getData() paste.
Clipboard.generalClipboard
. .
,
.
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
var textToCopy:String = "Copy to clipboard.";
Clipboard.generalClipboard.clear();
Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, textToCopy, false);

. , Flash Player AIR


, setData()
, , , copy cut. , ,
AIR, getData()
.

HTML AIR
Adobe AIR 1.0
HTML Adobe AIR
. ,
. AIR
Clipboard.generalClipboard. JavaScript
,
, , , HTML-.
: copy, cut paste. ,
, clipboardData.

23.11.2012.

642

ACTIONSCRIPT 3.0


Adobe AIR 1.0
AIR copy,
. cut AIR
, paste
.
preventDefault()
.

clipboardData
Adobe AIR 1.0
clipboardData copy paste
.
copy cut setData()
clipboardData, MIME-:
function customCopy(event){
event.clipboardData.setData("text/plain", "A copied string.");
}

getData() clipboardData,
MIME- . types.
function customPaste(event){
var pastedData = event.clipboardData("text/plain");
}

getData() types ,
paste.
, HTML. copy
HTML-. cut
. paste HTML
.

23.11.2012.

643

ACTIONSCRIPT 3.0

<html>
<head>
<title>Copy and Paste</title>
<script language="javascript" type="text/javascript">
function onCopy(event){
var selection = window.getSelection();
event.clipboardData.setData("text/html","<i>" + selection + "</i>");
event.preventDefault();
}
function onCut(event){
var selection = window.getSelection();
event.clipboardData.setData("text/html","<i>" + selection + "</i>");
var range = selection.getRangeAt(0);
range.extractContents();
event.preventDefault();
}
function onPaste(event){
var insertion = document.createElement("b");
insertion.innerHTML = event.clipboardData.getData("text/html");
var selection = window.getSelection();
var range = selection.getRangeAt(0);
range.insertNode(insertion);
event.preventDefault();
}
</script>
</head>
<body onCopy="onCopy(event)"
onPaste="onPaste(event)"
onCut="onCut(event)">
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur
magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</body>
</html>

Clipboard
Flash Player 10 , Adobe AIR 1.0
Clipboard , Clipboard. Flash Player
AIR ActionScript
. , ,
ActionScript, , .

23.11.2012.

644

ACTIONSCRIPT 3.0

Clipboard .
, Clipboard, Sprite,
, ,
Flash Player AIR,
, ,
PNG, Sprite
.


Flash Player 10 , Adobe AIR 1.0
, , ClipboardFormats:

TEXT_FORMAT

String ActionScript .

HTML_FORMAT

HTML-.

RICH_TEXT_FORMAT

RTF ByteArray ActionScript . RTF-


.

BITMAP_FORMAT

( AIR) ActionScript
BitmapData .

FILE_LIST_FORMAT

( AIR) ActionScript File


.

URL_FORMAT

( AIR) URL ActionScript String .

copy, cut paste HTML-,


AIR, ClipboardFormat MIME-.
MIME- :
MIME

text/plain;

URL-

text/uri-list;

image/x-vnd.adobe.air.bitmap;

application/x-vnd.adobe.air.file-list.

. RTF clipboardData
paste HTML-.

23.11.2012.

645

ACTIONSCRIPT 3.0


Flash Player 10 , Adobe AIR 1.0

. .
,
, . ,
, ,
.
Clipboard Clipboard.setData()
serializable true.
, .


Flash Player 10 , Adobe AIR 1.0
,
.
,
.

ClipboardTransferModes.ORIGINAL_ONLY

. , null.

ClipboardTransferModes.ORIGINAL_PREFFERED

( ).
.

ClipboardTransferModes.CLONE_ONLY

.
, .

ClipboardTransferModes.CLONE_PREFFERED

( ).
.


Flash Player 10 , Adobe AIR 1.0
,
air: flash: format.
. ,
.
public function createClipboardObject(object:Object):Clipboard{
var transfer:Clipboard = Clipboard.generalClipboard;
transfer.setData("object", object, true);
}

Clipboard ( ),
CLONE_ONLY CLONE_PREFFERED.
var transfer:Object = clipboard.getData("object", ClipboardTransferMode.CLONE_ONLY);

23.11.2012.

646

ACTIONSCRIPT 3.0

Clipboard . ,
( drop paste) ORIGINAL_ONLY
ORIGINAL_PREFFERED:
var transferredObject:Object =
clipboard.getData("object", ClipboardTransferMode.ORIGINAL_ONLY);

, Clipboard .
ORIGINAL_PREFFERED, , ,
, .


Flash Player 10 , Adobe AIR 1.0
,
: , .
,
.
Clipboard setDataHandler().
. ,
setDataHandler(ClipboardFormat.TEXT_FORMAT, writeText) writeText()
.
Clipboard setData() ,
( ).
,
.
. Mac OS X
. .


Flash Player 10 , Adobe AIR 1.0
, .
Copy (), ,
, .
setDataHandler() renderData() .
Paste () ,
.
, , renderData().
renderData() , .
, ,
, .
- , ,
. (
.)

23.11.2012.

647

ACTIONSCRIPT 3.0

Flash
package {
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
import flash.desktop.ClipboardTransferMode;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldType;
import flash.events.MouseEvent;
import flash.events.Event;
public class DeferredRenderingExample extends Sprite
{
private var sourceTextField:TextField;
private var destination:TextField;
private var copyText:TextField;
public function DeferredRenderingExample():void
{
sourceTextField = createTextField(10, 10, 380, 90);
sourceTextField.text = "Neque porro quisquam est qui dolorem "
+ "ipsum quia dolor sit amet, consectetur, adipisci velit.";
copyText = createTextField(10, 110, 35, 20);
copyText.htmlText = "<a href='#'>Copy</a>";
copyText.addEventListener(MouseEvent.CLICK, onCopy);
destination = createTextField(10, 145, 380, 90);
destination.addEventListener(Event.PASTE, onPaste);
}
private function createTextField(x:Number, y:Number, width:Number,
height:Number):TextField
{
var newTxt:TextField = new TextField();
newTxt.x = x;
newTxt.y = y;
newTxt.height = height;
newTxt.width = width;
newTxt.border = true;
newTxt.multiline = true;
newTxt.wordWrap = true;
newTxt.type = TextFieldType.INPUT;
addChild(newTxt);
return newTxt;
}
public function onCopy(event:MouseEvent):void
{
Clipboard.generalClipboard.clear();
Clipboard.generalClipboard.setDataHandler(ClipboardFormats.TEXT_FORMAT,
renderData);
}
public function onPaste(event:Event):void
{

23.11.2012.

648

ACTIONSCRIPT 3.0

sourceTextField.text =
Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT).toString;
}
public function renderData():String
{
trace("Rendering data");
var sourceStr:String = sourceTextField.text;
if (sourceTextField.selectionEndIndex >
sourceTextField.selectionBeginIndex)
{
return sourceStr.substring(sourceTextField.selectionBeginIndex,
sourceTextField.selectionEndIndex);
}
else
{
return sourceStr;
}
}
}
}

23.11.2012.

649

ACTIONSCRIPT 3.0

Flex
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="326"
height="330" applicationComplete="init()">
<mx:Script>
<![CDATA[
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
public function init():void
{
destination.addEventListener("paste", doPaste);
}
public function doCopy():void
{
Clipboard.generalClipboard.clear();
Clipboard.generalClipboard.setDataHandler(ClipboardFormats.TEXT_FORMAT, renderData);
}
public function doPaste(event:Event):void
{
destination.text =
Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT).toString;
}
public function renderData():String{
trace("Rendering data");
return source.text;
}
]]>
</mx:Script>
<mx:Label x="10" y="10" text="Source"/>
<mx:TextArea id="source" x="10" y="36" width="300" height="100">
<mx:text>Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur,
adipisci velit.</mx:text>
</mx:TextArea>
<mx:Label x="10" y="181" text="Destination"/>
<mx:TextArea id="destination" x="12" y="207" width="300" height="100"/>
<mx:Button click="doCopy();" x="91" y="156" label="Copy"/>
</mx:Application>

23.11.2012.

650

651

34.
Flash Player 10.1 , Adobe AIR 2
Accelerometer ,
. .
,
. Accelerometer , ,
, .
,
.
. , y ,
, .
, SWF-
,
.


flash.sensors.Accelerometer
flash.events.AccelerometerEvent


Accelerometer.isSupported,
:
if (Accelerometer.isSupported)
{
// Set up Accelerometer event listeners and code.
}

Accelerometer ,
API-. .
, Accelerometer Flash Player 10.1,
Accelerometer.isSupported
Accelerometer . Accelerometer.isSupported
true , Accelerometer.

23.11.2012.

ACTIONSCRIPT 3.0


, Accelerometer
update. update Accelerometer.
, :

accelerationX: X, (). X

, . (
, .)
, .

accelerationY: Y, (). Y

, . (
, .) ,
.

accelerationZ: Z, (). Z

. ,
. ,
.

timestamp: , .

1 , 9,8 /2.
:
var accl:Accelerometer;
if (Accelerometer.isSupported)
{
accl = new Accelerometer();
accl.addEventListener(AccelerometerEvent.UPDATE, updateHandler);
}
else
{
accTextField.text = "Accelerometer feature not supported";
}
function updateHandler(evt:AccelerometerEvent):void
{
accTextField.text = "acceleration X: " + evt.accelerationX.toString() + "\n"
+ "acceleration Y: " + evt.accelerationY.toString() + "\n"
+ "acceleration Z: " + evt.accelerationZ.toString()
}

, accTextField
.
,
setRequestedUpdateInterval() Accelerometer. interval,

:
var accl:Accelerometer;
accl = new Accelerometer();
accl.setRequestedUpdateInterval(1000);

23.11.2012.

652

ACTIONSCRIPT 3.0

.
.
setRequestedUpdateInterval()
, .
.
. ,
,
:
var accl:Accelerometer;
var rollingX:Number = 0;
var rollingY:Number = 0;
var rollingZ:Number = 0;
const FACTOR:Number = 0.25;
if (Accelerometer.isSupported)
{
accl = new Accelerometer();
accl.setRequestedUpdateInterval(200);
accl.addEventListener(AccelerometerEvent.UPDATE, updateHandler);
}
else
{
accTextField.text = "Accelerometer feature not supported";
}
function updateHandler(event:AccelerometerEvent):void
{
accelRollingAvg(event);
accTextField.text = rollingX + "\n" + rollingY + "\n" + rollingZ + "\n";
}
function accelRollingAvg(event:AccelerometerEvent):void
{
rollingX = (event.accelerationX * FACTOR) + (rollingX * (1 - FACTOR));
rollingY = (event.accelerationY * FACTOR) + (rollingY * (1 - FACTOR));
rollingZ = (event.accelerationZ * FACTOR) + (rollingZ * (1 - FACTOR));
}

23.11.2012.

653

654

35. AIR
Adobe AIR 1.0
API Adobe AIR.
,
, , .
, - .
, -
.
API-
.
:



HTML

RTF (Rich Text Format)
URL-


( )

AIR
Adobe AIR 1.0
AIR .
Adobe Developer Connection:

, (Flex)
, (Flash)
API- .

23.11.2012.

ACTIONSCRIPT 3.0
AIR

flash.desktop

NativeDragManager

NativeDragOptions

Clipboard

URLFilePromise

IFilePromise

, API- , :

flash.events

NativeDragActions

ClipboardFormat

ClipboardTransferModes

NativeDragEvent


:
,

. -
nativeDragStart nativeDragComplete. Adobe AIR
NativeDragManager.doDrag()
mouseDown mouseMove.
AIR, -
nativeDragStart nativeDragComplete.
, ,

.
nativeDragUpdate. ( AIR for Linux.)
AIR,
nativeDragEnter. , ,
, , ,
, NativeDragManager.acceptDragDrop().
,
nativeDragOver. ,
nativeDragExit.
.

AIR, nativeDragDrop.
, .
AIR, .
- nativeDragComplete (
AIR).
NativeDragManager , .
NativeDragManager ,
.

23.11.2012.

655

ACTIONSCRIPT 3.0
AIR

Clipboard
, , Clipboard.
Clipboard ,
, . ,
, .
, ,
.
Clipboard
nativeDragEnter, nativeDragOver nativeDragDrop.
Clipboard .
.
.
AIR , ,
.
ActionScript 3 (AMF3) .
Flex
Flex API-
Adobe Flex. Flex ,
Flex AIR ( AIR NativeDragManager). Flex
,
. AIR ,
AIR.


Adobe AIR 1.0
Clipboard mouseDown
NativeDragManager.doDrag().
nativeDragComplete -, , ,
.


Flash Player 9 , Adobe AIR 1.0
, Clipboard ,
.
, ,
, .
,
. ,
- .
. Clipboard
644.

23.11.2012.

656

ACTIONSCRIPT 3.0
AIR

, Clipboard,
: Bitmap, ,
, :
import flash.desktop.Clipboard;
import flash.display.Bitmap;
import flash.filesystem.File;
public function createClipboard(image:Bitmap, sourceFile:File):Clipboard{
var transfer:Clipboard = new Clipboard();
transfer.setData("CUSTOM_BITMAP", image, true); //Flash object by value and by reference
transfer.setData(ClipboardFormats.BITMAP_FORMAT, image.bitmapData, false);
transfer.setData(ClipboardFormats.FILE_LIST_FORMAT, new Array(sourceFile), false);
return transfer;
}


Adobe AIR 1.0
NativeDragManager.doDrag()
. doDrag() :

initiator

- , dragStart dragComplete.
.

clipboard

Clipboard, . Clipboard
NativeDragEvent, .

dragImage

BitmapData, ( ).
alpha. (. Microsoft Windows
-.)

offset

Point, (
).
. ,
.

actionsAllowed

NativeDragOptions, , (,
) ( ).
, . DragOptions NativeDragEvent,
,
. , trash
.

, ,
. , mouseDown
.

23.11.2012.

657

ACTIONSCRIPT 3.0
AIR

package
{
import flash.desktop.NativeDragManager;
import mx.core.UIComponent;
import flash.display.Sprite;
import flash.display.Loader;
import flash.system.LoaderContext;
import flash.net.URLRequest;
import flash.geom.Point;
import flash.desktop.Clipboard;
import flash.display.Bitmap;
import flash.filesystem.File;
import flash.events.Event;
import flash.events.MouseEvent;
public class DragOutExample extends UIComponent Sprite {
protected var fileURL:String = "app:/image.jpg";
protected var display:Bitmap;
private function init():void {
loadImage();
}
private function onMouseDown(event:MouseEvent):void {
var bitmapFile:File = new File(fileURL);
var transferObject:Clipboard = createClipboard(display, bitmapFile);
NativeDragManager.doDrag(this,
transferObject,
display.bitmapData,
new Point(-mouseX,-mouseY));
}
public function createClipboard(image:Bitmap, sourceFile:File):Clipboard {
var transfer:Clipboard = new Clipboard();
transfer.setData("bitmap",
image,
true);
// ActionScript 3 Bitmap object by value and by reference
transfer.setData(ClipboardFormats.BITMAP_FORMAT,
image.bitmapData,
false);
// Standard BitmapData format
transfer.setData(ClipboardFormats.FILE_LIST_FORMAT,

23.11.2012.

658

ACTIONSCRIPT 3.0
AIR

new Array(sourceFile),
false);
// Standard file list format
return transfer;
}
private function loadImage():void {
var url:URLRequest = new URLRequest(fileURL);
var loader:Loader = new Loader();
loader.load(url,new LoaderContext());
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
}
private function onLoadComplete(event:Event):void {
display = event.target.loader.content;
var flexWrapper:UIComponent = new UIComponent();
flexWrapper.addChild(event.target.loader.content);
addChild(flexWrapper);
flexWrapper.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
}
}


Adobe AIR 1.0
, , -
nativeDragComplete. dropAction ,
. , NativeDragAction.MOVE
. ,
. dropAction
NativeDragAction.NONE.


Adobe AIR 1.0
, (, ,
) nativeDragEnter nativeDragOver.


Adobe AIR 1.0
:
1 .
2 nativeDragEnter.
3 nativeDragEnter

. ,
NativeDragManager.acceptDragDrop().

23.11.2012.

659

ACTIONSCRIPT 3.0
AIR

4 NativeDragManager , , .
5 .
6 - nativeDragDrop.
7 - Clipboard .
8 AIR, -

nativeDragComplete. AIR, .


Adobe AIR 1.0
,
nativeDragEnter nativeDragOver. , ,
clipboard allowedActions .

NativeDragManager.acceptDragDrop() - .
acceptDragDrop() ,
. acceptDragDrop() ,
- nativeDragExit.
allowedActions, doDrag(), ,
-.
, ,
. dropAction NativeDragEvent. ,
, . ,
, . , ,
,
.

dropAction NativeDragManager.
, NativeDragManager unavailable.
nativeDragEnter nativeDragOver dropAction.
nativeDragEnter nativeDragOver.
,
.
import flash.desktop.NativeDragManager;
import flash.events.NativeDragEvent;
public function onDragIn(event:NativeDragEvent):void{
NativeDragManager.dropAction = NativeDragActions.MOVE;
if(event.clipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)){
NativeDragManager.acceptDragDrop(this); //'this' is the receiving component
}
}

23.11.2012.

660

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
, ,
nativeDragDrop.
clipboard .
, transferMode,
getData() Clipboard, ,
: .
nativeDragDrop:
import flash.desktop.Clipboard;
import flash.events.NativeDragEvent;
public function onDrop(event:NativeDragEvent):void {
if (event.clipboard.hasFormat(ClipboardFormats.TEXT_FORMAT)) {
var text:String =
String(event.clipboard.getData(ClipboardFormats.TEXT_FORMAT,
ClipboardTransferMode.ORIGINAL_PREFERRED));
}

Clipboard .
.


Adobe AIR 1.0
NativeDragEvent.
,
.

nativeDragStart

- nativeDragStart
, .

nativeDragUpdate

- nativeDragUpdate
. ( AIR for Linux.)

nativeDragEnter

-
, .

nativeDragOver

-
,
, .

nativeDragExit

-
, , , .

nativeDragComplete

-
(, )
.

23.11.2012.

661

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
, nativeDragOver.
.
nativeDragOver .
, - ,
. ,
,
nativeDragOver,
.

HTML
Adobe AIR 1.0
HTML- ( HTML-,
HTMLLoader, ), drag HTML. API- HTML
DOM HTML-.
. API- AIR NativeDragEvent
NativeDragManager. HTMLLoader,
HTML-. API- HTML HTML- DOM
.


Adobe AIR 1.0
HTML , URL.
. .
.

.
.
.
preventDefault() , .

.
, .
HTML- CSS WebKit -webkituser-select. , -webkit-user-select none,
. , ,
CSS -webkit-user-drag.
-. - .
. CSS AIR 1048.

23.11.2012.

662

ACTIONSCRIPT 3.0
AIR

HTML
Adobe AIR 1.0
, -, :

dragstart

, .
, preventDefault() .
,
effectAllowed. ,
,
dataTransfer .

drag

dragend

, .

dragover

, .
dataTransfer.dropEffect ,
: ,
.

dragenter

, , , .
- dataTransfer dragenter,
dragover. ,
dragenter dragover, ,
, .
.

dragleave

, , , .

drop

, .
.

, , mouse. mouse,
(clientX, clientY) (screenX, screenY), .
drag dataTransfer:
. dataTransfer :

23.11.2012.

663

ACTIONSCRIPT 3.0
AIR

effectAllowed

, . ,
dragstart. . HTML 665.

dropEffect

, . dropEffect
dragover dragenter, AIR , ,
. dropEffect
,
unavailable. dragover dragenter
dropEffect,
-.
dropEffect , dragend.
, ,
dropEffect none.

types

, MIME
dataTransfer.

getData(mimeType)

, mimeType.
getData() drop.

setData(mimeType)

dataTransfer , mimeType.
. MIME setData().
, dataTransfer
, .
setData() dragstart.

clearData(mimeType)

, mimeType.

setDragImage(image,
offsetX, offsetY)

. setDragImage()
dragstart, HTML
element CSS -webkit-user-drag. image
JavaScript Image.

MIME HTML
Adobe AIR 1.0
dataTransfer HTML MIME:

MIME

text/plain;

HTML

text/html;

URL-

text/uri-list;

image/x-vnd.adobe.air.bitmap;

application/x-vnd.adobe.air.file-list.

MIME, , .
. , ,
dataTransfer, .

23.11.2012.

664

ACTIONSCRIPT 3.0
AIR

. ,
. File
. .
HTML
669.

HTML
Adobe AIR 1.0

dataTransfer.effectAllowed dragstart.
:

"none"

"copy"

, .

"link"

,
.

"move"

"copyLink"

"copyMove"

"linkMove"

"all"

, . All
, .

dataTransfer.dropEffect,
, .
, , ,
. unavailable.
, .
dropEffect dragover dragenter:
function doDragStart(event) {
event.dataTransfer.setData("text/plain","Text to drag");
event.dataTransfer.effectAllowed = "copyMove";
}
function doDragOver(event) {
event.dataTransfer.dropEffect = "copy";
}
function doDragEnter(event) {
event.dataTransfer.dropEffect = "copy";
}

23.11.2012.

665

ACTIONSCRIPT 3.0
AIR

. dropEffect dragenter,
, dragover ( ).
dropEffect.

HTML-
Adobe AIR 1.0
HTML- .
, , CSS -webkit-user-select webkit-user-drag.
dragstart.
setData() dataTransfer
.
, -
dataTransfer.effectAllowed ,
dragstart. . ,
- copy, link, "copyLink".


Flash Player 9 , Adobe AIR 1.0
dragstart
dataTransfer. dataTransfer.setData() ,
MIME .
, imageOfGeorge,
dragstart.
, ,
.
function dragStartHandler(event){
event.dataTransfer.effectAllowed = "copy";
var dragImage = document.getElementById("imageOfGeorge");
var dragFile = new air.File(dragImage.src);
event.dataTransfer.setData("text/plain","A picture of George");
event.dataTransfer.setData("image/x-vnd.adobe.air.bitmap", dragImage);
event.dataTransfer.setData("application/x-vnd.adobe.air.file-list",
new Array(dragFile));
}

. setData() dataTransfer
- .

23.11.2012.

666

ACTIONSCRIPT 3.0
AIR

HTML-
Adobe AIR 1.0
. ,
,
contenteditable. .
designMode "on".

dragenter, dragover drop , .


Adobe AIR 1.0
.
HTML-, ,
dragenter dragover. preventDefault()
.
.


Adobe AIR 1.0
ondrop:
function doDrop(event){
droppedText = event.dataTransfer.getData("text/plain");
}

dataTransfer.getData()
MIME . , ,
types dataTransfer. types MIME
.
dragenter dragover ,
. API, .
.

:
HTML
Adobe AIR 1.0
, ,
.

23.11.2012.

667

ACTIONSCRIPT 3.0
AIR

, .
div,
.
preventDefault() ,
dragenter dragover. drop
HTML () .
<html>
<head>
<title>Drag-and-drop</title>
<script language="javascript" type="text/javascript" src="AIRAliases.js"></script>
<script language="javascript">
function init(){
var target = document.getElementById('target');
target.addEventListener("dragenter", dragEnterOverHandler);
target.addEventListener("dragover", dragEnterOverHandler);
target.addEventListener("drop", dropHandler);
var source = document.getElementById('source');
source.addEventListener("dragstart", dragStartHandler);
source.addEventListener("dragend", dragEndHandler);
emptyRow = document.getElementById("emptyTargetRow");
}
function dragStartHandler(event){
event.dataTransfer.effectAllowed = "copy";
}
function dragEndHandler(event){
air.trace(event.type + ": " + event.dataTransfer.dropEffect);
}
function dragEnterOverHandler(event){
event.preventDefault();
}
var emptyRow;
function dropHandler(event){
for(var prop in event){
air.trace(prop + " = " + event[prop]);
}
var row = document.createElement('tr');
row.innerHTML = "<td>" + event.dataTransfer.getData("text/plain") + "</td>" +
"<td>" + event.dataTransfer.getData("text/html") + "</td>" +
"<td>" + event.dataTransfer.getData("text/uri-list") + "</td>" +
"<td>" + event.dataTransfer.getData("application/x-vnd.adobe.air.file-list") +
"</td>";
var imageCell = document.createElement('td');
if((event.dataTransfer.types.toString()).search("image/x-vnd.adobe.air.bitmap") > 1){
imageCell.appendChild(event.dataTransfer.getData("image/xvnd.adobe.air.bitmap"));
}
row.appendChild(imageCell);

23.11.2012.

668

ACTIONSCRIPT 3.0
AIR

var parent = emptyRow.parentNode;


parent.insertBefore(row, emptyRow);
}
</script>
</head>
<body onLoad="init()" style="padding:5px">
<div>
<h1>Source</h1>
<p>Items to drag:</p>
<ul id="source">
<li>Plain text.</li>
<li>HTML <b>formatted</b> text.</li>
<li>A <a href="http://www.adobe.com">URL.</a></li>
<li><img src="icons/AIRApp_16.png" alt="An image"/></li>
<li style="-webkit-user-drag:none;">
Uses "-webkit-user-drag:none" style.
</li>
<li style="-webkit-user-select:none;">
Uses "-webkit-user-select:none" style.
</li>
</ul>
</div>
<div id="target" style="border-style:dashed;">
<h1 >Target</h1>
<p>Drag items from the source list (or elsewhere).</p>
<table id="displayTable" border="1">
<tr><th>Plain text</th><th>Html text</th><th>URL</th><th>File list</th><th>Bitmap
Data</th></tr>
<tr
id="emptyTargetRow"><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</
td></tr>
</table>
</div>
</div>
</body>
</html>


HTML
Adobe AIR 1.0
File,
AIR. File
. (
.) -
nativeDragDrop AIR HTMLLoader.

23.11.2012.

669

ACTIONSCRIPT 3.0
AIR

, , ,
drop . , ,
HTMLLoader ( HTML- AIR),
HTML, drop -
.

HTMLLoader, window.htmlLoader:
window.htmlLoader.addEventListener("nativeDragDrop",function(event){
var filelist = event.clipboard.getData(air.ClipboardFormats.FILE_LIST_FORMAT);
air.trace(filelist[0].url);
});

,
(http://localhost/).
HTMLLoader nativeDragDrop URL- .
<html>
<head>
<title>Drag-and-drop in a remote sandbox</title>
<script language="javascript" type="text/javascript" src="AIRAliases.js"></script>
<script language="javascript">
window.htmlLoader.addEventListener("nativeDragDrop",function(event){
var filelist = event.clipboard.getData(air.ClipboardFormats.FILE_LIST_FORMAT);
air.trace(filelist[0].url);
});
</script>
</head>
<body>
<iframe src="child.html"
sandboxRoot="http://localhost/"
documentRoot="app:/"
frameBorder="0" width="100%" height="100%">
</iframe>
</body>
</html>


preventDefault() Event HTML dragenter dragover.
.
<html>
<head>
<title>Drag and drop target</title>
<script language="javascript" type="text/javascript">
function preventDefault(event){
event.preventDefault();
}
</script>
</head>
<body ondragenter="preventDefault(event)" ondragover="preventDefault(event)">
<div>
<h1>Drop Files Here</h1>
</div>
</body>
</html>

23.11.2012.

670

ACTIONSCRIPT 3.0
AIR


Adobe AIR 2
,
AIR. ,

- . - ,
, URL.
.
URLFilePromise AIR , URL.
URLFilePromise aircore AIR 2 SDK.
aircore.swc aircore.swf, frameworks/libs/air SDK.

IFilePromise ( flash.desktop ).
, ,
.
.
- .
(
).

, ,
:

AIR; AIR
.

.
Clipboard.supportsFilePromise, ,
. , ,
.


(Clipboard.generalClipboard).


flash.desktop.IFilePromise
air.desktop.URLFilePromise

23.11.2012.

671

ACTIONSCRIPT 3.0
AIR


Adobe AIR 2
URLFilePromise ,
, URL.
FILE_PROMISE_LIST.
, http://www.example.com/foo.txt,
bar.txt.
.
if( Clipboard.supportsFilePromise )
{
var filePromise:URLFilePromise = new URLFilePromise();
filePromise.request = new URLRequest("http://example.com/foo.txt");
filePromise.relativePath = "bar.txt";
var fileList:Array = new Array( filePromise );
var clipboard:Clipboard = new Clipboard();
clipboard.setData( ClipboardFormats.FILE_PROMISE_LIST_FORMAT, fileList );
NativeDragManager.doDrag( dragSource, clipboard );
}


, .
relativePath,
.
, ,
. HTML- article.html
.
images, .
if( Clipboard.supportsFilePromise )
{
//Create the promise objects
var filePromise:URLFilePromise = new URLFilePromise();
filePromise.request = new URLRequest("http://example.com/article.html");
filePromise.relativePath = "article.html";
var image1Promise:URLFilePromise = new URLFilePromise();
image1Promise.request = new URLRequest("http://example.com/images/img_1.jpg");
image1Promise.relativePath = "images/img_1.html";
var image2Promise:URLFilePromise = new URLFilePromise();
image2Promise.request = new URLRequest("http://example.com/images/img_2.jpg");
image2Promise.relativePath = "images/img_2.jpg";

//Put the promise objects onto the clipboard inside an array


var fileList:Array = new Array( filePromise, image1Promise, image2Promise );
var clipboard:Clipboard = new Clipboard();
clipboard.setData( ClipboardFormats.FILE_PROMISE_LIST_FORMAT, fileList );
//Start the drag operation
NativeDragManager.doDrag( dragSource, clipboard );
}

23.11.2012.

672

ACTIONSCRIPT 3.0
AIR

IFilePromise
Adobe AIR 2
,
URLFilePromise , IFilePromise .
IFilePromise , AIR
, .
IFilePromise AIR,
. IDataInput,
AIR . , URLFilePromise,
IFilePromise, URLStream.
AIR . IFilePromise
isAsync.
,
IEventDispatcher ( open, progress complete).
,
:

ByteArray ()
FileStream ( )
Socket ()
URLStream ()
IFilePromise, .

open():IDataInput ,
. IDataInput. ,
IEventDispatcher (.

675).

get relativePath():String , .
,
. ,
, File.separator
. ,
.

get isAsync():Boolean AIR

close():void , (
, ).
.

reportError( e:ErrorEvent ):void

.
IFilePromise ,
. , -
.

23.11.2012.

673

ACTIONSCRIPT 3.0
AIR


Adobe AIR 2
IFilePromise ,
(, ByteArray FileStream).
ByteArray, open().
package
{
import
import
import
import

flash.desktop.IFilePromise;
flash.events.ErrorEvent;
flash.utils.ByteArray;
flash.utils.IDataInput;

public class SynchronousFilePromise implements IFilePromise


{
private const fileSize:int = 5000; //size of file data
private var filePath:String = "SynchronousFile.txt";
public function get relativePath():String
{
return filePath;
}
public function get isAsync():Boolean
{
return false;
}
public function open():IDataInput
{
var fileContents:ByteArray = new ByteArray();
//Create some arbitrary data for the file
for( var i:int = 0; i < fileSize; i++ )
{
fileContents.writeUTFBytes( 'S' );
}
//Important: the ByteArray is read from the current position
fileContents.position = 0;
return fileContents;
}
public function close():void
{
//Nothing needs to be closed in this case.
}
public function reportError(e:ErrorEvent):void
{
trace("Something went wrong: " + e.errorID + " - " + e.type + ", " + e.text );
}
}
}

23.11.2012.

674

ACTIONSCRIPT 3.0
AIR

.
,
. ,
, .

.
, .


Adobe AIR 2
isAsync IFilePromise
true, , open(),
IEventDispatcher. ,
. ,
progress FileStream URLStream, socketData
Socket. .
.

Event.OPEN .
ProgressEvent.PROGRESS .
.

ProgressEvent.SOCKET_DATA . socketData
.
progress. , ,
.

Event.COMPLETE , .
Event.CLOSE , .
close, complete.

IOErrorEvent.IOERROR .
IFilePromise close().

SecurityErrorEvent.SECURITY_ERROR .
IFilePromise close().

HTTPStatusEvent.HTTP_STATUS httpResponseStatus,
, ,
( 404). , HTTP.

HTTPStatusEvent.HTTP_RESPONSE_STATUS httpStatus,
, .
, HTTP.
:
1 open
2 progress socketData,
3 complete close.

. (FileStream, Socket URLStream)


.

23.11.2012.

675

ACTIONSCRIPT 3.0
AIR


. ByteArray ( IDataInput)
IEventDispatcher.
progress, .
complete.
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.ProgressEvent;
import flash.events.TimerEvent;
import flash.utils.ByteArray;
import flash.utils.Timer;
[Event(name="open", type="flash.events.Event.OPEN")]
[Event(name="complete", type="flash.events.Event.COMPLETE")]
[Event(name="progress", type="flash.events.ProgressEvent")]
[Event(name="ioError", type="flash.events.IOErrorEvent")]
[Event(name="securityError", type="flash.events.SecurityErrorEvent")]
public class AsyncDataProvider extends ByteArray implements IEventDispatcher
{
private var dispatcher:EventDispatcher = new EventDispatcher();
public var fileSize:int = 0; //The number of characters in the file
private const chunkSize:int = 1000; //Amount of data written per event
private var dispatchDataTimer:Timer = new Timer( 100 );
private var opened:Boolean = false;
public function AsyncDataProvider()
{
super();
dispatchDataTimer.addEventListener( TimerEvent.TIMER, generateData );
}
public function begin():void{
dispatchDataTimer.start();
}
public function end():void
{
dispatchDataTimer.stop();
}
private function generateData( event:Event ):void
{
if( !opened )
{
var open:Event = new Event( Event.OPEN );
dispatchEvent( open );
opened = true;
}
else if( position + chunkSize < fileSize )
{
for( var i:int = 0; i <= chunkSize; i++ )
{
writeUTFBytes( 'A' );

23.11.2012.

676

ACTIONSCRIPT 3.0
AIR

}
//Set position back to the start of the new data
this.position -= chunkSize;
var progress:ProgressEvent =
new ProgressEvent( ProgressEvent.PROGRESS, false, false, bytesAvailable,
bytesAvailable + chunkSize);
dispatchEvent( progress )
}
else
{
var complete:Event = new Event( Event.COMPLETE );
dispatchEvent( complete );
}
}
//IEventDispatcher implementation
public function addEventListener(type:String, listener:Function,
useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
dispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
public function removeEventListener(type:String, listener:Function,
useCapture:Boolean=false):void
{
dispatcher.removeEventListener( type, listener, useCapture );
}
public function dispatchEvent(event:Event):Boolean
{
return dispatcher.dispatchEvent( event );
}
public function hasEventListener(type:String):Boolean
{
return dispatcher.hasEventListener( type );
}
public function willTrigger(type:String):Boolean
{
return dispatcher.willTrigger( type );
}
}
}

. AsyncDataProvider ByteArray,
EventDispatcher. IEventDispatcher,
EventDispatcher IEventDispatcher
. EventDispatcher IDataInput (
).
IFilePromise .
, isAsync true open()
:

23.11.2012.

677

ACTIONSCRIPT 3.0
AIR

package
{
import
import
import
import

flash.desktop.IFilePromise;
flash.events.ErrorEvent;
flash.events.EventDispatcher;
flash.utils.IDataInput;

public class AsynchronousFilePromise extends EventDispatcher implements IFilePromise


{
private var fileGenerator:AsyncDataProvider;
private const fileSize:int = 5000; //size of file data
private var filePath:String = "AsynchronousFile.txt";
public function get relativePath():String
{
return filePath;
}
public function get isAsync():Boolean
{
return true;
}
public function open():IDataInput
{
fileGenerator = new AsyncDataProvider();
fileGenerator.fileSize = fileSize;
fileGenerator.begin();
return fileGenerator;
}
public function close():void
{
fileGenerator.end();
}
public function reportError(e:ErrorEvent):void
{
trace("Something went wrong: " + e.errorID + " - " + e.type + ", " + e.text );
}
}
}

23.11.2012.

678

679

36.
Flash Player 9 , Adobe AIR 1.0
- Flex Flash Player
API-.
, , Adobe AIR
API-.


Flash Player 9 , Adobe AIR 1.0
AIR .
Adobe Developer Connection:

AIR (Flex)
AIR (Flash)
,
. NativeMenu ( Mac
OS X), ( Windows Linux), .
AIR ,
Flash Player ,
Command . (
AIR .)


Flash Player 9 , Adobe AIR 1.0
.

flash.display

NativeMenu

NativeMenuItem

ContextMenu

ContextMenuItem

Event

ContextMenuEvent

flash.ui

flash.events

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
AIR .

Command SWF- HTML-.


Flash Player .
ContextMenu ContextMenuItem.
, , .
AIR NativeMenu
ContextMenu. HTML- AIR
WebKit HTML JavaScript.
( AIR) ,
. Mac OS X Windows Linux.
Mac OS X . API-
AIR .
. .
( AIR) .
NativeMenu menu
NativeWindow. Windows Linux, Mac OS X.
, Chrome.
Dock ( AIR)

Dock Mac OS X
Windows. Dock NativeMenu. Mac OS
X . Windows Linux
.
( AIR) AIR ,
.
display() NativeMenu.

Flash HTML.
, MXML, ActionScript JavaScript ( AIR).
.
Flex Adobe Flex Flex. Flex

, , . Flex
, Chrome. Flex ,
MXML. Flex Framework,
Flex, .
( AIR)
, AIR:

Mac OS X
Dock Mac OS X
HTML-
23.11.2012.

680

ACTIONSCRIPT 3.0

TextField ( TextField)


Flash Player 9 , Adobe AIR 1.0
SWF- - InteractiveObject .
contextMenu. ,
, , , . AIR ,
contextMenu, NativeMenu ContextMenu.
Flash Player ContextMenu.
, ,
ContextMenu ContextMenuItem; .
, ContextMenuEvent, ,
contextMenuOwner , , mouseTarget
, .
NativeMenuEvent.
, :
var sprite:Sprite = new Sprite();
sprite.contextMenu = createContextMenu()
private function createContextMenu():ContextMenu{
var editContextMenu:ContextMenu = new ContextMenu();
var cutItem:ContextMenuItem = new ContextMenuItem("Cut")
cutItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, doCutCommand);
editContextMenu.customItems.push(cutItem);
var copyItem:ContextMenuItem = new ContextMenuItem("Copy")
copyItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, doCopyCommand);
editContextMenu.customItems.push(copyItem);
var pasteItem:ContextMenuItem = new ContextMenuItem("Paste")
pasteItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, doPasteCommand);
editContextMenu.customItems.push(pasteItem);
return editContextMenu
}
private function doCutCommand(event:ContextMenuEvent):void{trace("cut");}
private function doCopyCommand(event:ContextMenuEvent):void{trace("copy");}
private function doPasteCommand(event:ContextMenuEvent):void{trace("paste");}

. SWF-, ,
AIR .
Flash Player
SWF- .
, .
showDefaultContextMenu false,
.

23.11.2012.

681

ACTIONSCRIPT 3.0


ContextMenu, hideBuiltInItems()
contextMenu DisplayObject.
, :
var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x =
square.y = 10;
addChild(square);
var menuItem:ContextMenuItem = new ContextMenuItem("Change Color");
menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,changeColor);
var customContextMenu:ContextMenu = new ContextMenu();
customContextMenu.hideBuiltInItems();
customContextMenu.customItems.push(menuItem);
square.contextMenu = customContextMenu;
function changeColor(event:ContextMenuEvent):void
{
square.transform.colorTransform = getRandomColor();
}
function getRandomColor():ColorTransform
{
return new ColorTransform(Math.random(), Math.random(), Math.random(),1,(Math.random() *
512) - 255, (Math.random() * 512) -255, (Math.random() * 512) - 255, 0);
}

(AIR)
Adobe AIR 1.0
. NativeMenu
NativeMenuItem. NativeMenuItem, , ,
NativeMenu. ()
. ( , .)

23.11.2012.

682

683

ACTIONSCRIPT 3.0

. ,
, .
, , .
.
NativeMenu

Root Menu
NativeMenuItem

File

NativeMenu

File Menu

NativeMenuItem

New

NativeMenuItem

Save

NativeMenuItem

Open Recent

NativeMenu

NativeMenuItem
NativeMenu

Open Recent Menu

NativeMenuItem

GreatGatsby.pdf

NativeMenuItem

WarAndPeace.pdf

NativeMenuItem

Iliad.pdf

Edit
Edit Menu

NativeMenuItem

Copy

NativeMenuItem

Paste

NativeMenuItem

Separator

NativeMenuItem

Preferences

NativeMenu NativeMenuItem. NativeMenuItem


, ,
. NativeMenu . NativeMenuItem
NativeMenu submenu NativeMenuItem.
, , . :
(AIR) 691.


Adobe AIR 1.0
NativeMenu NativeMenuItem preparing, displaying select:
Preparing:
preparing .
.

23.11.2012.

ACTIONSCRIPT 3.0

. preparing Adobe AIR 2.6 .


Displaying ():
displaying .

preparing displaying
. , displaying
, .
, preparing, ,
, select .
target currentTarget ,
( ).
preparing displaying.
.
: -, select

. ,
select.
select
. select ,
. select
target .
, currentTarget .
. ContextMenu ContextMenuItem menuItemSelect
menuSelect, select, preparing displaying.

(AIR)
Adobe AIR 1.0
( ).
select ,
. , , ,
.
: , ,
-, . ,
keyEquivalent .
Shift .
Mac OS X ommand (Keyboard.COMMAND). Windows
Linux trl (Keyboard.CONTROL).
. -
keyEquivalentModifiers. .
, , ,
keyEquivalent, , Shift .
- Keyboard.
.
.

23.11.2012.

684

ACTIONSCRIPT 3.0

. Keyboard.COMMAND Windows,
.
Ctrl.
, Ctrl+Shift+G:
var item:NativeMenuItem = new NativeMenuItem("Ungroup");
item.keyEquivalent = "G";

Ctrl+Shift+G
:
var item:NativeMenuItem = new NativeMenuItem("Ungroup");
item.keyEquivalent = "G";
item.keyEquivalentModifiers = [Keyboard.CONTROL];

. .
,
, .

(AIR)
Adobe AIR 1.0
. Linux, Mac OS
X Windows ,
.
Mac OS X Return.
mnemonicIndex .
Windows .
, ,
. (,
), .
,
, .
, .
Linux .
mnemonicIndex , .
.
0. ,
r, mnemonicIndex 2.
var item:NativeMenuItem = new NativeMenuItem("Format");
item.mnemonicIndex = 2;


Adobe AIR 1.0
: checked enabled:
checked true .

23.11.2012.

685

ACTIONSCRIPT 3.0

var item:NativeMenuItem = new NativeMenuItem("Format");


item.checked = true;

enabled true false, .

select.
var item:NativeMenuItem = new NativeMenuItem("Format");
item.enabled = false;


Adobe AIR 1.0
data NativeMenuItem . ,
File
.
var file:File = File.applicationStorageDirectory.resolvePath("GreatGatsby.pdf")
var menuItem:NativeMenuItem = docMenu.addItem(new NativeMenuItem(file.name));
menuItem.data = file;

(AIR)
Adobe AIR 1.0
, , AIR.


Adobe AIR 1.0
NativeMenu, ,
NativeMenu:
var root:NativeMenu = new NativeMenu();

, ,
. ,
, -.
. ,
, ,
addItemAt() .
, , , .
:

, ( Mac OS),
( )

23.11.2012.

686

ACTIONSCRIPT 3.0

var root:NativeMenu = new NativeMenu();


if (NativeApplication.supportsMenu)
{
NativeApplication.nativeApplication.menu = root;
}
else if (NativeWindow.supportsMenu)
{
nativeWindow.menu = root;
}

. Mac OS .
NativeMenu menu NativeApplication, .
, .
Adobe Flex FlexNativeMenu, ,
. Flex Framework, FlexNativeMenu
NativeMenu.

interactiveObject.contextMenu = root;

Dock
, ( Mac OS),
( )
if (NativeApplication.supportsSystemTrayIcon)
{
SystemTrayIcon(NativeApplication.nativeApplication.icon).menu = root;
}
else if (NativeApplication.supportsDockIcon)
{
DockIcon(NativeApplication.nativeApplication.icon).menu = root;
}

. Mac OS X Dock.
NativeMenu menu DockIcon, .
.

root.display(stage, x, y);


AIR


Adobe AIR 1.0
NativeMenuItem ,
NativeMenu, submenu . AIR
.
addSubmenu():

23.11.2012.

687

ACTIONSCRIPT 3.0

var editMenuItem:NativeMenuItem = root.addSubmenu(new NativeMenu(), "Edit");

submenu :
var editMenuItem:NativeMenuItem = root.addItem("Edit", false);
editMenuItem.submenu = new NativeMenu();


Adobe AIR 1.0
NativeMenuItem ,
, :
var copy:NativeMenuItem = new NativeMenuItem("Copy", false);
copy.addEventListener(Event.SELECT, onCopyCommand);
editMenu.addItem(copy);

select - ( ). select
.
. , -,
select, .

-
Adobe AIR 1.0
- NativeMenuItem isSeparator
true . :
var separatorA:NativeMenuItem = new NativeMenuItem("A", true);
editMenu.addItem(separatorA);

- , .

HTML (AIR)
Adobe AIR 1.0
HTML-, HTMLLoader,
contextmenu.
, (
). ,
contextmenu preventDefault() :
function showContextMenu(event){
event.preventDefault();
}

DHTML-
AIR. ,
display() HTML contextmenu:

23.11.2012.

688

ACTIONSCRIPT 3.0

<html>
<head>
<script src="AIRAliases.js" language="JavaScript" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function showContextMenu(event){
event.preventDefault();
contextMenu.display(window.nativeWindow.stage, event.clientX, event.clientY);
}
function createContextMenu(){
var menu = new air.NativeMenu();
var command = menu.addItem(new air.NativeMenuItem("Custom command"));
command.addEventListener(air.Event.SELECT, onCommand);
return menu;
}
function onCommand(){
air.trace("Context command invoked.");
}
var contextMenu = createContextMenu();
</script>
</head>
<body>
<p oncontextmenu="showContextMenu(event)" style="-khtml-user-select:auto;">Custom context
menu.</p>
</body>
</html>

(AIR)
Adobe AIR 1.0
NativeMenu .
display(). ,

.
, NativeMenu popupMenu,
:
private function onMouseClick(event:MouseEvent):void {
popupMenu.display(event.target.stage, event.stageX, event.stageY);
}

. .
display().

23.11.2012.

689

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, .


Flash Player 9 , Adobe AIR 1.0

.

NativeMenu (AIR)

Event.PREPARING (Adobe AIR 2.6 )


Event.DISPLAYING
Event.SELECT ( )

NativeMenuItem (AIR)

Event.PREPARING (Adobe AIR 2.6 )


Event.SELECT
Event.DISPLAYING ( )

ContextMenu

ContextMenuEvent.MENU_SELECT

ContextMenuItem

ContextMenuEvent.MENU_ITEM_SELECT
Event.SELECT (AIR)


Adobe AIR 1.0
NativeMenuItem
select:
var menuCommandX:NativeMenuItem = new NativeMenuItem("Command X");
menuCommandX.addEventListener(Event.SELECT, doCommandX)

select , select
. , ,
target . ,
:

23.11.2012.

690

ACTIONSCRIPT 3.0

var colorMenuItem:NativeMenuItem = new NativeMenuItem("Choose a color");


var colorMenu:NativeMenu = new NativeMenu();
colorMenuItem.submenu = colorMenu;
var red:NativeMenuItem = new NativeMenuItem("Red");
var green:NativeMenuItem = new NativeMenuItem("Green");
var blue:NativeMenuItem = new NativeMenuItem("Blue");
colorMenu.addItem(red);
colorMenu.addItem(green);
colorMenu.addItem(blue);
if(NativeApplication.supportsMenu){
NativeApplication.nativeApplication.menu.addItem(colorMenuItem);
NativeApplication.nativeApplication.menu.addEventListener(Event.SELECT, colorChoice);
} else if (NativeWindow.supportsMenu){
var windowMenu:NativeMenu = new NativeMenu();
this.stage.nativeWindow.menu = windowMenu;
windowMenu.addItem(colorMenuItem);
windowMenu.addEventListener(Event.SELECT, colorChoice);
}
function colorChoice(event:Event):void {
var menuItem:NativeMenuItem = event.target as NativeMenuItem;
trace(menuItem.label + " has been selected");
}

ContextMenuItem, select,
menuItemSelect. menuItemSelect ,
, .


Adobe AIR 1.0
displaying,
. displaying ,
.
menuSelect ContextMenu.
AIR 2.6 preparing
.

:
(AIR)
Adobe AIR 1.0
, , (AIR)
682.

23.11.2012.

691

ACTIONSCRIPT 3.0

Windows, , Mac OS
X, .
MenuExample supportsMenu NativeWindow NativeApplication.
NativeWindow.supportsMenu true, NativeMenu ,
. NativeApplication.supportsMenu true,

Mac OS X.
. select
. , , , ,
select. displaying .

Documents ( ). ,
displaying .
package {
import
import
import
import
import
import
import

flash.display.NativeMenu;
flash.display.NativeMenuItem;
flash.display.NativeWindow;
flash.display.Sprite;
flash.events.Event;
flash.filesystem.File;
flash.desktop.NativeApplication;

public class MenuExample extends Sprite


{
private var recentDocuments:Array =
new Array(new File("app-storage:/GreatGatsby.pdf"),
new File("app-storage:/WarAndPeace.pdf"),
new File("app-storage:/Iliad.pdf"));
public function MenuExample()
{
var fileMenu:NativeMenuItem;
var editMenu:NativeMenuItem;
if (NativeWindow.supportsMenu){
stage.nativeWindow.menu = new NativeMenu();
stage.nativeWindow.menu.addEventListener(Event.SELECT, selectCommandMenu);
fileMenu = stage.nativeWindow.menu.addItem(new NativeMenuItem("File"));
fileMenu.submenu = createFileMenu();
editMenu = stage.nativeWindow.menu.addItem(new NativeMenuItem("Edit"));
editMenu.submenu = createEditMenu();
}
if (NativeApplication.supportsMenu){
NativeApplication.nativeApplication.menu.addEventListener(Event.SELECT,
selectCommandMenu);
fileMenu = NativeApplication.nativeApplication.menu.addItem(new
NativeMenuItem("File"));
fileMenu.submenu = createFileMenu();
editMenu = NativeApplication.nativeApplication.menu.addItem(new
NativeMenuItem("Edit"));
editMenu.submenu = createEditMenu();
}
}

23.11.2012.

692

ACTIONSCRIPT 3.0

public function createFileMenu():NativeMenu {


var fileMenu:NativeMenu = new NativeMenu();
fileMenu.addEventListener(Event.SELECT, selectCommandMenu);
var newCommand:NativeMenuItem = fileMenu.addItem(new NativeMenuItem("New"));
newCommand.addEventListener(Event.SELECT, selectCommand);
var saveCommand:NativeMenuItem = fileMenu.addItem(new NativeMenuItem("Save"));
saveCommand.addEventListener(Event.SELECT, selectCommand);
var openRecentMenu:NativeMenuItem =
fileMenu.addItem(new NativeMenuItem("Open Recent"));
openRecentMenu.submenu = new NativeMenu();
openRecentMenu.submenu.addEventListener(Event.DISPLAYING,
updateRecentDocumentMenu);
openRecentMenu.submenu.addEventListener(Event.SELECT, selectCommandMenu);
return fileMenu;
}
public function createEditMenu():NativeMenu {
var editMenu:NativeMenu = new NativeMenu();
editMenu.addEventListener(Event.SELECT, selectCommandMenu);
var copyCommand:NativeMenuItem = editMenu.addItem(new NativeMenuItem("Copy"));
copyCommand.addEventListener(Event.SELECT, selectCommand);
copyCommand.keyEquivalent = "c";
var pasteCommand:NativeMenuItem =
editMenu.addItem(new NativeMenuItem("Paste"));
pasteCommand.addEventListener(Event.SELECT, selectCommand);
pasteCommand.keyEquivalent = "v";
editMenu.addItem(new NativeMenuItem("", true));
var preferencesCommand:NativeMenuItem =
editMenu.addItem(new NativeMenuItem("Preferences"));
preferencesCommand.addEventListener(Event.SELECT, selectCommand);
return editMenu;
}
private function updateRecentDocumentMenu(event:Event):void {
trace("Updating recent document menu.");
var docMenu:NativeMenu = NativeMenu(event.target);
for each (var item:NativeMenuItem in docMenu.items) {
docMenu.removeItem(item);
}
for each (var file:File in recentDocuments) {
var menuItem:NativeMenuItem =
docMenu.addItem(new NativeMenuItem(file.name));
menuItem.data = file;
menuItem.addEventListener(Event.SELECT, selectRecentDocument);
}
}
private function selectRecentDocument(event:Event):void {
trace("Selected recent document: " + event.target.data.name);
}

23.11.2012.

693

ACTIONSCRIPT 3.0

private function selectCommand(event:Event):void {


trace("Selected command: " + event.target.label);
}
private function selectCommandMenu(event:Event):void {
if (event.currentTarget.parent != null) {
var menuItem:NativeMenuItem =
findItemForMenu(NativeMenu(event.currentTarget));
if (menuItem != null) {
trace("Select event for \"" +
event.target.label +
"\" command handled by menu: " +
menuItem.label);
}
} else {
trace("Select event for \"" +
event.target.label +
"\" command handled by root menu.");
}
}
private function findItemForMenu(menu:NativeMenu):NativeMenuItem {
for each (var item:NativeMenuItem in menu.parent.items) {
if (item != null) {
if (item.submenu == menu) {
return item;
}
}
}
return null;
}
}
}

23.11.2012.

694

695

37. AIR
Adobe AIR 1.0
, Mac OS X,
. Adobe AIR
NativeApplication.nativeApplication.icon.

(Flex)
(Flash)


flash.desktop.NativeApplication
flash.desktop.DockIcon
flash.desktop.SystemTrayIcon


Adobe AIR 1.0
AIR NativeApplication.nativeApplication.icon .
DockIcon SystemTrayIcon . ,
InteractiveIcon AIR ,
NativeApplication.supportsDockIcon NativeApplication.supportsSystemTrayIcon.
InteractiveIcon width, height bitmaps,
. DockIcon SystemTrayIcon
.
,
, NativeApplication.nativeApplication.icon.bitmaps.
.
- bitmaps
. AIR ,
, .
, :
NativeApplication.nativeApplication.icon.bitmaps =
[bmp16x16.bitmapData, bmp128x128.bitmapData];

, ,
bitmaps. , enterFrame
timer.
Windows Linux
Mac OS X, bitmaps .
NativeApplication.nativeApplication.icon.bitmaps = [];

23.11.2012.

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
AIR , NativeApplication.supportsDockIcon true.
NativeApplication.nativeApplication.icon (
).
. AIR Mac OS X.
,
.


Adobe AIR 1.0
, NativeMenu, ,
NativeApplication.nativeApplication.icon.menu.
.


Adobe AIR 1.0

NativeApplication.nativeApplication.icon.bounce(). bounce() priority
informational, . critical,
, . priority
NotificationType.
. , .


Adobe AIR 1.0
NativeApplication invoke.
, . invoke
.

23.11.2012.

696

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
AIR ,
NativeApplication.supportsSystemTrayIcon true,
Windows Linux. Windows Linux
. .
, BitmapData, bitmaps .
, , bitmaps.
bitmaps null.


Adobe AIR 1.0
, NativeMenu
NativeApplication.nativeApplication.icon.menu (
). .


Adobe AIR 1.0
, tooltip:
NativeApplication.nativeApplication.icon.tooltip = "Application name";


Adobe AIR 1.0
SystemTrayIcon, NativeApplication.nativeApplication.icon,
ScreenMouseEvent click, mouseDown, mouseUp, rightClick, rightMouseDown rightMouseUp.
, ,
.

:
Adobe AIR 1.0
AIR, ,
. ( visible true
; .)

23.11.2012.

697

ACTIONSCRIPT 3.0
AIR

package
{
import
import
import
import
import
import
import
import
import
import

flash.display.Loader;
flash.display.NativeMenu;
flash.display.NativeMenuItem;
flash.display.NativeWindow;
flash.display.Sprite;
flash.desktop.DockIcon;
flash.desktop.SystemTrayIcon;
flash.events.Event;
flash.net.URLRequest;
flash.desktop.NativeApplication;

public class SysTrayApp extends Sprite


{
public function SysTrayApp():void{
NativeApplication.nativeApplication.autoExit = false;
var icon:Loader = new Loader();
var iconMenu:NativeMenu = new NativeMenu();
var exitCommand:NativeMenuItem = iconMenu.addItem(new NativeMenuItem("Exit"));
exitCommand.addEventListener(Event.SELECT, function(event:Event):void {
NativeApplication.nativeApplication.icon.bitmaps = [];
NativeApplication.nativeApplication.exit();
});
if (NativeApplication.supportsSystemTrayIcon) {
NativeApplication.nativeApplication.autoExit = false;
icon.contentLoaderInfo.addEventListener(Event.COMPLETE, iconLoadComplete);
icon.load(new URLRequest("icons/AIRApp_16.png"));
var systray:SystemTrayIcon =
NativeApplication.nativeApplication.icon as SystemTrayIcon;
systray.tooltip = "AIR application";
systray.menu = iconMenu;
}
if (NativeApplication.supportsDockIcon){
icon.contentLoaderInfo.addEventListener(Event.COMPLETE,iconLoadComplete);
icon.load(new URLRequest("icons/AIRApp_128.png"));
var dock:DockIcon = NativeApplication.nativeApplication.icon as DockIcon;
dock.menu = iconMenu;
}
}
private function iconLoadComplete(event:Event):void
{
NativeApplication.nativeApplication.icon.bitmaps =
[event.target.content.bitmapData];
}
}
}

. Flex WindowedApplication
visible WindowedApplication false.
.

23.11.2012.

698

ACTIONSCRIPT 3.0
AIR

. AIRApp_16.png
AIRApp_128.png icons . ( ,
, AIR SDK.)


Adobe AIR 1.0
, , ,
, .
Mac OS X , .
Microsoft Windows Linux
.


Adobe AIR 1.0
, ,
, . Mac OS X
( 696). Windows Linux
, notifyUser() NativeWindow.
type, , :

NotificationType.CRITICAL: , .

NotificationType.INFORMATIONAL: , .

. Linux .
notifyUser() .
:
stage.nativeWindow.notifyUser(NotificationType.CRITICAL);

NativeWindow.notifyUser() ,
, . NativeWindow.supportsNotification
, .


Adobe AIR 1.0
Windows utility lightweight .
.

23.11.2012.

699

ACTIONSCRIPT 3.0
AIR

normal, ,
, ,
. , ,
autoExit NativeApplication false .
, <visible>false</visible>
<initalWindow> ( visible true
activate() ).
, , type NativeWindowInitOption,
, NativeWindowType.UTILITY
NativeWindowType.LIGHTWEIGHT.
Mac OS X .
, , .
nativeWindowDisplayState .
visible false:
private function preventMinimize(event:NativeWindowDisplayStateEvent):void{
if(event.afterDisplayState == NativeWindowDisplayState.MINIMIZED){
event.preventDefault();
event.target.visible = false;
}
}

Mac OS X visible false


. , .

23.11.2012.

700

701

38.
Flash Player 9 , Adobe AIR 1.0
Flash Player , FileReference.
Flash Player
.
Adobe AIR ,
Flash Player. API AIR ,
, . .


flash.net.FileReference
flash.net.FileReferenceList
flash.filesystem.File
flash.filesystem.FileStream

FileReference
Flash Player 9 , Adobe AIR 1.0
FileReference .
FileReference ,
.
FileReference , .
FileReference browse(), upload() download().
browse(), . upload()
. download()
. Flash Player 10 Adobe AIR 1.5 FileReference
load() save(). load() save()
.
URLLoader Loader .
. File, FileReference, FileStream
. File FileStream
AIR, Flash Player.

23.11.2012.

ACTIONSCRIPT 3.0

FileReference
Flash Player 9 , Adobe AIR 1.0
FileReference .
FileReference , , , , ,
.
. creator Mac OS.
null.
. extension Adobe AIR.
FileReference .

new, :
import flash.net.FileReference;
var fileRef:FileReference = new FileReference();

FileReferenceList.browse(), ,
.
FileReference, .
FileReference, .

FileReference.browse(),
.
FileReference.upload() FileReference.load().
FileReference.upload() .
FileReference.load() .

FileReference.download(). download() ,
.
.

FileReference.load(). ,
browse(). load()
browse() ( ).

FileReference.save().
.
.
. browse(), download() save(),
.
FileReference, name, size modificationDate ,
.

FileReference.browse() FileReferenceList.browse(),
.

FileReference.download(),
.
. FileReference.name.
, .

23.11.2012.

702

ACTIONSCRIPT 3.0

FileReference.browse(), FileReferenceList.browse(),
FileReference.download(), FileReference.load() FileReference.save()
SWF-,
.
SWF-
, , .
, SWF-,
.
. FileReference.


Flash Player 9 , Adobe AIR 1.0
FileReference.load() .
. FileReference.browse(),
. , Adobe AIR
.
FileReference.load() ,
. FileReference
.
FileReference .

open (Event.OPEN): .
progress (ProgressEvent.PROGRESS):
.

complete (Event.COMPLETE):
.

ioError (IOErrorEvent.IO_ERROR): , -
/ .
FileReference,
ByteArray data FileReference.
,
.

23.11.2012.

703

ACTIONSCRIPT 3.0

package
{
import
import
import
import
import
import

flash.display.Sprite;
flash.events.*;
flash.net.FileFilter;
flash.net.FileReference;
flash.net.URLRequest;
flash.utils.ByteArray;

public class FileReferenceExample1 extends Sprite


{
private var fileRef:FileReference;
public function FileReferenceExample1()
{
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, onFileSelected);
fileRef.addEventListener(Event.CANCEL, onCancel);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
onSecurityError);
var textTypeFilter:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)",
"*.txt;*.rtf");
fileRef.browse([textTypeFilter]);
}
public function onFileSelected(evt:Event):void
{
fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
fileRef.addEventListener(Event.COMPLETE, onComplete);
fileRef.load();
}
public function onProgress(evt:ProgressEvent):void
{
trace("Loaded " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes.");
}
public function onComplete(evt:Event):void
{
trace("File was successfully loaded.");
trace(fileRef.data);
}
public function onCancel(evt:Event):void
{
trace("The browse request was canceled by the user.");
}
public function onIOError(evt:IOErrorEvent):void
{
trace("There was an IO Error.");
}
public function onSecurityError(evt:Event):void
{
trace("There was a security error.");
}
}
}

23.11.2012.

704

ACTIONSCRIPT 3.0

FileReference fileRef,
browse(). browse() , .
onFileSelected().
progress complete, load() FileReference.
.
trace().
Adobe AIR FileStream .
. 740.


Flash Player 9 , Adobe AIR 1.0
FileReference.save() .
, ,
. .
FileReference .
. FileReference.save() ,
. .
, Adobe AIR
.
FileReference.save() . FileReference
.
FileReference .

select (Event.SELECT): ,
.

cancel (Event.CANCEL): ,
.

open (Event.OPEN): .
progress (ProgressEvent.PROGRESS):
.

complete (Event.COMPLETE):
.

ioError (IOErrorEvent.IO_ERROR): , -
/ .
, data FileReference.save(),
:

String, UTF-8.
XML, XML- .
ByteArray, -
.

, FileReference.save()
toString() String UTF-8.

toString() , .

23.11.2012.

705

ACTIONSCRIPT 3.0

data null, .
FileReference.load().

.
package
{
import
import
import
import
import
import

flash.display.Sprite;
flash.events.*;
flash.net.FileFilter;
flash.net.FileReference;
flash.net.URLRequest;
flash.utils.ByteArray;

public class FileReferenceExample2 extends Sprite


{
private var fileRef:FileReference;
public function FileReferenceExample2()
{
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, onFileSelected);
fileRef.addEventListener(Event.CANCEL, onCancel);
fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
onSecurityError);
var textTypeFilter:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)",
"*.txt;*.rtf");
fileRef.browse([textTypeFilter]);
}
public function onFileSelected(evt:Event):void
{
fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
fileRef.addEventListener(Event.COMPLETE, onComplete);
fileRef.load();
}
public function onProgress(evt:ProgressEvent):void
{
trace("Loaded " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes.");
}
public function onCancel(evt:Event):void
{
trace("The browse request was canceled by the user.");
}
public function onComplete(evt:Event):void
{
trace("File was successfully loaded.");
fileRef.removeEventListener(Event.SELECT, onFileSelected);
fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
fileRef.removeEventListener(Event.COMPLETE, onComplete);
fileRef.removeEventListener(Event.CANCEL, onCancel);
saveFile();
}
public function saveFile():void
{
fileRef.addEventListener(Event.SELECT, onSaveFileSelected);

23.11.2012.

706

ACTIONSCRIPT 3.0

fileRef.save(fileRef.data,"NewFileName.txt");
}
public function onSaveFileSelected(evt:Event):void
{
fileRef.addEventListener(ProgressEvent.PROGRESS, onSaveProgress);
fileRef.addEventListener(Event.COMPLETE, onSaveComplete);
fileRef.addEventListener(Event.CANCEL, onSaveCancel);
}
public function onSaveProgress(evt:ProgressEvent):void
{
trace("Saved " + evt.bytesLoaded + " of " + evt.bytesTotal + " bytes.");
}
public function onSaveComplete(evt:Event):void
{
trace("File saved.");
fileRef.removeEventListener(Event.SELECT, onSaveFileSelected);
fileRef.removeEventListener(ProgressEvent.PROGRESS, onSaveProgress);
fileRef.removeEventListener(Event.COMPLETE, onSaveComplete);
fileRef.removeEventListener(Event.CANCEL, onSaveCancel);
}
public function onSaveCancel(evt:Event):void
{
trace("The save request was canceled by the user.");
}
public function onIOError(evt:IOErrorEvent):void
{
trace("There was an IO Error.");
}
public function onSecurityError(evt:Event):void
{
trace("There was a security error.");
}
}
}

, onComplete(). onComplete()
saveFile(). saveFile()
FileReference.save(). FileReference.save() ,
.
.
Adobe AIR FileStream .
. 740.

23.11.2012.

707

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, browse(),
. FileReference.upload()
. FileReferenceList.browse(),
Flash Player FileReferenceList.fileList,
. FileReference.upload(),
.
. FileReference.browse() .
,
FileReferenceList.browse().

.
FileFilter browse().
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;
*.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)", "*.txt; *.rtf");
var allTypes:Array = new Array(imageTypes, textTypes);
var fileRef:FileReference = new FileReference();
fileRef.browse(allTypes);

,
Event.SELECT.
FileReference.browse(), -.
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
try
{
var success:Boolean = fileRef.browse();
}
catch (error:Error)
{
trace("Unable to browse for files.");
}
function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/fileUploadScript.cfm")
try
{
fileRef.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
function completeHandler(event:Event):void
{
trace("uploaded");
}

23.11.2012.

708

ACTIONSCRIPT 3.0

FileReference.upload(),
URLRequest.method URLRequest.data POST GET.
FileReference.upload()
.

open event (Event.OPEN): .

progress (ProgressEvent.PROGRESS):
.

complete (Event.COMPLETE):
.

httpStatus (HTTPStatusEvent.HTTP_STATUS):
HTTP.

httpResponseStatus (HTTPStatusEvent.HTTP_RESPONSE_STATUS): ,
upload() uploadUnencoded() HTTP Adobe AIR
.

securityError (SecurityErrorEvent.SECURITY_ERROR):
.

uploadCompleteData event (DataEvent.UPLOAD_COMPLETE_DATA):

ioError (IOErrorEvent.IO_ERROR):
:

-, Flash Player ,
.

SWF- , (
). Flash Player .

url . FileReference.upload()
HTTP HTTPS.
Flash Player ,
. SWF-,
Microsoft ActiveX, ,
, .
ActiveX,
.
ColdFusion,
Flash Player, , :
<cffile action="upload" filefield="Filedata" destination="#ExpandPath('./')#"
nameconflict="OVERWRITE" />

ColdFusion , Flash Player,


, ColdFusion, .
, .
. ,
, ,
, .

23.11.2012.

709

ACTIONSCRIPT 3.0

, .
10, , 200 ,
JPEG-, GIF- PNG-.
<?php
$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE)
{
move_uploaded_file($_FILES['Filedata']['tmp_name'],
"./temporary/".$_FILES['Filedata']['name']);
$type = exif_imagetype("./temporary/".$_FILES['Filedata']['name']);
if ($type == 1 || $type == 2 || $type == 3)
{
rename("./temporary/".$_FILES['Filedata']['name'],
"./images/".$_FILES['Filedata']['name']);
}
else
{
unlink("./temporary/".$_FILES['Filedata']['name']);
}
}
$directory = opendir('./images/');
$files = array();
while ($file = readdir($directory))
{
array_push($files, array('./images/'.$file, filectime('./images/'.$file)));
}
usort($files, sorter);
if (count($files) > $MAXIMUM_FILE_COUNT)
{
$files_to_delete = array_splice($files, 0, count($files) - $MAXIMUM_FILE_COUNT);
for ($i = 0; $i < count($files_to_delete); $i++)
{
unlink($files_to_delete[$i][0]);
}
}
print_r($files);
closedir($directory);
function sorter($a, $b)
{
if ($a[1] == $b[1])
{
return 0;
}
else
{
return ($a[1] < $b[1]) ? -1 : 1;
}
}
?>

POST GET.
POST ,
:

23.11.2012.

710

ACTIONSCRIPT 3.0

var fileRef:FileReference = new FileReference();


fileRef.addEventListener(Event.SELECT, selectHandler);
fileRef.addEventListener(Event.COMPLETE, completeHandler);
fileRef.browse();
function selectHandler(event:Event):void
{
var params:URLVariables = new URLVariables();
params.date = new Date();
params.ssid = "94103-1394-2345";
var request:URLRequest = new
URLRequest("http://www.yourdomain.com/FileReferenceUpload/fileupload.cfm");
request.method = URLRequestMethod.POST;
request.data = params;
fileRef.upload(request, "Custom1");
}
function completeHandler(event:Event):void
{
trace("uploaded");
}

URLVariables, ,
. ActionScript ,
, . ActionScript 3.0
URLRequest,
POST GET. , ,
. , (GET
POST), URLRequest.method URLRequestMethod.GET
URLRequestMethod.POST.
, ActionScript 3.0 Filedata
upload(), ,
Filedata Custom1.
Flash Player .
, true upload().
, ,
( ).
. Flash Player
Windows.
, , HTTP- POST
:

Content-Type ( ) multipart/form-data.

Content-Disposition ( ), name Filedata,

filename . name,
uploadDataFieldName FileReference.upload().

.
HTTP- POST:

23.11.2012.

711

ACTIONSCRIPT 3.0

POST /handler.asp HTTP/1.1


Accept: text/*
Content-Type: multipart/form-data;
boundary=----------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
User-Agent: Shockwave Flash
Host: www.mydomain.com
Content-Length: 421
Connection: Keep-Alive
Cache-Control: no-cache
------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
Content-Disposition: form-data; name="Filename"
sushi.jpg
------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
Content-Disposition: form-data; name="Filedata"; filename="sushi.jpg"
Content-Type: application/octet-stream
Test File
------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
Content-Disposition: form-data; name="Upload"
Submit Query
------------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
(actual file data,,,)

HTTP- POST POST: api_sig, api_key auth_token,


"photo".

23.11.2012.

712

ACTIONSCRIPT 3.0

POST /handler.asp HTTP/1.1


Accept: text/*
Content-Type: multipart/form-data;
boundary=----------Ij5ae0ae0KM7GI3KM7ei4cH2ei4gL6
User-Agent: Shockwave Flash
Host: www.mydomain.com
Content-Length: 421
Connection: Keep-Alive
Cache-Control: no-cache
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="Filename"
sushi.jpg
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="api_sig"
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="api_key"
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="auth_token"
XXXXXXXXXXXXXXXXXXXXXXX
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="photo"; filename="sushi.jpg"
Content-Type: application/octet-stream
(actual file data,,,)
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7
Content-Disposition: form-data; name="Upload"
Submit Query
------------Ij5GI3GI3ei4GI3ei4KM7GI3KM7KM7--


Flash Player 9 , Adobe AIR 1.0
,
FileReference.download() : request defaultFileName.
URLRequest, URL- .
. ,
. , defaultFileName,
URL-.
index.xml , SWF-.
var request:URLRequest = new URLRequest("index.xml");
var fileRef:FileReference = new FileReference();
fileRef.download(request);

currentnews.xml index.xml, defaultFileName,


.

23.11.2012.

713

ACTIONSCRIPT 3.0

var request:URLRequest = new URLRequest("index.xml");


var fileToDownload:FileReference = new FileReference();
fileToDownload.download(request, "currentnews.xml");

, .
defaultFileName , ,
, . ,
defaultFileName, ,
URL.
, .
download() URL,
. ActionScript 3.0
, ColdFusion.
package
{
import
import
import
import
import

flash.display.Sprite;
flash.net.FileReference;
flash.net.URLRequest;
flash.net.URLRequestMethod;
flash.net.URLVariables;

public class DownloadFileExample extends Sprite


{
private var fileToDownload:FileReference;
public function DownloadFileExample()
{
var request:URLRequest = new URLRequest();
request.url = "http://www.[yourdomain].com/downloadfile.cfm";
request.method = URLRequestMethod.GET;
request.data = new URLVariables("id=2");
fileToDownload = new FileReference();
try
{
fileToDownload.download(request, "file2.txt");
}
catch (error:Error)
{
trace("Unable to download file.");
}
}
}
}

ColdFusion (download.cfm),
URL.
<cfparam name="URL.id" default="1" />
<cfswitch expression="#URL.id#">
<cfcase value="2">
<cfcontent type="text/plain" file="#ExpandPath('two.txt')#" deletefile="No" />
</cfcase>
<cfdefaultcase>
<cfcontent type="text/plain" file="#ExpandPath('one.txt')#" deletefile="No" />
</cfdefaultcase>
</cfswitch>

23.11.2012.

714

ACTIONSCRIPT 3.0

FileReferenceList
Flash Player 9 , Adobe AIR 1.0
FileReferenceList
, .
FileReference.upload(), , .
FileFilter (imageFilter textFilter)
FileReferenceList.browse().
.
var imageFilter:FileFilter = new FileFilter("Image Files (*.jpg, *.jpeg, *.gif, *.png)",
"*.jpg; *.jpeg; *.gif; *.png");
var textFilter:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)", "*.txt; *.rtf");
var fileRefList:FileReferenceList = new FileReferenceList();
try
{
var success:Boolean = fileRefList.browse(new Array(imageFilter, textFilter));
}
catch (error:Error)
{
trace("Unable to browse for files.");
}

FileReferenceList
, FileReference.browse() ,
FileReferenceList .
FileReference.upload(), .

23.11.2012.

715

ACTIONSCRIPT 3.0

var fileRefList:FileReferenceList = new FileReferenceList();


fileRefList.addEventListener(Event.SELECT, selectHandler);
fileRefList.browse();
function selectHandler(event:Event):void
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/fileUploadScript.cfm");
var file:FileReference;
var files:FileReferenceList = FileReferenceList(event.target);
var selectedFileArray:Array = files.fileList;
for (var i:uint = 0; i < selectedFileArray.length; i++)
{
file = FileReference(selectedFileArray[i]);
file.addEventListener(Event.COMPLETE, completeHandler);
try
{
file.upload(request);
}
catch (error:Error)
{
trace("Unable to upload files.");
}
}
}
function completeHandler(event:Event):void
{
trace("uploaded");
}

Event.COMPLETE FileReference , Flash


Player completeHandler() .

API-
AIR
Adobe AIR 1.0
API Adobe AIR :

File;
FileMode;
FileStream.
API- ( ) :

, , ;
;
.

23.11.2012.

716

ACTIONSCRIPT 3.0

AIR
Adobe AIR 1.0
AIR
Adobe Developer Connection:

(Flash)
(Flex)
(Flex)
XML- (Flex)
(Flex)
Adobe AIR , , .
flash.filesystem. :
File

File

File . File
.

FileMode

FileMode , fileMode
open() openAsync() FileStream. fileMode
FileStream , , ,
.

FileStream

FileStream . File,
, FileStream,
.

File , :

File.copyTo() File.copyToAsync()

File.deleteDirectory() File.deleteDirectoryAsync()

File.deleteFile() File.deleteFileAsync()

File.getDirectoryListing() File.getDirectoryListingAsync()

File.moveTo() File.moveToAsync()

File.moveToTrash() File.moveToTrashAsync()

, FileStream ,
FileStream : open() openAsync().

( ).
.
addEventListener() File FileStream, .
, .
, , ,
, .

23.11.2012.

717

ACTIONSCRIPT 3.0

File AIR
Adobe AIR 1.0
File .
File FileReference. FileReference,
Adobe Flash AIR, . File ,
Flash ( SWF-
).

File
Adobe AIR 1.0
File :

, ,
, .



( )


File, ,
FileStream.
File .
.

File
Adobe AIR 1.0
File , :

nativePath

. , Windows
:\Sample directory\test.txt, Mac OS /Sample directory/test.txt. Windows
nativePath (\), Mac OS Linux
(/).

url

URL- , . , Windows
file:///c:/Sample%20directory/test.txt, Mac OS
file:///Sample%20directory/test.txt. file,
URL-, AIR URL 728

23.11.2012.

718

ACTIONSCRIPT 3.0

File Mac OS, Windows


Linux. :

File.applicationStorageDirectory ,

AIR.
. .
Android iOS
,
.

File.applicationDirectory , (
).
, . ,
. .

File.desktopDirectory .

, .

File.documentsDirectory .
, .

File.userDirectory . ,

.
. ,
, File.documentsDirectory, File.desktopDirectory
File.userDirectory .
. , Mac Windows
.
File.desktopDirectory .

, . resolvePath()
. , preferences.xml :
var prefsFile:File = File.applicationStorageDirectory;
prefsFile = prefsFile.resolvePath("preferences.xml");

File , ,
. , C:\Documents and Settings\joe\
Windows. File,
File.documentsDirectory.

23.11.2012.

719

ACTIONSCRIPT 3.0

Android

/data/data/

/data/data/air.applicationID/filename/Local Store

/mnt/sdcard

/mnt/sdcard

/data/data/applicationID/cache/FlashTmp.randomString

/mnt/sdcard

/var/mobile/Applications/uid/filename.app

/var/mobile/Applications/uid/Library/Application
Support/applicationID/Local Store

/var/mobile/Applications/uid/Documents

/private/var/mobile/Applications/uid/tmp/FlashTmpNNN

/opt/filename/share

/home/userName/.appdata/applicationID/Local Store

/home/userName/Desktop

/home/userName/Documents

/tmp/FlashTmp.randomString

/home/userName

/Applications/filename.app/Contents/Resources

3.2 )

iOS

Linux

Mac

/Users/userName/Library/Preferences/applicationid/Local Store (AIR

path/Library/Application Support/applicationid/Local Store (AIR 3.3

), path
/Users/userName/Library/Containers/bundle-id/Data (
) /Users/userName (

/Users/userName/Desktop

/Users/userName/Documents

/private/var/folders/JY/randomString/TemporaryItems/FlashTmp

/Users/userName

23.11.2012.

720

ACTIONSCRIPT 3.0

Windows

C:\Program Files\filename

C:\Documents and
settings\userName\ApplicationData\applicationID\Local Store

C:\Documents and settings\userName\Desktop

C:\Documents and settings\userName\My Documents

C:\Documents and settings\userName\Local


Settings\Temp\randomString.tmp

C:\Documents and settings\userName


. , , .
File.
AIR applicationID filename, , .
publisher ID,
. userName
, .

AIR for TV
y AIR for TV AIR
. AIR
. , AIR for TV
AIR.
AIR ,
ActionScript 3.0. . AIR for TV
ActionScript 3.0 .
AIR for TV
, .
ActionScript 3.0 :
/app/ , , AIR.
/app-storage/ , , AIR.
/home/ , .
/tmp/ , , AIR.
/volumes/ , , ,

, .
,
, ActionScript.
File.nativePath File.
.

23.11.2012.

721

722

ACTIONSCRIPT 3.0

File

File.nativePat
h
applicationDirectory

/app/

applicationStorageDirectory

/app-storage/

desktopDirectory

/home/


.
, ,
userDirectory documentsDirectory.

userDirectory

/home/


.
, ,
desktopDirectory documentsDirectory.

documentsDirectory

/home/


.
, ,
userDirectory desktopDirectory.

createTempDirectory()

/tmp/

. AIR for
TV
AIR.

AIR for TV.

File.createTempFile() /tmp/.

File.getRootDirectories() File. nativePath File


/. app, app-storage, home tmp.

StorageVolumeInfo.storageVolumeInfo.getStorageVolumes() Vector
StorageVolume. rootDirectory StorageVolume File.
nativePath File /volumes/.
/volumes/.

File,
Adobe AIR 1.0
File , .

Adobe AIR 1.0
File . File
AIR Test :
var file:File = File.userDirectory.resolvePath("AIR Test");


Adobe AIR 1.0
File . File
AIR Test :

23.11.2012.

ACTIONSCRIPT 3.0

var file:File = File.documentsDirectory.resolvePath("AIR Test");


Adobe AIR 1.0
File . File
AIR Test :
var file:File = File.desktopDirectory.resolvePath("AIR Test");


Adobe AIR 1.0
File . AIR ,
.
. ,
(, ). ,
File prefs.xml,
:
var file:File = File.applicationStorageDirectory;
file = file.resolvePath("prefs.xml");


.
.
File.applicationStorage URI app-storage:

Mac OS AIR:
AIR 3.2 : /Users/user name/Library/Preferences/applicationID/Local Store/
AIR 3.3 : path/Library/Application Support/applicationID/Local Store,
path /Users/username/Library/Containers/bundle-id/Data ( )
/Users/username ( )
(AIR 3.2):
/Users/babbage/Library/Preferences/com.example.TestApp/Local Store

Windows Documents and Settings, :


C:\Documents and Settings\ \Application Data\applicationID\Local Store\
:
C:\Documents and Settings\babbage\Application Data\com.example.TestApp\Local Store

Linux :
/home/ /.appdata/ /Local Store/

:
/home/babbage/.appdata/com.example.TestApp/Local Store

Android:
/data/data/androidPackageID/applicationID/Local Store

23.11.2012.

723

ACTIONSCRIPT 3.0

:
/data/data/air.com.example.TestApp/com.example.TestApp/Local Store

AIR for TV AIR for TV


721.
. ,
.
URL- ( url) File, File.applicationStorageDirectory,
URL- app-storage (. AIR URL-
728), :
var dir:File = File.applicationStorageDirectory;
dir = dir.resolvePath("preferences");
trace(dir.url); // app-storage:/preferences


Adobe AIR 1.0
File , (.. ).
File.applicationDirectory.
, . ,
File images :
var dir:File = File.applicationDirectory;
dir = dir.resolvePath("images");

URL- ( url) File, File.applicationDirectory,


URL- app (. AIR URL- 728),
:
var dir:File = File.applicationDirectory;
dir = dir.resolvePath("images");
trace(dir.url); // app:/images

. Android nativePath
. nativePath .
URL .

Adobe AIR 1.0
File.getRootDirectories() , C:,
Windows. Mac Linux
( /). StorageVolumeInfo.getStorageVolumes()
(.
738).
. Android .
File, /,
. , spaceAvailable 0.

23.11.2012.

724

ACTIONSCRIPT 3.0


Adobe AIR 1.0
File . nativePath
File, ( Windows):
var file:File = new File();
file.nativePath = "C:\\AIR Test";

: , .
, Windows.
, , File,
File.applicationStorageDirectory.
resolvePath() (. ).

Adobe AIR 1.0
resolvePath() . ,
File AIR Test .
var file:File = File.userDirectory;
file = file.resolvePath("AIR Test");

url File URL-, :


var urlStr:String = "file:///C:/AIR Test/";
var file:File = new File()
file.url = urlStr;

. 728.

Adobe AIR 1.0
File browseForDirectory(), ,
. browseForDirectory()
. File select,
, cancel, .
,
:
var file:File = new File();
file.addEventListener(Event.SELECT, dirSelected);
file.browseForDirectory("Select a directory");
function dirSelected(e:Event):void {
trace(file.nativePath);
}

. Android browseForDirectory() .
. cancel.
, , .

23.11.2012.

725

ACTIONSCRIPT 3.0

,
Adobe AIR 1.0
, , ,
currentDirectory InvokeEvent, .
. 943.

File,
Adobe AIR 1.0
, File.

Adobe AIR 1.0
: , .
, C:/foo.txt Windows.
, ,
File, File.applicationStorageDirectory.
resolvePath() (. 728).
url File URL-, :
var urlStr:String = "file:///C:/AIR Test/test.txt";
var file:File = new File()
file.url = urlStr;

File() URL-, :
var urlStr:String = "file:///C:/AIR Test/test.txt";
var file:File = new File(urlStr);

url URL URI (, "%20):


file.url = "file:///c:/AIR Test";
trace(file.url); // file:///c:/AIR%20Test

nativePath File . ,
Windows, File
text.txt AIR Test ::
var file:File = new File();
file.nativePath = "C:/AIR Test/test.txt";

File(), :
var file:File = new File("C:/AIR Test/test.txt");

nativePath (/).
Windows (\),
.
. 728.

23.11.2012.

726

ACTIONSCRIPT 3.0


Adobe AIR 1.0
getDirectoryListing() File File,
. .
734.

Adobe AIR 1.0
File , ,
:

browseForOpen()

browseForSave()

browseForOpenMultiple()

. browseForOpen() browseForSave() select,


(, browseForSave(), ).
browseForOpen() browseForSave(), File .
browseForOpenMultiple() selectMultiple, .
selectMultiple FileListEvent, files,
File ( ).
, :
var fileToOpen:File = File.documentsDirectory;
selectTextFile(fileToOpen);
function selectTextFile(root:File):void
{
var txtFilter:FileFilter = new FileFilter("Text", "*.as;*.css;*.html;*.txt;*.xml");
root.browseForOpen("Open", [txtFilter]);
root.addEventListener(Event.SELECT, fileSelected);
}
function fileSelected(event:Event):void
{
trace(fileToOpen.nativePath);
}

browse ,
Error.
. Android browseForOpen() browseForOpenMultiple()
, . browseForSave()
, .
, ,
.

23.11.2012.

727

ACTIONSCRIPT 3.0


Adobe AIR 1.0
File , resolvePath()
nativePath url , ( Windows):
var file1:File = File.documentsDirectory;
file1 = file1.resolvePath("AIR Test");
trace(file1.nativePath); // C:\Documents and Settings\userName\My Documents\AIR Test
var file2:File = File.documentsDirectory;
file2 = file2.resolvePath("..");
trace(file2.nativePath); // C:\Documents and Settings\userName
var file3:File = File.documentsDirectory;
file3.nativePath += "/subdirectory";
trace(file3.nativePath); // C:\Documents and Settings\userName\My Documents\subdirectory
var file4:File = new File();
file4.url = "file:///c:/AIR Test/test.txt";
trace(file4.nativePath); // C:\AIR Test\test.txt

nativePath
(/). Windows (\),
.

AIR URL-
Adobe AIR 1.0
AIR url File URL-.
URL

file

. :
file:///c:/AIR Test/test.txt

URL , URL- file://<host>/<path>.


<host> , ,
URL-. URL-
(///).
app


(, application.xml ). ,
:
app:/images

app-storage

. AIR
,
, . , prefs.xml
:
app-storage:/settings/prefs.xml


Adobe AIR 1.0
getRelativePath()
:

23.11.2012.

728

ACTIONSCRIPT 3.0

var file1:File = File.documentsDirectory.resolvePath("AIR Test");


var file2:File = File.documentsDirectory
file2 = file2.resolvePath("AIR Test/bob/test.txt");
trace(file1.getRelativePath(file2)); // bob/test.txt

getRelativePath() useDotDot ..
:
var file1:File = File.documentsDirectory;
file1 = file1.resolvePath("AIR Test");
var file2:File = File.documentsDirectory;
file2 = file2.resolvePath("AIR Test/bob/test.txt");
var file3:File = File.documentsDirectory;
file3 = file3.resolvePath("AIR Test/susan/test.txt");
trace(file2.getRelativePath(file1, true)); // ../..
trace(file3.getRelativePath(file2, true)); // ../../bob/test.txt


Adobe AIR 1.0
Windows Mac OS . File
:
File.documentsDirectory.resolvePath("test.txt");
File.documentsDirectory.resolvePath("TeSt.TxT");

. ,
, AIR Test:
var file:File = File.documentsDirectory.resolvePath("AIR test");
trace(file.nativePath); // ... AIR test
file.canonicalize();
trace(file.nativePath); // ... AIR Test

canonicalize() nativePath ,
. , ( Linux),
, , canonicalize()
( , ).
canonicalize() ( 8.3)
Windows, :
var path:File = new File();
path.nativePath = "C:\\AIR~1";
path.canonicalize();
trace(path.nativePath); // C:\AIR Test


Adobe AIR 1.0
:

23.11.2012.

729

ACTIONSCRIPT 3.0

. Mac OS
Mac OS Finder , .
. Mac OS, Linux Windows Vista.
.
. ( ),
, .
, , , .
,
, , . , Windows
isSymbolicLink File, ( NTFS),
true.
File isPackage isSymbolicLink, , File
.
,
:
var desktopNodes:Array = File.desktopDirectory.getDirectoryListing();
for (var i:uint = 0; i < desktopNodes.length; i++)
{
if (desktopNodes[i].isDirectory && !desktopNodes[i].isPackage)
{
trace(desktopNodes[i].name);
}
}

,
:
var desktopNodes:Array = File.desktopDirectory.getDirectoryListing();
for (var i:uint = 0; i < desktopNodes.length; i++)
{
if (!desktopNodes[i].isSymbolicLink)
{
trace(desktopNodes[i].name);
}
}

canonicalize() , ,
.
, , :
var desktopNodes:Array = File.desktopDirectory.getDirectoryListing();
for (var i:uint = 0; i < desktopNodes.length; i++)
{
if (desktopNodes[i].isSymbolicLink)
{
var linkNode:File = desktopNodes[i] as File;
linkNode.canonicalize();
trace(linkNode.nativePath);
}
}

23.11.2012.

730

ACTIONSCRIPT 3.0


Adobe AIR 1.0
spaceAvailable File
File . ,
.
trace(File.applicationStorageDirectory.spaceAvailable);

File , spaceAvailable ,
. File , spaceAvailable
, . ,
spaceAvailable 0. File ,
spaceAvailable , .
, , , ,
.
.
, , ,
. , .
. ,
. ,
. .
740.
StorageVolumeInfo.getStorageVolumes()
(. 738).


Adobe AIR 2
AIR 2 ,
. , AIR DOC- ,
. openWithDefaultApplication() File
. , test.doc
, DOC:
var file:File = File.deskopDirectory;
file = file.resolvePath("test.doc");
file.openWithDefaultApplication();

. Linux MIME ( ) .
mp3- ,
mp3-:

23.11.2012.

731

ACTIONSCRIPT 3.0

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();
}

openWithDefaultApplication() ,
.
AIR openWithDefaultApplication() . Windows
AIR (, EXE BAT). Mac OS Linux
AIR . (
AppletLauncher Mac OS csh, bash ruby Linux.)
openWithDefaultApplication() .
.
File.openWithDefaultApplication().
. AIR,
( ).


Adobe AIR 1.0
File ,
:

File.lineEnding

,
. Mac OS Linux . Windows ,
.

File.separator

, . Mac OS Linux
(/). Windows (\).

File.systemCharset

, .
, .

Capabilities ,
.

Capabilities.hasIME

, (IME) ,
: (true) (false).

Capabilities.language

, .

Capabilities.os

23.11.2012.

732

ACTIONSCRIPT 3.0

. , Capabilities.os .
, .
, .
, :
var separator:String;
if (Capablities.os.indexOf("Mac") > -1)
{
separator = "/";
}
else
{
separator = "\\";
}

Linux.
File.separator.


Adobe AIR 1.0
.
File, , . File,
722.


Adobe AIR 1.0
File.createDirectory() . ,
AIR Test, :
var dir:File = File.userDirectory.resolvePath("AIR Test");
dir.createDirectory();

, createDirectory() .
FileStream .
FileStream fileMode
FileStream(), FileMode.APPEND FileMode.WRITE. .
740.


Adobe AIR 1.0
File createTempDirectory(), System
, :
var temp:File = File.createTempDirectory();

createTempDirectory() ,
.

23.11.2012.

733

ACTIONSCRIPT 3.0

,
. , createTempFile(),
System.
,
.


Adobe AIR 1.0
getDirectoryListing() getDirectoryListingAsync() File
File, .
,
( ):
var directory:File = File.documentsDirectory;
var contents:Array = directory.getDirectoryListing();
for (var i:uint = 0; i < contents.length; i++)
{
trace(contents[i].name, contents[i].size);
}

directoryListing
files, File, :
var directory:File = File.documentsDirectory;
directory.getDirectoryListingAsync();
directory.addEventListener(FileListEvent.DIRECTORY_LISTING, dirListHandler);
function dirListHandler(event:FileListEvent):void
{
var contents:Array = event.files;
for (var i:uint = 0; i < contents.length; i++)
{
trace(contents[i].name, contents[i].size);
}
}


Adobe AIR 1.0
,
. , :
var sourceDir:File = File.documentsDirectory.resolvePath("AIR Test");
var resultDir:File = File.documentsDirectory.resolvePath("AIR Test Copy");
sourceDir.copyTo(resultDir);

overwrite copyTo() true,


(
).
, newLocation copyTo() .
, .

23.11.2012.

734

ACTIONSCRIPT 3.0

. 736.


Adobe AIR 1.0
File deleteDirectory() deleteDirectoryAsync().
. , (.
AIR 717). deleteDirectoryContents (
). true ( false),
, .
, AIR Test
:
var directory:File = File.documentsDirectory.resolvePath("AIR Test");
directory.deleteDirectory(true);

AIR Test :
var directory:File = File.documentsDirectory.resolvePath("AIR Test");
directory.addEventListener(Event.COMPLETE, completeHandler)
directory.deleteDirectoryAsync(true);
function completeHandler(event:Event):void {
trace("Deleted.")
}

moveToTrash() moveToTrashAsync(),
. .
738.


Adobe AIR 1.0
API- AIR
. , , ,
. ,
AIR 1159, .
. AIR (
). .
951.


Adobe AIR 1.0
File , ,
File:

23.11.2012.

735

ACTIONSCRIPT 3.0

File

creationDate

creator

. extension. ( creator
Macintosh Mac OS, Mac OS X.)

downloaded

(AIR 2 ) , , ,
. ,
:

Windows XP SP2 Windows Vista

Mac OS 10.5

exists

, , .

extension

, . (.)
( ). , extension null.

icon

Icon, , .

isDirectory

, File .

modificationDate

name

( , ) .

nativePath

. .
File 718.

parent

, , File. null,
File .

size

type

. extension. ( Macintosh
, Mac OS,
Mac OS X.)

url

URL- . . File 718.

. File c ActionScript 3.0


Flash Platform.


Adobe AIR 1.0
File : copyTo() copyToAsync(). File
: moveTo() moveToAsync(). copyTo()
moveTo() , copyToAsync() moveToAsync() (.
AIR 717).
File. ,
, ,
( ).
test.txt AIR Test
copy.txt :

23.11.2012.

736

ACTIONSCRIPT 3.0

var original:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");


var newFile:File = File.resolvePath("AIR Test/copy.txt");
original.copyTo(newFile, true);

overwrite copyTo() ( ) true.


overwrite true .
. false ( ) IOErrorEvent,
( ).
, Async,
. addEventListener() ,
:
var original = File.documentsDirectory;
original = original.resolvePath("AIR Test/test.txt");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("AIR Test 2/copy.txt");
original.addEventListener(Event.COMPLETE, fileMoveCompleteHandler);
original.addEventListener(IOErrorEvent.IO_ERROR, fileMoveIOErrorEventHandler);
original.moveToAsync(destination);
function fileMoveCompleteHandler(event:Event):void {
trace(event.target); // [object File]
}
function fileMoveIOErrorEventHandler(event:IOErrorEvent):void {
trace("I/O Error.");
}

File File.moveToTrash() File.moveToTrashAsync(),


.


Adobe AIR 1.0
File deleteFile() deleteFileAsync(). .
, (. AIR
717).
, test.txt :
var file:File = File.documentsDirectory.resolvePath("test.txt");
file.deleteFile();

test.txt :
var file:File = File.documentsDirectory.resolvePath("test.txt");
file.addEventListener(Event.COMPLETE, completeHandler)
file.deleteFileAsync();
function completeHandler(event:Event):void {
trace("Deleted.")
}

23.11.2012.

737

ACTIONSCRIPT 3.0

moveToTrash() moveToTrashAsync,
. .
738.


Adobe AIR 1.0
File moveToTrash() moveToTrashAsync().
. , (.
AIR 717).
, test.txt
:
var file:File = File.documentsDirectory.resolvePath("test.txt");
file.moveToTrash();

. ,
, .


Adobe AIR 1.0
File createTempFile(),
, :
var temp:File = File.createTempFile();

createTempFile() ,
.
,
. , createTempDirectory(),
System.
,
.


Adobe AIR 2
AIR 2 .
StorageVolumeInfo storageVolumeInfo.
StorageVolumeInfo.storageVolumeInfo storageVolumeMount
. , storageVolumeUnmount.
StorageVolumeChangeEvent .
. Linux StorageVolumeInfo
storageVolumeMount storageVolumeUnmount ,
.

23.11.2012.

738

ACTIONSCRIPT 3.0

storageVolume StorageVolumeChangeEvent StorageVolume.


StorageVolume :

drive Windows (null )

fileSystemType (, FAT, NTFS,


HFS UFS);

isRemoveable (true) (false);

isWritable (true) (false);

name ;

rootDirectory File, ;

StorageVolumeChangeEvent rootDirectory. rootDirectory


File, ,
.
storageVolume StorageVolumeChangeEvent (null) .
rootDirectory .
, :
StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME
_MOUNT, onVolumeMount);
function onVolumeMount(event:StorageVolumeChangeEvent):void
{
trace(event.storageVolume.name, event.rootDirectory.nativePath);
}

, :
StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME
_UNMOUNT, onVolumeUnmount);
function onVolumeUnmount(event:StorageVolumeChangeEvent):void
{
trace(event.rootDirectory.nativePath);
}

StorageVolumeInfo.storageVolumeInfo getStorageVolumes().
StorageVolume,
. ,
:
var volumes:Vector.<StorageVolume> = new Vector.<StorageVolume>;
volumes = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i:int = 0; i < volumes.length; i++)
{
trace(volumes[i].name, volumes[i].rootDirectory.nativePath);
}

. Linux getStorageVolumes() ,
,
.
File.getRootDirectories() (.
724). StorageVolume (
StorageVolumeInfo.getStorageVolumes())
.

23.11.2012.

739

ACTIONSCRIPT 3.0

spaceAvailable rootDirectory StorageVolume ,


. .
731.
AIR for TV .
AIR for TV 721.


StorageVolume
StorageVolumeInfo


Adobe AIR 1.0
FileStream AIR .


Adobe AIR 1.0
.
File, .
File , ( ,
).
var file:File = File.documentsDirectory;
file = file.resolvePath("AIR Test/testFile.txt");

File.documentsDirectory resolvePath() File


File. File .
. File, 726.
FileStream.
open() openAsync() FileStream.
,
. File file open. fileMode
FileMode, , .
, FileStream,
:
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);

. FileStream,
742 FileStream 741.

23.11.2012.

740

ACTIONSCRIPT 3.0

( openAsync()),
FileStream.
, FileStream
, , /,
.
. ,
FileStream 746.
.
FileStream . (
read write.) , ,
.
, UTF, readUTFBytes()
writeUTFBytes(). ,
readByte(), readBytes(), writeByte() writeBytes(). .
747.
, , .
. bytesAvailable FileStream
745.
,
spaceAvailable File. .
731.
close() FileStream.
close() .
. FileStream,
742.
, FileStream,
Adobe AIR:



XML-

FileStream
Adobe AIR 1.0
FileStream , .
FileStream
Adobe AIR 1.0
open() openAsync() FileStream fileMode,
:

23.11.2012.

741

ACTIONSCRIPT 3.0



, ( )
, fileMode
open() openAsync():

FileMode.READ

, .

FileMode.WRITE

, . ,
FileStream. , .

FileMode.APPEND

, . ,
. , ,
.

FileMode.UPDATE

, . ,
. .
.
, , .

FileStream,
Adobe AIR 1.0
FileStream .
FileStream open() openAsync() FileStream:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.READ);

fileMode ( open() openAsync()) ,


: , , . .
FileStream 741.
openAsync(),
:

23.11.2012.

742

ACTIONSCRIPT 3.0

var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");


var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completeHandler);
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.addEventListener(IOErrorEvent.IOError, errorHandler);
myFileStream.open(myFile, FileMode.READ);
function completeHandler(event:Event):void {
// ...
}
function progressHandler(event:ProgressEvent):void {
// ...
}
function errorHandler(event:IOErrorEvent):void {
// ...
}

,
: open() openAsync(). . AIR
717.
FileMode.READ FileMode.UPDATE FileStream
fileMode, , FileStream.
. bytesAvailable FileStream
745.
close() FileStream ,
.
position FileStream
Adobe AIR 1.0
position FileStream ,
.
position
.
, "hello" ( UTF) 8:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.UPDATE);
myFileStream.position = 8;
myFileStream.writeUTFBytes("hello");

FileStream position 0.
position 0 (
).
position :

position .
23.11.2012.

743

ACTIONSCRIPT 3.0

.
.
FileStream, position
. ,
position
.
.
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.UPDATE);
myFileStream.position = 4000;
trace(myFileStream.position); // 4000
myFileStream.writeBytes(myByteArray, 0, 200);
trace(myFileStream.position); // 4200

: FileStream ,
position . (
, position.)
, ,
.
:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.openAsync(myFile, FileMode.WRITE);
myFileStream.writeUTFBytes("hello");
myFileStream.writeUTFBytes("world");
myFileStream.addEventListener(Event.CLOSE, closeHandler);
myFileStream.close();
trace("started.");
closeHandler(event:Event):void
{
trace("finished.");
}

:
started.
finished.

position (
), . ,
, position
writeBytes(), position 300 :
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.openAsync(myFile, FileMode.UPDATE);
myFileStream.position = 4000;
trace(myFileStream.position); // 4000
myFileStream.writeBytes(myByteArray, 0, 200);
myFileStream.position = 300;
trace(myFileStream.position); // 300

23.11.2012.

744

ACTIONSCRIPT 3.0

bytesAvailable FileStream
Adobe AIR 1.0
FileStream (. . fileMode open()
openAsync() READ UPDATE) .
FileStream ( open()
openAsync() FileStream).
( open()), position
( ) (
), ( , 100 ):
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.READ);
myFileStream.position = 10;
myFileStream.readBytes(myByteArray, 0, 20);
myFileStream.position = 89;
myFileStream.readBytes(myByteArray, 0, 10);

, : ,
, bytesAvalable.
. ,
, position, ,
progress.
, bytesAvailable
position ( ).
, , , ,
. ,
( position, )
, bytesAvailable .
bytesAvailable , ,
position, . FileStream progress.
, , ,
FileStream progress. ,
ByteArray, bytes, :
var bytes:ByteArray = new ByteArray();
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.openAsync(myFile, FileMode.READ);
function progressHandler(event:ProgressEvent):void
{
myFileStream.readBytes(bytes, myFileStream.position, myFileStream.bytesAvailable);
}

, . ,
, . ,
. , 8000 , 4000:

23.11.2012.

745

ACTIONSCRIPT 3.0

var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");


var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.addEventListener(Event.COMPLETE, completed);
myFileStream.openAsync(myFile, FileMode.READ);
myFileStream.position = 4000;
var str:String = "";
function progressHandler(event:Event):void
{
if (myFileStream.bytesAvailable > 8000 )
{
str += myFileStream.readMultiByte(8000, "iso-8859-1");
}
}

FileStream .
( ) FileStream (
FileStream ) ,
, position. position
, position
.
,
FileStream
Adobe AIR 1.0
( openAsync()),
.
ActionScript.
, ,
FileStream.
progress, ,
, :
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.openAsync(myFile, FileMode.READ);
var str:String = "";
function progressHandler(event:ProgressEvent):void
{
str += myFileStream.readMultiByte(myFileStream.bytesAvailable, "iso-8859-1");
}

, complete, :

23.11.2012.

746

ACTIONSCRIPT 3.0

var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");


var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completed);
myFileStream.openAsync(myFile, FileMode.READ);
var str:String = "";
function completeHandler(event:Event):void
{
str = myFileStream.readMultiByte(myFileStream.bytesAvailable, "iso-8859-1");
}

, , ,
, .
FileStream OutputProgressEvent.
OutputProgressEvent bytesPending,
. outputProgress,
, , (, ,
). . , close()
. FileStream , close
.

Adobe AIR 1.0
. ActionScript
(ByteArray). , ,
ByteArray bytes:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completeHandler);
myFileStream.openAsync(myFile, FileMode.READ);
var bytes:ByteArray = new ByteArray();
function completeHandler(event:Event):void
{
myFileStream.readBytes(bytes, 0, myFileStream.bytesAvailable);
}

ByteArray bytes :
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.WRITE);
myFileStream.writeBytes(bytes, 0, bytes.length);

ByteArray.
.
, ,
( String).
FileStream ByteArray.
, readMultiByte() ,
:

23.11.2012.

747

ACTIONSCRIPT 3.0

var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");


var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completed);
myFileStream.openAsync(myFile, FileMode.READ);
var str:String = "";
function completeHandler(event:Event):void
{
str = myFileStream.readMultiByte(myFileStream.bytesAvailable, "iso-8859-1");
}

readMultiByte() , ActionScript
(, iso-8859-1). Adobe AIR
(. ).
FileStream readUTFBytes(),
UTF-8. UTF-8 ,
readUTFBytes() progress,
. (
readMultiByte() .)
, FileStream complete.
: writeMultiByte() writeUTFBytes(),
String .
readUTF() writeUTF() ( readUTFBytes() writeUTFBytes())
, ,
,
.
UTF UTF-BOM ( ),
(UTF-16 UTF-32).
: XML- XML-
750.
readObject() writeObject()
ActionScript. AMF (ActionScript Message Format).
Adobe AIR, Flash Player, Flash Media Server Flex Data Services
API.
(, readDouble() writeDouble()).
,
.
, . , MP3-
,
MP3-. MP3- ID3 (,
). ID3; (ID3
1) :
751.
(, , . .) ,
, ActionScript, , .

23.11.2012.

748

ACTIONSCRIPT 3.0

load() save()
Flash Player 10 , Adobe AIR 1.5
Adobe Flash Player 10 FileReference load() save().
AIR 1.5, File FileReference.

Adobe Flash. AIR
.
, :
var file:File = File.applicationStorageDirectory.resolvePath("test.txt");
var str:String = "Hello.";
file.addEventListener(Event.COMPLETE, fileSaved);
file.save(str);
function fileSaved(event:Event):void
{
trace("Done.");
}

data save() String, XML ByteArray.


String XML, UTF-8.
,
.
UTF-8:
var file:File = File.applicationStorageDirectory.resolvePath("test.txt");
file.addEventListener(Event.COMPLETE, loaded);
file.load();
var str:String;
function loaded(event:Event):void
{
var bytes:ByteArray = file.data;
str = bytes.readUTFBytes(bytes.length);
trace(str);
}

FileStream , load() save():

FileStream, , .
FileStream .
FileStream ( ,
).

FileStream , fileMode
open() openAsync().

FileStream ,
.

FileStream ,
.

23.11.2012.

749

ACTIONSCRIPT 3.0

: XML- XML-
Adobe AIR 1.0
, XML-.
File FileStream, readUTFBytes() FileStream
XML-:
var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var prefsXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
fileStream.close();

, File FileStream
FileStream. XML- , :
var prefsXML:XML = <prefs><autoSave>true</autoSave></prefs>;
var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml");
fileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';
outputString += prefsXML.toXMLString();
fileStream.writeUTFBytes(outputString);
fileStream.close();

readUTFBytes() writeUTFBytes(), ,
UTF-8. (.
747).
FileStream, .
(
). , XML-:
var file:File = File.documentsDirectory.resolvePath("AIR Test/preferences.xml");
var fileStream:FileStream = new FileStream();
fileStream.addEventListener(Event.COMPLETE, processXMLData);
fileStream.openAsync(file, FileMode.READ);
var prefsXML:XML;
function processXMLData(event:Event):void
{
prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
fileStream.close();
}

processXMLData() , , . .
FileStream complete. readUTFBytes()
XML- prefsXML.
, , . XML-
.

23.11.2012.

750

ACTIONSCRIPT 3.0

:
Adobe AIR 1.0
MP3- ID3 ,
. ID3. ,
MP3- ID3 (ID3 1.0),
. , .
MP3- ID3 1 ID3 128 .
FileMode.UPDATE
fileMode open() openAsync():
var file:File = File.documentsDirectory.resolvePath("My Music/Sample ID3 v1.mp3");
var fileStr:FileStream = new FileStream();
fileStr.open(file, FileMode.UPDATE);

, .
, position 128 :
fileStr.position = file.size - 128;

position , ID3 1.0


, ID3 128 . ,
. :

3 "TAG".
30 MP3- .
30 .
30 .
4 .
30 .
, .
ISO 8859-1.
id3TagRead() ( complete):
function id3TagRead():void
{
if (fileStr.readMultiByte(3, "iso-8859-1").match(/tag/i))
{
var id3Title:String = fileStr.readMultiByte(30, "iso-8859-1");
var id3Artist:String = fileStr.readMultiByte(30, "iso-8859-1");
var id3Album:String = fileStr.readMultiByte(30, "iso-8859-1");
var id3Year:String = fileStr.readMultiByte(4, "iso-8859-1");
var id3Comment:String = fileStr.readMultiByte(30, "iso-8859-1");
var id3GenreCode:String = fileStr.readByte().toString(10);
}
}

23.11.2012.

751

ACTIONSCRIPT 3.0

. ,
id3Title, , (
String), newTitle, :
fileStr.position = file.length - 125;
// 128 - 3
fileStr.writeMultiByte(newTitle, "iso-8859-1");

ID3 1, newTitle 30 ,
0 (String.fromCharCode(0)).

23.11.2012.

752

753

39.
Flash Player 9 , Adobe AIR 1.0
SharedObject .
Adobe AIR EncryptedLocalStore
AIR.
( Adobe AIR)
. .
701 SQL AIR 767.
, . .
1157 1120.


Flash Player 9 , Adobe AIR 1.0
, Flash cookie, ,
.
. , -.


Flash Player 9 , Adobe AIR 1.0
cookie . SharedObject

. SharedObject
. ,
, .

cookie
Flash Player 9 , Adobe AIR 1.0
cookie . -
cookie, cookie
SharedObjects.
, cookie, RFC 2109, :

, ;
;
cookie, 300, 20 ;
4 ;

23.11.2012.

ACTIONSCRIPT 3.0

,
;

;
HTTP.
cookie, :

;
100 ;
(, String, Array Date).
( );
.

SharedObject
Flash Player 9 , Adobe AIR 1.0
SharedObject ,
SharedObject. SharedObject .

clear()

SharedObject SharedObject .

flush()

SharedObject .

getLocal()

SharedObject.
.

getSize()

SharedObject .
100 , , .

SharedObject :

data

, ,
.

onStatus

, ,
.


Flash Player 9 , Adobe AIR 1.0
SharedObject SharedObject.getLocal()
:
SharedObject.getLocal("objectName" [, pathname]): SharedObject

mySO:
public var mySO:SharedObject;
mySO = SharedObject.getLocal("preferences");

23.11.2012.

754

755

ACTIONSCRIPT 3.0

preferences.sol.
local . Adobe Flash Player
SharedObject .
Flash Player
. *.sol, SharedObject.
.
:

Windows
95/98/ME/2000/XP

c:/Documents and Settings/username/Application


Data/Macromedia/Flash Player/#SharedObjects

Windows Vista

c:/Users/username/AppData/Roaming/Macromedia/Flash
Player/#SharedObjects

Macintosh OS X

/Users/username/Library/Preferences/Macromedia/Flash
Player/#SharedObjects/web_domain/path_to_application/applicatio
n_name/object_name.sol

Linux/Unix

/home/username/.macromedia/Flash_Player/#SharedObjects/web_doma
in/path_to_application/application_name/object_name.sol

#SharedObjects . ,
, , , *.sol.
, MyApp.swf,
/sos, Flash Player *.sol ( Windows XP):
c:/Documents and Settings/fred/Application Data/Macromedia/Flash
Player/#SharedObjects/KROKWXRK/#localhost/sos/MyApp.swf/data.sol

. SharedObject.getLocal()
undefined.sol.

, Flash Player

Flash SharedObject 100


. .
, 100 , Flash Player
,
, .


Flash Player 9 , Adobe AIR 1.0
pathname
SharedObject. SharedObject . ,
:
mySO = SharedObject.getLocal("myObjectFile","/");

23.11.2012.

ACTIONSCRIPT 3.0

Flash Player SharedObject /#localhost ( /localhost,


-).
.
Flex, ,
; .
, ,
LocalConnection.
Flash Player SharedObject.


Flash Player 9 , Adobe AIR 1.0
*.sol SharedObject , data SharedObject.
:
sharedObject_name.data.variable = value;

userName, itemNumbers adminPrivileges,


, SharedObject:
public var currentUserName:String = "Reiner";
public var itemsArray:Array = new Array(101,346,483);
public var currentUserIsAdmin:Boolean = true;
mySO.data.userName = currentUserName;
mySO.data.itemNumbers = itemsArray;
mySO.data.adminPrivileges = currentUserIsAdmin;

data Flash Player


SharedObject. SharedObject
SharedObject.flush(), :
mySO.flush();

SharedObject.flush(), Flash Player


.
, Flash Player ,
. SharedObject.flush().
flush()
,
Flash Player Settings Manager
(www.macromedia.com/support/documentation/ru/flashplayer/help/settings_manager07.html),
.
var so:SharedObject = SharedObject.getLocal("test");
trace("Current SharedObject size is " + so.size + " bytes.");
so.flush();


, , Arrays Strings, SharedObject data.
ActionScript, ,
.
. ArrayCollection, .

23.11.2012.

756

ACTIONSCRIPT 3.0

package {
import mx.collections.ArrayCollection;
import flash.net.SharedObject;
public class LSOHandler {
private var mySO:SharedObject;
private var ac:ArrayCollection;
private var lsoType:String;
// The parameter is "feeds" or "sites".
public function LSOHandler(s:String) {
init(s);
}
private function init(s:String):void {
ac = new ArrayCollection();
lsoType = s;
mySO = SharedObject.getLocal(lsoType);
if (getObjects()) {
ac = getObjects();
}
}
public function getObjects():ArrayCollection {
return mySO.data[lsoType];
}
public function addObject(o:Object):void {
ac.addItem(o);
updateSharedObjects();
}
private function updateSharedObjects():void {
mySO.data[lsoType] = ac;
mySO.flush();
}
}
}

Flex ActionScript ,
.
URL- .

23.11.2012.

757

ACTIONSCRIPT 3.0

<?xml version="1.0"?>
<!-- lsos/BlogAggregator.mxml -->
<mx:Application
xmlns:local="*"
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="initApp()"
backgroundColor="#ffffff"
>
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.utils.ObjectUtil;
import flash.net.SharedObject;
[Bindable]
public var welcomeMessage:String;
[Bindable]
public var localFeeds:ArrayCollection = new ArrayCollection();
[Bindable]
public var localSites:ArrayCollection = new ArrayCollection();
public var lsofeeds:LSOHandler;
public var lsosites:LSOHandler;
private function initApp():void {
lsofeeds = new LSOHandler("feeds");
lsosites = new LSOHandler("sites");
if (lsofeeds.getObjects()) {
localFeeds = lsofeeds.getObjects();
}
if (lsosites.getObjects()) {
localSites = lsosites.getObjects();
}
}
// Adds a new feed to the feeds DataGrid.
private function addFeed():void {
// Construct an object you want to store in the
// LSO. This object can contain any number of fields.
var o:Object = {name:ti1.text, url:ti2.text, date:new Date()};
lsofeeds.addObject(o);
// Because the DataGrid's dataProvider property is
// bound to the ArrayCollection, Flex updates the
// DataGrid when you call this method.
localFeeds = lsofeeds.getObjects();
// Clear the text fields.
ti1.text = '';
ti2.text = '';
}
// Removes feeds from the feeds DataGrid.
private function removeFeed():void {

23.11.2012.

758

ACTIONSCRIPT 3.0

//
//
//
//
//
if

Use a method of ArrayCollection to remove a feed.


Because the DataGrid's dataProvider property is
bound to the ArrayCollection, Flex updates the
DataGrid when you call this method. You do not need
to update it manually.
(myFeedsGrid.selectedIndex > -1) {

localFeeds.removeItemAt(myFeedsGrid.selectedIndex);
}
}
private function addSite():void {
var o:Object = {name:ti3.text, date:new Date()};
lsosites.addObject(o);
localSites = lsosites.getObjects();
ti3.text = '';
}
private function removeSite():void {
if (mySitesGrid.selectedIndex > -1) {
localSites.removeItemAt(mySitesGrid.selectedIndex);
}
}
]]>
</mx:Script>
<mx:Label text="Blog aggregator" fontSize="28"/>
<mx:Panel title="Blogs">
<mx:Form id="blogForm">
<mx:HBox>
<mx:FormItem label="Name:">
<mx:TextInput id="ti1" width="100"/>
</mx:FormItem>
<mx:FormItem label="Location:">
<mx:TextInput id="ti2" width="300"/>
</mx:FormItem>
<mx:Button id="b1" label="Add Feed" click="addFeed()"/>
</mx:HBox>
<mx:FormItem label="Existing Feeds:">
<mx:DataGrid
id="myFeedsGrid"
dataProvider="{localFeeds}"
width="400"
/>
</mx:FormItem>
<mx:Button id="b2" label="Remove Feed" click="removeFeed()"/>
</mx:Form>
</mx:Panel>
<mx:Panel title="Sites">

23.11.2012.

759

ACTIONSCRIPT 3.0

<mx:Form id="siteForm">
<mx:HBox>
<mx:FormItem label="Site:">
<mx:TextInput id="ti3" width="400"/>
</mx:FormItem>
<mx:Button id="b3" label="Add Site" click="addSite()"/>
</mx:HBox>
<mx:FormItem label="Existing Sites:">
<mx:DataGrid
id="mySitesGrid"
dataProvider="{localSites}"
width="400"
/>
</mx:FormItem>
<mx:Button id="b4" label="Remove Site" click="removeSite()"/>
</mx:Form>
</mx:Panel>
</mx:Application>


ActionScript
.
flash.net.registerClassAlias() . ,

. SharedObject objectEncoding
AMF3 SharedObject.
, registerClassAlias().


Flash Player 9 , Adobe AIR 1.0
Flex.
, :
public var mySO:SharedObject = SharedObject.getLocal("preferences");
public var mySO2:SharedObject = SharedObject.getLocal("history");

Flex preferences.sol history.sol.

SharedObject
Flash Player 9 , Adobe AIR 1.0
SharedObject getLocal()
getRemote(), secure, ,
SWF-, HTTPS-.
true SWF- HTTPS, Flash Player
.

23.11.2012.

760

ACTIONSCRIPT 3.0

SWF-,
HTTPS, SharedObject.getLocal()
secure, true. false SWF-
HTTPS, Flash Player
.
SWF-, HTTPS. SWF- HTTPS
true, (
) , ,
null.
HTTPS, SharedObject.getLocal() .
try
{
var so:SharedObject = SharedObject.getLocal("contactManager", null, true);
}
catch (error:Error)
{
trace("Unable to create SharedObject.");
}


, .


Flash Player 9 , Adobe AIR 1.0
data. SharedObject
for..in, .
var so:SharedObject = SharedObject.getLocal("test");
so.data.hello = "world";
so.data.foo = "bar";
so.data.timezone = new Date().timezoneOffset;
for (var i:String in so.data)
{
trace(i + ":\t" + so.data[i]);
}


Flash Player 9 , Adobe AIR 1.0
SharedObject SharedObject.clear().
, .
SharedObject :
public function destroySharedObject():void {
mySO.clear();
}

23.11.2012.

761

ACTIONSCRIPT 3.0

SharedObject
Flash Player 9 , Adobe AIR 1.0
, Date,
SharedObject SharedObject .
,
. .

.
, , , ,
. .
.
<?xml version="1.0"?>
<!-- lsos/WelcomeMessage.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="initApp()">
<mx:Script><![CDATA[
public var mySO:SharedObject;
[Bindable]
public var welcomeMessage:String;
public function initApp():void {
mySO = SharedObject.getLocal("mydata");
if (mySO.data.visitDate==null) {
welcomeMessage = "Hello first-timer!"
} else {
welcomeMessage = "Welcome back. You last visited on " +
getVisitDate();
}
}
private function getVisitDate():Date {
return mySO.data.visitDate;
}
private function storeDate():void {
mySO.data.visitDate = new Date();
mySO.flush();
}
private function deleteLSO():void {
// Deletes the SharedObject from the client machine.
// Next time they log in, they will be a 'first-timer'.
mySO.clear();
}
]]></mx:Script>
<mx:Label id="label1" text="{welcomeMessage}"/>
<mx:Button label="Log Out" click="storeDate()"/>
<mx:Button label="Delete LSO" click="deleteLSO()"/>
</mx:Application>

23.11.2012.

762

ACTIONSCRIPT 3.0

EncryptedLocalStore (ELS) ,

. ELS . ELS ,
, ,
. ELS ,

ELS.
. Adobe AIR
, SQL. .
SQL 813.
, ,
, -.
ELS.
, . ,
, DRM .

AIR DPAPI Windows, KeyChain Mac OS iOS,
KeyRing KWallet Linux. 128-
AES-CBC.
Android , EncryptedLocalStorage, .
. Android
.
, , ).
, Android ,
, . ,
,
.
AIR
.
AIR
, .

stronglyBound true
AIR 1.5.3, .

.
, ,
. ,
.

23.11.2012.

763

ACTIONSCRIPT 3.0

, ,
, , (
). , ,
, ,
. , ELS .
, .
ELS . ,
. .
, ELS ,
.
stronglyBound true . true
. ,
, .
,
10 .
AIR - .

ELS .

ELS , ( false
stronglyBound).

ELS ,
.

, ELS,
ELS. ,
.

stronglyBound.
stronglyBound true,
. .

.
AIR SQL.


flash.data.EncryptedLocalStore


setItem()
EncryptedLocalStore. - -;
.
, :

23.11.2012.

764

ACTIONSCRIPT 3.0

var str:String = "Bob";


var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(str);
EncryptedLocalStore.setItem("firstName", bytes);

setItem() stronglyBound .
true,
AIR :
var str:String = "Bob";
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(str);
EncryptedLocalStore.setItem("firstName", bytes, false);

stronglyBound true, getItem()


, AIR, (
). AIR ,
getItem() Error.
,
, . stronglyBound true
. , false.
stronglyBound false ( ),
.
( ), ,
. ,
, - .
. stronglyBound true
. ,
, ELS. , ,
, , stronglyBound true false.
stronglyBound true .

Adobe AIR 1.0



EncryptedLocalStore.getItem(), :
var storedValue:ByteArray = EncryptedLocalStore.getItem("firstName");
trace(storedValue.readUTFBytes(storedValue.length)); // "Bob"

23.11.2012.

765

ACTIONSCRIPT 3.0

Adobe AIR 1.0



EncryptedLocalStore.removeItem(), :
EncryptedLocalStore.removeItem("firstName");


EncryptedLocalStore.reset(), :
EncryptedLocalStore.reset();

23.11.2012.

766

767

40.
SQL AIR
Adobe AIR 1.0
Adobe AIR SQL .
SQL SQL
SQLite. SQL
. , ,
, , .

SQL
Adobe AIR 1.0
SQL .
Adobe Developer Connection:

SQL (Flex)
SQL (Flex)
(Flex)
SQL (Flash)
SQL (Flash)
(Flash)
Adobe AIR SQL,
, ,
AIR (, ).
AIR
. , SQL
,
SQL.

SQL
Adobe AIR 1.0
SQL AIR ,
. Adobe AIR
, .
SQL AIR:

(, )
.

23.11.2012.

ACTIONSCRIPT 3.0
SQL AIR

,
, , ,
, . ( , ,
, AIR .
.)


, .
.


, ,
.


(Christophe Coenraets): AIR for Android
(Raymond Camden): jQuery AIR -

AIR
Adobe AIR 1.0
SQL Adobe AIR
. SQL,
,
. ,
; .
. AIR
(. . ).
,
.
,
.
,
. SQL
SQL .


Adobe AIR 1.0
( ) .
: , (
) . ,
. ,
. , ,
, . . , ,
.

23.11.2012.

768

ACTIONSCRIPT 3.0
SQL AIR

,
. --
.
, ,
--. .
.

, . .
.
, .
, . . ,
. , ,
,
( ) . ,
,
, .
. ,
,
( ). :
, ,
. , ,

.
,
. AIR

.
,
.

SQL
Adobe AIR 1.0
(SQL)
. SQL , .
, , SQL
. .
SQL (ANSI).
SQL Adobe AIR SQL-92.
SQL, Adobe AIR, . SQL
1193.

23.11.2012.

769

ACTIONSCRIPT 3.0
SQL AIR

SQL
Adobe AIR 1.0
SQL ActionScript 3.0 ,
flash.data:

flash.data.SQLConnection

( ),
.

flash.data.SQLStatement

SQL ( ),
, .

flash.data.SQLResult

,
SELECT, , UPDATE
DELETE, . .

, ,
flash.data:

flash.data.SQLSchemaResult

,
SQLConnection.loadSchema().

flash.data.SQLTableSchema

flash.data.SQLViewSchema

flash.data.SQLIndexSchema

flash.data.SQLTriggerSchem
a

flash.data , SQLConnection
SQLColumnSchema:

flash.data.SQLMode

, openMode
SQLConnection.open() SQLConnection.openAsync().

flash.data.SQLColumnNameStyle

,
SQLConnection.columnNameStyle.

flash.data.SQLTransactionLockType , option
SQLConnection.begin().
flash.data.SQLCollationType

,
SQLColumnSchema.defaultCollationType defaultCollationType
SQLColumnSchema().

, flash.events (
):

23.11.2012.

770

ACTIONSCRIPT 3.0
SQL AIR

flash.events.SQLEvent

, SQLConnection SQLStatement
- . ,
SQLEvent.

flash.events.SQLErrorEvent

, SQLConnection SQLStatement
- .

flash.events.SQLUpdateEven , SQLConnection
t
SQL INSERT, UPDATE
DELETE.

, flash.errors :

flash.errors.SQLError

, ,
, .

flash.errors.SQLErrorOperati
on

, operation
SQLError, ,
.


Adobe AIR 1.0
SQL
: . ,
,
.
,
.
.
, . , ( )
. , ,
. :
, .
,
. ,
. , , .
,
.
, , . .
, , .
Adobe AIR
. .
, .
.
. .

23.11.2012.

771

ACTIONSCRIPT 3.0
SQL AIR

SQLConnection.
,
. SQLConnection
SQLConnection .
SQLConnection.open() ,
SQLConnection.openAsync() .
SQLConnection open() openAsync(),
,
.
. ,
. ,
, .
808.


Adobe AIR 1.0
,
, .
. ,
, .


Mind the Flex: AIR


Adobe AIR 1.0
SQLConnection. open()
, openAsync()
. open() openAsync()
. File, ,
reference ( ) open() openAsync()
.
, open() openAsync() ,
. open()
openAsync() null reference ,
.
( )
.
723 DBSample.db:

23.11.2012.

772

ACTIONSCRIPT 3.0
SQL AIR

import
import
import
import

flash.data.SQLConnection;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;
flash.filesystem.File;

var conn:SQLConnection = new SQLConnection();


conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
conn.openAsync(dbFile);
function openHandler(event:SQLEvent):void
{
trace("the database was created successfully");
}
function errorHandler(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}

23.11.2012.

773

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
private function init():void
{
var conn:SQLConnection = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
conn.openAsync(dbFile);
}
private function openHandler(event:SQLEvent):void
{
trace("the database was created successfully");
}
private function errorHandler(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
]]>
</mx:Script>
</mx:WindowedApplication>

. File ,
, . , C:\Documents and
Settings\joe\test.db Windows.
File, File.applicationStorageDirectory,
resolvePath() ( ). .
File 718.

SQLConnection open().
SQLConnection, :

23.11.2012.

774

ACTIONSCRIPT 3.0
SQL AIR

import flash.data.SQLConnection;
import flash.errors.SQLError;
import flash.filesystem.File;
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
try
{
conn.open(dbFile);
trace("the database was created successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.errors.SQLError;
import flash.filesystem.File;
private function init():void
{
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
try
{
conn.open(dbFile);
trace("the database was created successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}
]]>
</mx:Script>
</mx:WindowedApplication>

23.11.2012.

775

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
SQL ,
, SQL, SELECT, INSERT . .
CREATE TABLE,
. SQL .
SQL 783.
employees
. ,
SQLConnection conn.
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLStatement;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;

// ... create and open the SQLConnection instance named conn ...
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employees (" +
"
empId INTEGER PRIMARY KEY AUTOINCREMENT, " +
"
firstName TEXT, " +
"
lastName TEXT, " +
"
salary NUMERIC CHECK (salary > 0)" +
")";
createStmt.text = sql;
createStmt.addEventListener(SQLEvent.RESULT, createResult);
createStmt.addEventListener(SQLErrorEvent.ERROR, createError);
createStmt.execute();
function createResult(event:SQLEvent):void
{
trace("Table created");
}
function createError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}

23.11.2012.

776

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employees (" +
"
empId INTEGER PRIMARY KEY AUTOINCREMENT, " +
"
firstName TEXT, " +
"
lastName TEXT, " +
"
salary NUMERIC CHECK (salary > 0)" +
")";
createStmt.text = sql;
createStmt.addEventListener(SQLEvent.RESULT, createResult);
createStmt.addEventListener(SQLErrorEvent.ERROR, createError);
createStmt.execute();
}
private function createResult(event:SQLEvent):void
{
trace("Table created");
}
private function createError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
]]>
</mx:Script>
</mx:WindowedApplication>

employees
. ,
SQLConnection conn.

23.11.2012.

777

ACTIONSCRIPT 3.0
SQL AIR

import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.errors.SQLError;
// ... create and open the SQLConnection instance named conn ...
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employees (" +
"
empId INTEGER PRIMARY KEY AUTOINCREMENT, " +
"
firstName TEXT, " +
"
lastName TEXT, " +
"
salary NUMERIC CHECK (salary > 0)" +
")";
createStmt.text = sql;
try
{
createStmt.execute();
trace("Table created");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}

23.11.2012.

778

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.errors.SQLError;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
var createStmt:SQLStatement = new SQLStatement();
createStmt.sqlConnection = conn;
var sql:String =
"CREATE TABLE IF NOT EXISTS employees (" +
"
empId INTEGER PRIMARY KEY AUTOINCREMENT, " +
"
firstName TEXT, " +
"
lastName TEXT, " +
"
salary NUMERIC CHECK (salary > 0)" +
")";
createStmt.text = sql;
try
{
createStmt.execute();
trace("Table created");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}
]]>
</mx:Script>
</mx:WindowedApplication>

SQL
Adobe AIR 1.0
,
SQL. ,
. ,
, .
,
, . ,

.
772.

23.11.2012.

779

ACTIONSCRIPT 3.0
SQL AIR

,

. .
, ( )
.
.
808.


Adobe AIR 1.0
.
SQLConnection .
, SQLConnection, .
open() (
) openAsync() ( ).
openAsync()
open SQLConnection, openAsync().

error SQLConnection, .

. DBSample.db
723.
import
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLMode;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;
flash.filesystem.File;

var conn:SQLConnection = new SQLConnection();


conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
conn.openAsync(dbFile, SQLMode.UPDATE);
function openHandler(event:SQLEvent):void
{
trace("the database opened successfully");
}
function errorHandler(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}

23.11.2012.

780

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLMode;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
private function init():void
{
var conn:SQLConnection = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
conn.openAsync(dbFile, SQLMode.UPDATE);
}
private function openHandler(event:SQLEvent):void
{
trace("the database opened successfully");
}
private function errorHandler(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
]]>
</mx:Script>
</mx:WindowedApplication>


. DBSample.db
723.

23.11.2012.

781

ACTIONSCRIPT 3.0
SQL AIR

import
import
import
import

flash.data.SQLConnection;
flash.data.SQLMode;
flash.errors.SQLError;
flash.filesystem.File;

var conn:SQLConnection = new SQLConnection();


// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
try
{
conn.open(dbFile, SQLMode.UPDATE);
trace("the database opened successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLMode;
import flash.errors.SQLError;
import flash.filesystem.File;
private function init():void
{
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
try
{
conn.open(dbFile, SQLMode.UPDATE);
trace("the database opened successfully");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}
]]>
</mx:Script>
</mx:WindowedApplication>

23.11.2012.

782

ACTIONSCRIPT 3.0
SQL AIR

, openAsync()
open() SQLMode.UPDATE.
SQLMode.UPDATE (openMode) ,
. SQLMode.CREATE openMode (
openMode) ,
. , , SQLMode.Update.
SQLMode.READ openMode,
. , ,
.

SQL
Adobe AIR 1.0
SQL ( )
SQLStatement. SQL:
SQLStatement.
SQLStatement SQL .
var selectData:SQLStatement = new SQLStatement();

, .
sqlConnection SQLStatement SQLConnection,
.
// A SQLConnection named "conn" has been created previously
selectData.sqlConnection = conn;

SQL.
text SQLStatement.
selectData.text = "SELECT col1, col2 FROM my_table WHERE col1 = :param1";

execute (
).
addEventListener()
result error SQLStatement.
// using listener methods and addEventListener()
selectData.addEventListener(SQLEvent.RESULT, resultHandler);
selectData.addEventListener(SQLErrorEvent.ERROR, errorHandler);
function resultHandler(event:SQLEvent):void
{
// do something after the statement execution succeeds
}
function errorHandler(event:SQLErrorEvent):void
{
// do something after the statement execution fails
}

23.11.2012.

783

ACTIONSCRIPT 3.0
SQL AIR

Responder.
Responder .
// using a Responder (flash.net.Responder)
var selectResponder = new Responder(onResult, onError);
function onResult(result:SQLResult):void
{
// do something after the statement execution succeeds
}
function onError(error:SQLError):void
{
// do something after the statement execution fails
}

, .
parameters
SQLStatement.
selectData.parameters[":param1"] = 25;

SQL.
execute() SQLStatement.
// using synchronous execution mode
// or listener methods in asynchronous execution mode
selectData.execute();

, Responder
, Responder execute().
// using a Responder in asynchronous execution mode
selectData.execute(-1, selectResponder);

, , . :
787
797
803


Adobe AIR 1.0
SQL SQL
.
(, , INSERT),
. ,
.

23.11.2012.

784

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
SQL .
,
. , ,
SQL INSERT, .
. ,
.
SQL, ,
SQL, , .
,
. SQL , ,
SQLStatement. SQL, text,
. ,
parameters SQLStatement. parameters
, :
statement.parameters[parameter_identifier] = value;

parameter_identifier , ,
, .


Adobe AIR 1.0
. ,
.
: @, , :
:itemName
@firstName

:
var sql:String =
"INSERT INTO inventoryItems (name, productCode)" +
"VALUES (:name, :productCode)";
var addItemStmt:SQLStatement = new SQLStatement();
addItemStmt.sqlConnection = conn;
addItemStmt.text = sql;
// set parameter values
addItemStmt.parameters[":name"] = "Item name";
addItemStmt.parameters[":productCode"] = "12345";
addItemStmt.execute();

23.11.2012.

785

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
.
SQL ?.
, 0 .

:
var sql:String =
"INSERT INTO inventoryItems (name, productCode)" +
"VALUES (?, ?)";
var addItemStmt:SQLStatement = new SQLStatement();
addItemStmt.sqlConnection = conn;
addItemStmt.text = sql;
// set parameter values
addItemStmt.parameters[0] = "Item name";
addItemStmt.parameters[1] = "12345";
addItemStmt.execute();


Adobe AIR 1.0
SQL :
SQLStatement, ,

, SQL .
,
SQL.
,

SQL.
, . ,

.
.
1217.

SQL. SQL SQL ,
(, ). SQL,
SQL, SQL
.
SQL. :

23.11.2012.

786

ACTIONSCRIPT 3.0
SQL AIR

// 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;


SQL. SQL ,
, .
:
// 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;


Adobe AIR 1.0
. SQL
SELECT, . ,
.

SELECT
Adobe AIR 1.0
SQLStatement.
SQL SELECT text , execute().
SELECT . SQL
1193.
SELECT
products .

23.11.2012.

787

ACTIONSCRIPT 3.0
SQL AIR

var selectStmt:SQLStatement = new SQLStatement();


// A SQLConnection named "conn" has been created previously
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT itemId, itemName, price FROM products";
selectStmt.addEventListener(SQLEvent.RESULT, resultHandler);
selectStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);
selectStmt.execute();
function resultHandler(event:SQLEvent):void
{
var result:SQLResult = selectStmt.getResult();
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var output:String = "itemId: " + row.itemId;
output += "; itemName: " + row.itemName;
output += "; price: " + row.price;
trace(output);
}
}
function errorHandler(event:SQLErrorEvent):void
{
// Information about the error is available in the
// event.error property, which is an instance of
// the SQLError class.
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
private function init():void
{
var selectStmt:SQLStatement = new SQLStatement();
// A SQLConnection named "conn" has been created previously
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT itemId, itemName, price FROM products";
selectStmt.addEventListener(SQLEvent.RESULT, resultHandler);
selectStmt.addEventListener(SQLErrorEvent.ERROR, errorHandler);

23.11.2012.

788

ACTIONSCRIPT 3.0
SQL AIR

selectStmt.execute();
}
private function resultHandler(event:SQLEvent):void
{
var result:SQLResult = selectStmt.getResult();
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var output:String = "itemId: " + row.itemId;
output += "; itemName: " + row.itemName;
output += "; price: " + row.price;
trace(output);
}
}
private function errorHandler(event:SQLErrorEvent):void
{
// Information about the error is available in the
// event.error property, which is an instance of
// the SQLError class.
}
]]>
</mx:Script>
</mx:WindowedApplication>

SELECT
products .

23.11.2012.

789

ACTIONSCRIPT 3.0
SQL AIR

var selectStmt:SQLStatement = new SQLStatement();


// A SQLConnection named "conn" has been created previously
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT itemId, itemName, price FROM products";
try
{
selectStmt.execute();
var result:SQLResult = selectStmt.getResult();
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var output:String = "itemId: " + row.itemId;
output += "; itemName: " + row.itemName;
output += "; price: " + row.price;
trace(output);
}
}
catch (error:SQLError)
{
// Information about the error is available in the
// error variable, which is an instance of
// the SQLError class.
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
private function init():void
{
var selectStmt:SQLStatement = new SQLStatement();
// A SQLConnection named "conn" has been created previously
selectStmt.sqlConnection = conn;
selectStmt.text = "SELECT itemId, itemName, price FROM products";
try
{
selectStmt.execute();
var result:SQLResult = selectStmt.getResult();

23.11.2012.

790

ACTIONSCRIPT 3.0
SQL AIR

var numResults:int = result.data.length;


for (var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
var output:String = "itemId: " + row.itemId;
output += "; itemName: " + row.itemName;
output += "; price: " + row.price;
trace(output);
}
}
catch (error:SQLError)
{
// Information about the error is available in the
// error variable, which is an instance of
// the SQLError class.
}
}
]]>
</mx:Script>
</mx:WindowedApplication>

SQLStatement
result (SQLEvent.RESULT), . ,
Responder execute(),
Responder.
execute(), .

SELECT
Adobe AIR 1.0
SELECT
. , SELECT,
getResult() SQLStatement.
var result:SQLResult = selectStatement.getResult();

getResult() SQLResult. data SQLResult


Array, SELECT.
var numResults:int = result.data.length;
for (var i:int = 0; i < numResults; i++)
{
// row is an Object representing one row of result data
var row:Object = result.data[i];
}

SELECT Object data.


, .
. , SELECT
: itemId, itemName price.
Object itemId, itemName price.
.

23.11.2012.

791

ACTIONSCRIPT 3.0
SQL AIR

SQLStatement, SELECT.
, firstName lastName
employees. .
selectResult(),
SQLStatement.getResult(), trace(). ,

SQLConnection conn. , employees
.
import
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLResult;
flash.data.SQLStatement;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;

// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var selectStmt:SQLStatement = new SQLStatement();
selectStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"SELECT firstName, lastName " +
"FROM employees";
selectStmt.text = sql;
// register listeners for the result and error events
selectStmt.addEventListener(SQLEvent.RESULT, selectResult);
selectStmt.addEventListener(SQLErrorEvent.ERROR, selectError);
// execute the statement
selectStmt.execute();
function selectResult(event:SQLEvent):void
{
// access the result data
var result:SQLResult = selectStmt.getResult();
var numRows:int = result.data.length;
for (var i:int = 0; i < numRows; i++)
{
var output:String = "";
for (var columnName:String in result.data[i])
{
output += columnName + ": " + result.data[i][columnName] + "; ";
}
trace("row[" + i.toString() + "]\t", output);
}
}
function selectError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}

23.11.2012.

792

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var selectStmt:SQLStatement = new SQLStatement();
selectStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"SELECT firstName, lastName " +
"FROM employees";
selectStmt.text = sql;
// register listeners for the result and error events
selectStmt.addEventListener(SQLEvent.RESULT, selectResult);
selectStmt.addEventListener(SQLErrorEvent.ERROR, selectError);
// execute the statement
selectStmt.execute();
}
private function selectResult(event:SQLEvent):void
{
// access the result data
var result:SQLResult = selectStmt.getResult();
var numRows:int = result.data.length;
for (var i:int = 0; i < numRows; i++)
{
var output:String = "";
for (var columnName:String in result.data[i])
{
output += columnName + ": " + result.data[i][columnName] + "; ";
}
trace("row[" + i.toString() + "]\t", output);
}
}
private function selectError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
]]>
</mx:Script>
</mx:WindowedApplication>

23.11.2012.

793

ACTIONSCRIPT 3.0
SQL AIR

, ,
. SQLStatement,
SELECT. , firstName lastName
employees.
SQLStatement.getResult(), trace(). ,
SQLConnection
conn. , employees .
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLResult;
flash.data.SQLStatement;
flash.errors.SQLError;

// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var selectStmt:SQLStatement = new SQLStatement();
selectStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"SELECT firstName, lastName " +
"FROM employees";
selectStmt.text = sql;
try
{
// execute the statement
selectStmt.execute();
// access the result data
var result:SQLResult = selectStmt.getResult();
var numRows:int = result.data.length;
for (var i:int = 0; i < numRows; i++)
{
var output:String = "";
for (var columnName:String in result.data[i])
{
output += columnName + ": " + result.data[i][columnName] + "; ";
}
trace("row[" + i.toString() + "]\t", output);
}
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}

23.11.2012.

794

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.errors.SQLError;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var selectStmt:SQLStatement = new SQLStatement();
selectStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"SELECT firstName, lastName " +
"FROM employees";
selectStmt.text = sql;
try
{
// execute the statement
selectStmt.execute();
// access the result data
var result:SQLResult = selectStmt.getResult();
var numRows:int = result.data.length;
for (var i:int = 0; i < numRows; i++)
{
var output:String = "";
for (var columnName:String in result.data[i])
{
output += columnName + ": ";
output += result.data[i][columnName] + "; ";
}
trace("row[" + i.toString() + "]\t", output);
}
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}
]]>
</mx:Script>
</mx:WindowedApplication>

23.11.2012.

795

ACTIONSCRIPT 3.0
SQL AIR

SELECT
Adobe AIR 1.0
, SELECT, Object,
, ,
. SQL SELECT
itemClass SQLStatement. itemClass, ,
SELECT, .
,
SELECT itemClass.
, itemClass, ,
. , ,
SELECT. SELECT
itemClass, .

SELECT
Adobe AIR 1.0
SELECT .
,
. ,
, ,
.
,
. ,
. ,
. ,
.
SELECT
SQLStatement.execute() ( prefetch). prefetch ,
. execute() SQLStatement
prefetch, .
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = conn;
stmt.text = "SELECT ...";
stmt.addEventListener(SQLEvent.RESULT, selectResult);
stmt.execute(20); // only the first 20 rows (or fewer) are returned

result, , .
data SQLResult , complete
, .
next() SQLStatement. execute(), next()
, result.

23.11.2012.

796

ACTIONSCRIPT 3.0
SQL AIR

function selectResult(event:SQLEvent):void
{
var result:SQLResult = stmt.getResult();
if (result.data != null)
{
// ... loop through the rows or perform other processing ...
if (!result.complete)
{
stmt.next(20); // retrieve the next 20 rows
}
else
{
stmt.removeEventListener(SQLEvent.RESULT, selectResult);
}
}
}

SQLStatement result , next()


. ,
( next()) ,
.
. SQLStatement.execute() (
prefetch) SQLStatement.next().


Adobe AIR 1.0
SQL INSERT.
,
.

INSERT
Adobe AIR 1.0
SQLStatement,
SQL INSERT.
SQLStatement
employees.
. ,
SQLConnection conn. ,
employees .

23.11.2012.

797

ACTIONSCRIPT 3.0
SQL AIR

import
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLResult;
flash.data.SQLStatement;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;

// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt:SQLStatement = new SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"INSERT INTO employees (firstName, lastName, salary) " +
"VALUES ('Bob', 'Smith', 8000)";
insertStmt.text = sql;
// register listeners for the result and failure (status) events
insertStmt.addEventListener(SQLEvent.RESULT, insertResult);
insertStmt.addEventListener(SQLErrorEvent.ERROR, insertError);
// execute the statement
insertStmt.execute();
function insertResult(event:SQLEvent):void
{
trace("INSERT statement succeeded");
}
function insertError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt:SQLStatement = new SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"INSERT INTO employees (firstName, lastName, salary) " +

23.11.2012.

798

ACTIONSCRIPT 3.0
SQL AIR

"VALUES ('Bob', 'Smith', 8000)";


insertStmt.text = sql;
// register listeners for the result and failure (status) events
insertStmt.addEventListener(SQLEvent.RESULT, insertResult);
insertStmt.addEventListener(SQLErrorEvent.ERROR, insertError);
// execute the statement
insertStmt.execute();
}
private function insertResult(event:SQLEvent):void
{
trace("INSERT statement succeeded");
}
private function insertError(event:SQLErrorEvent):void
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
]]>
</mx:Script>
</mx:WindowedApplication>

employees
. ,
SQLConnection conn. ,
employees .

23.11.2012.

799

ACTIONSCRIPT 3.0
SQL AIR

import
import
import
import

flash.data.SQLConnection;
flash.data.SQLResult;
flash.data.SQLStatement;
flash.errors.SQLError;

// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt:SQLStatement = new SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"INSERT INTO employees (firstName, lastName, salary) " +
"VALUES ('Bob', 'Smith', 8000)";
insertStmt.text = sql;
try
{
// execute the statement
insertStmt.execute();
trace("INSERT statement succeeded");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}

23.11.2012.

800

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.errors.SQLError;
private function init():void
{
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt:SQLStatement = new SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql:String =
"INSERT INTO employees (firstName, lastName, salary) " +
"VALUES ('Bob', 'Smith', 8000)";
insertStmt.text = sql;
try
{
// execute the statement
insertStmt.execute();
trace("INSERT statement succeeded");
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}
]]>
</mx:Script>
</mx:WindowedApplication>


Adobe AIR 1.0
, ,
. ,
.
.
SQLResult, .
, SELECT.
SQL, INSERT
SQLResult. SQLResult
getResult() SQLStatement,

23.11.2012.

801

ACTIONSCRIPT 3.0
SQL AIR

. , Responder
execute(), SQLResult
. SQLResult , lastInsertRowID,
, SQL
INSERT.

:
insertStmt.text = "INSERT INTO ...";
insertStmt.addEventListener(SQLEvent.RESULT, resultHandler);
insertStmt.execute();
function resultHandler(event:SQLEvent):void
{
// get the primary key
var result:SQLResult = insertStmt.getResult();
var primaryKey:Number = result.lastInsertRowID;
// do something with the primary key
}


:
insertStmt.text = "INSERT INTO ...";
try
{
insertStmt.execute();
// get the primary key
var result:SQLResult = insertStmt.getResult();
var primaryKey:Number = result.lastInsertRowID;
// do something with the primary key
}
catch (error:SQLError)
{
// respond to the error
}

, ,
, .
:

, INTEGER,
lastInsertRowID , ( ,
, AUTOINCREMENT).

( )
, INTEGER,
.
lastInsertRowID.

23.11.2012.

802

ACTIONSCRIPT 3.0
SQL AIR

. INSERT
, , lastInsertRowID
, , INSERT.
, ,
INSERT SQLResult.lastInsertRowID,
INTEGER PRIMARY KEY. INTEGER
PRIMARY KEY,
.
SQL ROWID,
_ROWID_ OID.
,
INTEGER PRIMARY KEY.
, ,
INTEGER PRIMARY KEY ,
,
.
.
SQL 1193.


Adobe AIR 1.0
SQL
SELECT INSERT, SQL 783.
SQL text SQLStatement:

UPDATE.
DELETE.
. SQL 1193.


Adobe AIR 1.0
SQLConnection.attach() ,
SQLConnection, .
name attach().
(
database-name.table-name) SQL,
, .
SQL, ,
SQLConnection.
SQLConnection, SQL,
SQLConnection. ,
.

23.11.2012.

803

ACTIONSCRIPT 3.0
SQL AIR

SQLConnection ,
.
,
SQLConnection. ,
SQLConnection ,
. , UPDATE DELETE
SQLConnection,
,
, (, , ).


Adobe AIR 1.0
, .
, , ,
. , :
, SQL .


Adobe AIR 1.0
,
. ,
,
.

, . , ,

. :
.


. , .
, , ,
. .
.
. ,
. , ,
, , .
.

, .
, , (
). , ,
.
,
. , ,
. ,

23.11.2012.

804

ACTIONSCRIPT 3.0
SQL AIR

, .
,
.


Adobe AIR 1.0
SQL
. SQL ,
SQL . SQL ,
.
SQL:
SQL
SQL .
, .
( ) SQL
SQL ,
SQL .
. SQL,
. ,
.


SQL .
, SQL
(, ).
. , ,
.


Adobe AIR 1.0
INSERT UPDATE .
,
. :
unique

. ,
. ,
.
primary key , ,
primary key unique.
not null , NULL ,

, .
check .

check ,
(, 0).

23.11.2012.

805

ACTIONSCRIPT 3.0
SQL AIR

check
(, ).
data type ( )

, .
. .
807 .
. ,
.
SQL
. .
, - . ,
,
. .
, . , ,
,
, .
.
, , .

.
. ,
. .
.
:

.
. ,
, , , ,
. .
.
INSERT

, , .
,
NULL. ,
NOT NULL.
NOT NULL

.
. , , String null,
.
,
, , , NOT
NULL CHECK. , UNIQUE ,
SELECT, .
, (, , )
.
.

23.11.2012.

806

ACTIONSCRIPT 3.0
SQL AIR

, .
, ,
:

INSERT UPDATE .
, .
.
. .
, .
. ON CONFLICT ( )
SQL 1193.
,

SQL, . ,
, . ,
, . ,
.
UNIQUE,
. , .
,
.
.


Adobe AIR 1.0
SQL, , ,
. SQL CREATE
TABLE , .
, , INSERT,
SELECT.
,
. ,
. ,
NUMERIC,
(INTEGER REAL) .
, . , 12345
NUMERIC, 12345
. SELECT
(Number), String.
, . -,
, . , , .
.
( , , ). ,
.

23.11.2012.

807

ACTIONSCRIPT 3.0
SQL AIR


SQL . 1217.



Adobe AIR 1.0
, , ,
, , .
.
,
. , .

. ,
,
. , .
, , .
.
.
.

, .
SQLConnection .
SQLConnection.open() ,
SQLConnection.openAsync() .
SQLConnection open() openAsync(),
.


Adobe AIR 1.0
, ,
, .
. ,
(, , SELECT,
, INSERT).
.

23.11.2012.

808

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
,
. , ,
.
,
. :
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
// open the database
conn.open(dbFile, OpenMode.UPDATE);
// start a transaction
conn.begin();
// add the customer record to the database
var insertCustomer:SQLStatement = new SQLStatement();
insertCustomer.sqlConnection = conn;
insertCustomer.text =
"INSERT INTO customers (firstName, lastName) " +
"VALUES ('Bob', 'Jones')";
insertCustomer.execute();
var customerId:Number = insertCustomer.getResult().lastInsertRowID;
// add a related phone number record for the customer
var insertPhoneNumber:SQLStatement = new SQLStatement();
insertPhoneNumber.sqlConnection = conn;
insertPhoneNumber.text =
"INSERT INTO customerPhoneNumbers (customerId, number) " +
"VALUES (:customerId, '800-555-1234')";
insertPhoneNumber.parameters[":customerId"] = customerId;
insertPhoneNumber.execute();
// commit the transaction
conn.commit();

,
.
, , .

23.11.2012.

809

ACTIONSCRIPT 3.0
SQL AIR

,
Adobe AIR 1.0
, ,
. ,
. ,
, ,
, . , ,
, INSERT, ,
,
. :
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
// open the database
conn.open(dbFile, SQLMode.UPDATE);
// start a transaction
conn.begin();
// add the customer record to the database
var insertCustomer:SQLStatement = new SQLStatement();
insertCustomer.sqlConnection = conn;
insertCustomer.text =
"INSERT INTO customers (firstName, lastName) " +
"VALUES ('Bob', 'Jones')";
insertCustomer.execute();
var customerId:Number = insertCustomer.getResult().lastInsertRowID;
// add a related phone number record for the customer
var insertPhoneNumber:SQLStatement = new SQLStatement();
insertPhoneNumber.sqlConnection = conn;
insertPhoneNumber.text =
"INSERT INTO customerPhoneNumbers (customerId, number) " +
"VALUES (:customerId, '800-555-1234')";
insertPhoneNumber.parameters[":customerId"] = customerId;
insertPhoneNumber.execute();
// commit the transaction
conn.commit();

23.11.2012.

810

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0

. , ,
try..catch..finally. , , try. ,
, catch. ,
(,
), finally.
try..catch..finally .
:
var conn:SQLConnection = new SQLConnection();
// The database file is in the application storage directory
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBSample.db");
// open the database
conn.open(dbFile, SQLMode.UPDATE);
// start a transaction
conn.begin();
try
{
// add the customer record to the database
var insertCustomer:SQLStatement = new SQLStatement();
insertCustomer.sqlConnection = conn;
insertCustomer.text =
"INSERT INTO customers (firstName, lastName)" +
"VALUES ('Bob', 'Jones')";
insertCustomer.execute();
var customerId:Number = insertCustomer.getResult().lastInsertRowID;
// add a related phone number record for the customer
var insertPhoneNumber:SQLStatement = new SQLStatement();
insertPhoneNumber.sqlConnection = conn;
insertPhoneNumber.text =
"INSERT INTO customerPhoneNumbers (customerId, number)" +
"VALUES (:customerId, '800-555-1234')";
insertPhoneNumber.parameters[":customerId"] = customerId;
insertPhoneNumber.execute();
// if we've gotten to this point without errors, commit the transaction
conn.commit();
}
catch (error:SQLError)
{
// rollback the transaction
conn.rollback();
}

23.11.2012.

811

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
,
SQLStatement SQLStatement
. .
SQLStatement text .
SQLStatement SQL, ,
execute() SQLStatement SQLStatement,
.
(
SQLConnection) .
.
SQLStatement execute()
.
SQLConnection, . ,
SQLStatement execute().
.
, .

result . :
// Using asynchronous execution mode
var stmt1:SQLStatement = new SQLStatement();
stmt1.sqlConnection = conn;
// ... Set statement text and parameters, and register event listeners ...
stmt1.execute();
// At this point stmt1's execute() operation is added to conn's execution queue.
var stmt2:SQLStatement = new SQLStatement();
stmt2.sqlConnection = conn;
// ... Set statement text and parameters, and register event listeners ...
stmt2.execute();
// At this point stmt2's execute() operation is added to conn's execution queue.
// When stmt1 finishes executing, stmt2 will immediately begin executing
// in the background.

.
,
( , execute()),
. , execute()
text parameters .
, ,
. ,
, .

23.11.2012.

812

ACTIONSCRIPT 3.0
SQL AIR

SQLConnection.begin()
SQLConnection begin. execute()
SQLStatement.
, begin.
SQLStatement.execute() .

SQL
Adobe AIR 1.5
Adobe AIR . ,
AIR
. Adobe AIR 1.5
.
.
( ),
. ,
.
.
, .
. ,
. ,
SQL , , .


Adobe AIR 1.5
, ,
. Adobe AIR .
, :

- ,
, , (
)

, ,
. ,
,
.

, ,
SQL 767,
, ,
.
, , ,
. , , ,
. .
817.

23.11.2012.

813

ACTIONSCRIPT 3.0
SQL AIR


.
ByteArray . AIR, ,
, , .
.

, ByteArray.
,
.
. 763.


Adobe AIR 1.5
.
, .
. ,
. .
816. , ,
,
.

, 772.
SQLConnection, .
open() openAsync() SQLConnection,
, .
, encryptionKey (
open() openAsync()).
encryptionKey ByteArray, 16 .
.
.
, .
var conn:SQLConnection = new SQLConnection();
var encryptionKey:ByteArray = new ByteArray();
encryptionKey.writeUTFBytes("Some16ByteString"); // This technique is not secure!
// Create an encrypted database in asynchronous mode
conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);
// Create an encrypted database in synchronous mode
conn.open(dbFile, SQLMode.CREATE, false, 1024, encryptionKey);

, , .
: 819.

23.11.2012.

814

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.5
,
.
780. open()
, openAsync()
. ,
encryptionKey ( open()
openAsync()).
, . open()
SQLError. openAsync() SQLConnection SQLErrorEvent, error
SQLError. SQLError, ,
errorID 3138.
.

. .
, .
import
import
import
import
import

flash.data.SQLConnection;
flash.data.SQLMode;
flash.events.SQLErrorEvent;
flash.events.SQLEvent;
flash.filesystem.File;

var conn:SQLConnection = new SQLConnection();


conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler);
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample.db");
var encryptionKey:ByteArray = new ByteArray();
encryptionKey.writeUTFBytes("Some16ByteString"); // This technique is not secure!
conn.openAsync(dbFile, SQLMode.UPDATE, null, false, 1024, encryptionKey);
function openHandler(event:SQLEvent):void
{
trace("the database opened successfully");
}
function errorHandler(event:SQLErrorEvent):void
{
if (event.error.errorID == 3138)
{
trace("Incorrect encryption key");
}
else
{
trace("Error message:", event.error.message);
trace("Details:", event.error.details);
}
}

23.11.2012.

815

ACTIONSCRIPT 3.0
SQL AIR


. .
, .
import flash.data.SQLConnection;
import flash.data.SQLMode;
import flash.filesystem.File;
var conn:SQLConnection = new SQLConnection();
var dbFile:File = File.applicationStorageDirectory.resolvePath("DBSample.db");
var encryptionKey:ByteArray = new ByteArray();
encryptionKey.writeUTFBytes("Some16ByteString"); // This technique is not secure!
try
{
conn.open(dbFile, SQLMode.UPDATE, false, 1024, encryptionKey);
trace("the database was created successfully");
}
catch (error:SQLError)
{
if (error.errorID == 3138)
{
trace("Incorrect encryption key");
}
else
{
trace("Error message:", error.message);
trace("Details:", error.details);
}
}

, , .
: 819.


Adobe AIR 1.5
, .
,
SQLConnection open() openAsync().
, reencrypt(),
.
, , reencrypt() ,
.
open(), reencrypt()
. , :
var newKey:ByteArray = new ByteArray();
// ... generate the new key and store it in newKey
conn.reencrypt(newKey);

23.11.2012.

816

ACTIONSCRIPT 3.0
SQL AIR

, openAsync(), reencrypt()
. reencrypt() .
, SQLConnection reencrypt. ,
, :
var newKey:ByteArray = new ByteArray();
// ... generate the new key and store it in newKey
conn.addEventListener(SQLEvent.REENCRYPT, reencryptHandler);
conn.reencrypt(newKey);
function reencryptHandler(event:SQLEvent):void
{
// save the fact that the key changed
}

reencrypt() .
(, ),
. -
.
reencrypt() .
null , 16- ByteArray, reencrypt(),
.


Adobe AIR 1.5
813 ,
. ,
( )
. , ,
, . ,
,
,
.
.
,
, .
, ,
, .
.

23.11.2012.

817

ACTIONSCRIPT 3.0
SQL AIR

, ,
, .
.

,
, ,
. ,
, , SSL.
.

, , .

,
(, ). ,
- , (, ,
).
,
, .

,
. . :
819.
,
:

.
,
. , ,
.

AIR ( HTML) ( SWF-).


, :


, , (,
)

AIR AES CCM.


-.
. : 819.

, , ,
. ,
.
. ,
AIR, , ,
.

23.11.2012.

818

ACTIONSCRIPT 3.0
SQL AIR

:
Adobe AIR 1.5
.
.

. , ,
, ,
.
: ActionScript, (
EncryptionKeyGenerator), , ,
. . ,
821.

EncryptionKeyGenerator

Adobe AIR 1.5


EncryptionKeyGenerator
. .
EncryptionKeyGenerator 826.
, EncryptionKeyGenerator :
1 EncryptionKeyGenerator SWC.

EncryptionKeyGenerator ActionScript 3.0 (as3corelib)


. as3corelib, . SWC
.
2 EncryptionKeyGenerator ( as3corelib SWC) ,

.
3 import EncryptionKeyGenerator .
import com.adobe.air.crypto.EncryptionKeyGenerator;

4 , , ,

EncryptionKeyGenerator, EncryptionKeyGenerator().
var keyGenerator:EncryptionKeyGenerator = new EncryptionKeyGenerator();

5 :
var password:String = passwordInput.text;
if (!keyGenerator.validateStrongPassword(password))
{
// display an error message
return;
}

23.11.2012.

819

ACTIONSCRIPT 3.0
SQL AIR

EncryptionKeyGenerator
( ). EncryptionKeyGenerator
. ,
. ,
validateStrongPassword() EncryptionKeyGenerator. ,
.
6 :
var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password);

getEncryptionKey() (16- ByteArray).



.
getEncryptionKey() , ,
5.
.

.
. - . ,
,
,
.
getEncryptionKey() () overrideSaltELSKey.
EncryptionKeyGenerator ( -),
. , (ELS) AIR.
EncryptionKeyGenerator ELS.
, , ,
.
ELS. ,
getEncryptionKey(), :
var customKey:String = "My custom ELS salt key";
var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password, customKey);

, getEncryptionKey(),

. open() openAsync()
SQLConnection, 814
815.
,
.
openAsync(), :
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, openError);
conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);

23.11.2012.

820

ACTIONSCRIPT 3.0
SQL AIR

.
, , ,
.
openError(). if , (,
)
EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID.
, , . (
, .) ,
:
if (!createNewDB && event.error.errorID ==
EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID)
{
statusMsg.text = "Incorrect password!";
}
else
{
statusMsg.text = "Error creating or opening database.";
}

.
, 821.

Adobe AIR 1.5



. .
EncryptionKeyGenerator .
EncryptionKeyGenerator ActionScript 3.0 (as3corelib)
. as3corelib, . SWC
.
Flex
MXML- ,
:

23.11.2012.

821

ACTIONSCRIPT 3.0
SQL AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
creationComplete="init();">
<mx:Script>
<![CDATA[
import com.adobe.air.crypto.EncryptionKeyGenerator;
private const dbFileName:String = "encryptedDatabase.db";
private var dbFile:File;
private var createNewDB:Boolean = true;
private var conn:SQLConnection;
// ------- Event handling ------private function init():void
{
conn = new SQLConnection();
dbFile = File.applicationStorageDirectory.resolvePath(dbFileName);
if (dbFile.exists)
{
createNewDB = false;
instructions.text = "Enter your database password to open the encrypted
database.";
openButton.label = "Open Database";
}
}
private function openConnection():void
{
var password:String = passwordInput.text;
var keyGenerator:EncryptionKeyGenerator = new EncryptionKeyGenerator();
if (password == null || password.length <= 0)
{
statusMsg.text = "Please specify a password.";
return;
}
if (!keyGenerator.validateStrongPassword(password))
{
statusMsg.text = "The password must be 8-32 characters long. It must
contain at least one lowercase letter, at least one uppercase letter, and at least one number
or symbol.";
return;
}
passwordInput.text = "";
passwordInput.enabled = false;
openButton.enabled = false;
var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password);
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, openError);

23.11.2012.

822

ACTIONSCRIPT 3.0
SQL AIR

conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);


}
private function openHandler(event:SQLEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openHandler);
conn.removeEventListener(SQLErrorEvent.ERROR, openError);
statusMsg.setStyle("color", 0x009900);
if (createNewDB)
{
statusMsg.text = "The encrypted database was created successfully.";
}
else
{
statusMsg.text = "The encrypted database was opened successfully.";
}
}
private function openError(event:SQLErrorEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openHandler);
conn.removeEventListener(SQLErrorEvent.ERROR, openError);
if (!createNewDB && event.error.errorID ==
EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID)
{
statusMsg.text = "Incorrect password!";
}
else
{
statusMsg.text = "Error creating or opening database.";
}
}
]]>
</mx:Script>
<mx:Text id="instructions" text="Enter a password to create an encrypted database. The next
time you open the application, you will need to re-enter the password to open the database
again." width="75%" height="65"/>
<mx:HBox>
<mx:TextInput id="passwordInput" displayAsPassword="true"/>
<mx:Button id="openButton" label="Create Database" click="openConnection();"/>
</mx:HBox>
<mx:Text id="statusMsg" color="#990000" width="75%"/>
</mx:WindowedApplication>

Flash Professional
FLA- ,
. FLA- ,
:

23.11.2012.

823

ACTIONSCRIPT 3.0
SQL AIR

instructions

Label

passwordInput

TextInput

openButton

Button

statusMsg

Label

(
)

1 .
:
import com.adobe.air.crypto.EncryptionKeyGenerator;
const dbFileName:String = "encryptedDatabase.db";
var dbFile:File;
var createNewDB:Boolean = true;
var conn:SQLConnection;
init();
// ------- Event handling ------function init():void
{
passwordInput.displayAsPassword = true;
openButton.addEventListener(MouseEvent.CLICK, openConnection);
statusMsg.setStyle("textFormat", new TextFormat(null, null, 0x990000));
conn = new SQLConnection();
dbFile = File.applicationStorageDirectory.resolvePath(dbFileName);
if (dbFile.exists)
{
createNewDB = false;
instructions.text = "Enter your database password to open the encrypted database.";
openButton.label = "Open Database";
}
else
{
instructions.text = "Enter a password to create an encrypted database. The next time
you open the application, you will need to re-enter the password to open the database again.";
openButton.label = "Create Database";
}
}
function openConnection(event:MouseEvent):void
{
var keyGenerator:EncryptionKeyGenerator = new EncryptionKeyGenerator();
var password:String = passwordInput.text;
if (password == null || password.length <= 0)

23.11.2012.

824

ACTIONSCRIPT 3.0
SQL AIR

{
statusMsg.text = "Please specify a password.";
return;
}
if (!keyGenerator.validateStrongPassword(password))
{
statusMsg.text = "The password must be 8-32 characters long. It must contain at least
one lowercase letter, at least one uppercase letter, and at least one number or symbol.";
return;
}
passwordInput.text = "";
passwordInput.enabled = false;
openButton.enabled = false;
var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password);
conn.addEventListener(SQLEvent.OPEN, openHandler);
conn.addEventListener(SQLErrorEvent.ERROR, openError);
conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);
}
function openHandler(event:SQLEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openHandler);
conn.removeEventListener(SQLErrorEvent.ERROR, openError);
statusMsg.setStyle("textFormat", new TextFormat(null, null, 0x009900));
if (createNewDB)
{
statusMsg.text = "The encrypted database was created successfully.";
}
else
{
statusMsg.text = "The encrypted database was opened successfully.";
}
}
function openError(event:SQLErrorEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openHandler);
conn.removeEventListener(SQLErrorEvent.ERROR, openError);
if (!createNewDB && event.error.errorID ==
EncryptionKeyGenerator.ENCRYPTED_DB_PASSWORD_ERROR_ID)
{
statusMsg.text = "Incorrect password!";
}
else
{
statusMsg.text = "Error creating or opening database.";
}
}

23.11.2012.

825

ACTIONSCRIPT 3.0
SQL AIR

EncryptionKeyGenerator
Adobe AIR 1.5
EncryptionKeyGenerator,
.
EncryptionKeyGenerator
819. , , ,
. , -
, .
EncryptionKeyGenerator ActionScript 3.0 (as3corelib)
. as3corelib, .
.
EncryptionKeyGenerator getEncryptionKey(),
,
.
,
.

Adobe AIR 1.5
getEncryptionKey(), .
. ,
, , , ,
.
, , .
.
EncryptionKeyGenerator getEncryptionKey(),
( password ):
var keyGenerator:EncryptionKeyGenerator = new EncryptionKeyGenerator();
var encryptionKey:ByteArray = keyGenerator.getEncryptionKey(password);

, EncryptionKeyGenerator getEncryptionKey(),

. EncryptionKeyGenerator , 8-32 .
.
, ,
STRONG_PASSWORD_PATTERN:
private static const STRONG_PASSWORD_PATTERN:RegExp =
/(?=^.{8,32}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;

, , validateStrongPassword()
EncryptionKeyGenerator. :

23.11.2012.

826

ACTIONSCRIPT 3.0
SQL AIR

public function vaidateStrongPassword(password:String):Boolean


{
if (password == null || password.length <= 0)
{
return false;
}
return STRONG_PASSWORD_PATTERN.test(password))
}

getEncryptionKey() validateStrongPassword()
EncryptionKeyGenerator , , .
validateStrongPassword() ,
getEncryptionKey(), .
256
Adobe AIR 1.5
, 256 . ,
256 (32 ) ,
.
getEncryptionKey() concatenatePassword()
.
var concatenatedPassword:String = concatenatePassword(password);

concatenatePassword().
private function concatenatePassword(pwd:String):String
{
var len:int = pwd.length;
var targetLength:int = 32;
if (len == targetLength)
{
return pwd;
}
var repetitions:int = Math.floor(targetLength / len);
var excess:int = targetLength % len;
var result:String = "";
for (var i:uint = 0; i < repetitions; i++)
{
result += pwd;
}
result += pwd.substr(0, excess);
return result;
}

256 , ,
256 .
, , 256 .

23.11.2012.

827

ACTIONSCRIPT 3.0
SQL AIR

256- -
Adobe AIR 1.5
256- -,
. ,
. -
,
, +, , .
,
. - ,
, .
getEncryptionKey() ,
256- -. -
.
- salt. , , .
var salt:ByteArray = EncryptedLocalStore.getItem(saltKey);
if (salt == null)
{
salt = makeSalt();
EncryptedLocalStore.setItem(saltKey, salt);
}

-, makeSalt() 256- .
,
ByteArray. makeSalt() Math.random() .
Math.random() 256 .
, Math.random() .
uint 0 4294967295 ( uint). uint
, uint 32 . 256-
uint ByteArray. makeSalt():
private function makeSalt():ByteArray
{
var result:ByteArray = new ByteArray;
for (var i:uint = 0; i < 8; i++)
{
result.writeUnsignedInt(Math.round(Math.random() * uint.MAX_VALUE));
}
return result;
}

- (ELS) ELS,
String, -. -,
. .
EncryptionKeyGenerator ELS,
SALT_ELS_KEY.
ELS getEncryptionKey(). ,
, ELS saltKey.
EncryptedLocalStore.setItem() EncryptedLocalStore.getItem(), .

23.11.2012.

828

ACTIONSCRIPT 3.0
SQL AIR

256- - XOR
Adobe AIR 1.5
256- 256- -.
XOR - .
256- , .
, ,
- .
,
.
XOR unhashedKey.
XOR xorBytes():
var unhashedKey:ByteArray = xorBytes(concatenatedPassword, salt);

XOR ^) uint uint. ( uint


32 .) , xorBytes(),
String () ByteArray (). , 32
XOR.
private function xorBytes(passwordString:String, salt:ByteArray):ByteArray
{
var result:ByteArray = new ByteArray();
for (var i:uint = 0; i < 32; i += 4)
{
// ...
}
return result;
}

32 (4 ) passwordString.
uint (o1) . charCodeAt()
. uint
(<<), o1. , (i)
8 (<<);
24 , o1. (i + 1) 8
16 o1.
.
// ...
// Extract 4 bytes from the password string and convert to a uint
var o1:uint = passwordString.charCodeAt(i) << 24;
o1 += passwordString.charCodeAt(i + 1) << 16;
o1 += passwordString.charCodeAt(i + 2) << 8;
o1 += passwordString.charCodeAt(i + 3);
// ...

o1 32 passwordString. 32
salt readUnsignedInt(). 32 uint o2.

23.11.2012.

829

ACTIONSCRIPT 3.0
SQL AIR

// ...
salt.position = i;
var o2:uint = salt.readUnsignedInt();
// ...

32- (uint) XOR,


ByteArray result.
// ...
var xor:uint = o1 ^ o2;
result.writeUnsignedInt(xor);
// ...

ByteArray, XOR.
// ...
}
return result;
}


Adobe AIR 1.5
- ,
SHA-256.

.
ByteArray unhashedKey, ,
-. ActionScript 3.0 (as3corelib)
SHA256 com.adobe.crypto. SHA256.hashBytes() SHA-256
ByteArray String, 256-
. EncryptionKeyGenerator SHA256 .
var hashedKey:String = SHA256.hashBytes(unhashedKey);


Adobe AIR 1.5
ByteArray 16 (128 ).
SHA-256 256- . ,
128
.
EncryptionKeyGenerator 128 ,
generateEncryptionKey().
getEncryptionKey():
var encryptionKey:ByteArray = generateEncryptionKey(hashedKey);
return encryptionKey;

23.11.2012.

830

ACTIONSCRIPT 3.0
SQL AIR

128 .
, ,
. , 128
128 .
generateEncryptionKey() ,
18- . , SHA256 String,
256- - . 128
ByteArray. for
String,
ByteArray. SHA-256 String
64 . 128 32 String,
4 . , ByteArray, 1
(8 ), hash String.
0 31 (32 ) 2 .
.
17 (18- ), position
(i) 17. substr() String
. hex.
parseInt() hex String
. byte. ,
byte result ByteArray, writeByte().
, result ByteArray 16
.
private function generateEncryptionKey(hash:String):ByteArray
{
var result:ByteArray = new ByteArray();
for (var i:uint = 0; i < 32; i += 2)
{
var position:uint = i + 17;
var hex:String = hash.substr(position, 2);
var byte:int = parseInt(hex, 16);
result.writeByte(byte);
}
return result;
}

SQL
Adobe AIR 1.0
SQL
. ,
. .
. ,
. ,
.

23.11.2012.

831

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
AIR SQL ,
, . . ,
.
.
. ,
,
.
, , . ,
,
. ,
.
AIR
.
, AIR, (,
File.applicationDirectory).
. AIR .

723 ( )
.

SQL
Adobe AIR 1.0
,
,
SQL.


Adobe AIR 1.0
,
SQLConnection open() openAsync() (,
) . .
780.


Adobe AIR 1.0
,
SQLConnection ,
. . 780.

23.11.2012.

832

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
,
, .
,
808, ,
. , ,
. , SQL INSERT ,
, , SELECT,
.
. , ,
, , .

.
, ,
. ,
, SELECT.
SELECT 796.
. ,
,
, .
. ,
, ,
.
SQLStatement SQL,
, SQL,
. .
812.

SQL
SQLStatement
Adobe AIR 1.0
SQLStatement SQL,
. SQLStatement
SQL. , , SQL,
. SQLStatement
execute() .
SQLStatement SQL, text
.

23.11.2012.

833

ACTIONSCRIPT 3.0
SQL AIR


Adobe AIR 1.0
SQLStatement
.
SQL. ( SQL).
,
. .
784.

23.11.2012.

834

835

41.

Flash Player 9 , Adobe AIR 1.0


ByteArray , .
.
, 8 ,
, , .
ByteArray , ,
, .
writeObject() AMF (Action Message Format)
ByteArray, readObject() ByteArray
. , , . . ,
. ,
. AMF
.
Adobe AIR zip- ,
zip- .


flash.utils.ByteArray
flash.utils.IExternalizable
AMF (Action Message Format)

ByteArray
Flash Player 9 , Adobe AIR 1.0
ByteArray flash.utils. ByteArray ActionScript 3.0,
ByteArray , :
import flash.utils.ByteArray;
var stream:ByteArray = new ByteArray();

23.11.2012.

ACTIONSCRIPT 3.0

ByteArray
Flash Player 9 , Adobe AIR 1.0
, ,
. ,
, , , . . MP3- ID3,
, , , .
. .
ByteArray , .
readBytes() writeBytes(), readInt() writeInt(), readFloat() writeFloat(), readObject()
writeObject(), readUTFBytes() writeUTFBytes().

.
, ,
ByteArray.
ByteArray (writeUTFBytes() writeFloat()).
.
// The following example reads a simple Array (groceries), made up of strings
// and floating-point numbers, and writes it to a ByteArray.
import flash.utils.ByteArray;
// define the grocery list Array
var groceries:Array = ["milk", 4.50, "soup", 1.79, "eggs", 3.19, "bread" , 2.35]
// define the ByteArray
var bytes:ByteArray = new ByteArray();
// for each item in the array
for (var i:int = 0; i < groceries.length; i++) {
bytes.writeUTFBytes(groceries[i++]); //write the string and position to the next item
bytes.writeFloat(groceries[i]);// write the float
trace("bytes.position is: " + bytes.position);//display the position in ByteArray
}
trace("bytes length is: " + bytes.length);// display the length

position
Flash Player 9 , Adobe AIR 1.0
position , ByteArray
. position 0 (), :
var bytes:ByteArray = new ByteArray();
trace("bytes.position is initially: " + bytes.position); // 0

ByteArray position,
, . ,
ByteArray, position ,
ByteArray:

23.11.2012.

836

ACTIONSCRIPT 3.0

var bytes:ByteArray = new ByteArray();


trace("bytes.position is initially: " + bytes.position); // 0
bytes.writeUTFBytes("Hello World!");
trace("bytes.position is now: " + bytes.position);// 12

, position .
var bytes:ByteArray = new ByteArray();
trace("bytes.position is initially: " + bytes.position); // 0
bytes.writeUTFBytes("Hello World!");
trace("bytes.position is now: " + bytes.position);// 12
bytes.position = 0;
trace("The first 6 bytes are: " + (bytes.readUTFBytes(6)));//Hello
trace("And the next 6 bytes are: " + (bytes.readUTFBytes(6)));// World!

, position ByteArray,
.

bytesAvailable length
Flash Player 9 , Adobe AIR 1.0
length bytesAvailable ByteArray ,
. , .
ByteArray, ByteArray ,
(bytesAvailable <= 0).
var bytes:ByteArray = new ByteArray();
var text:String = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vivamus etc.";
bytes.writeUTFBytes(text); // write the text to the ByteArray
trace("The length of the ByteArray is: " + bytes.length);// 70
bytes.position = 0; // reset position
while (bytes.bytesAvailable > 0 && (bytes.readUTFBytes(1) != 'a')) {
//read to letter a or end of bytes
}
if (bytes.position < bytes.bytesAvailable) {
trace("Found the letter a; position is: " + bytes.position); // 23
trace("and the number of bytes available is: " + bytes.bytesAvailable);// 47
}

endian
Flash Player 9 , Adobe AIR 1.0
, . . ,
. , 4 32 .
, .
(
) ( ). ,
0x31323334 ,
, a0 4 , a3 :

23.11.2012.

837

ACTIONSCRIPT 3.0

a0

a1

a2

a3

31

32

33

34

a0

a1

a2

a3

34

33

32

31

endian ByteArray .
"bigEndian" "littleEndian", Endian
BIG_ENDIAN LITTLE_ENDIAN endian .

compress() uncompress()
Flash Player 9 , Adobe AIR 1.0
compress() ByteArray ,
. uncompress() ByteArray
. compress() uncompress()
, position .
CompressionAlgorithm ,
. ByteArray deflate ( AIR), zlib lzma.
zlib http://www.ietf.org/rfc/rfc1950.txt. lzma
Flash Player 11.4 AIR 3.4. http://www.7-zip.org/7z.html.
deflate : zlib, gzip zip.
deflate http://www.ietf.org/rfc/rfc1951.txt.
ByteArray bytes lzma:
bytes.compress(CompressionAlgorithm.LZMA);

ByteArray deflate:
bytes.uncompress(CompressionAlgorithm.LZMA);


Flash Player 9 , Adobe AIR 1.0
readObject() writeObject() ByteArray,
AMF (Action Message Format). AMF Adobe.
ActionScript 3.0, Netstream, NetConnection, NetStream,
LocalConnection Shared Objects.

23.11.2012.

838

ACTIONSCRIPT 3.0

. AMF 13 .
value-type = undefined-marker | null-marker | false-marker | true-marker | integer-type |
double-type | string-type | xml-doc-type | date-type | array-type | object-type |
xml-type | byte-array-type

; ,
, null, true false,
.
AMF: AMF0 AMF3. AMF 0
. AMF 3
AMF 0: , ,
, , ActionScript 3.0.
ByteArray.objectEcoding AMF,
. flash.net.ObjectEncoding AMF:
ObjectEncoding.AMF0 ObjectEncoding.AMF3.
writeObject() XML- ByteArray,
Deflate order .
Wrote order file to desktop! ( !) AIR .
import flash.filesystem.*;
import flash.display.Sprite;
import flash.display.TextField;
import flash.utils.ByteArray;
public class WriteObjectExample extends Sprite
{
public function WriteObjectExample()
{
var bytes:ByteArray = new ByteArray();
var myLabel:TextField = new TextField();
myLabel.x = 150;
myLabel.y = 150;
myLabel.width = 200;
addChild(myLabel);
var myXML:XML =
<order>
<item id='1'>
<menuName>burger</menuName>
<price>3.95</price>
</item>
<item id='2'>
<menuName>fries</menuName>
<price>1.45</price>
</item>
</order>;
// Write XML object to ByteArray

23.11.2012.

839

ACTIONSCRIPT 3.0

bytes.writeObject(myXML);
bytes.position = 0;//reset position to beginning
bytes.compress(CompressionAlgorithm.DEFLATE);// compress ByteArray
writeBytesToFile("order.xml", bytes);
myLabel.text = "Wrote order file to desktop!";
}
private function writeBytesToFile(fileName:String, data:ByteArray):void
{
var outFile:File = File.desktopDirectory; // dest folder is desktop
outFile = outFile.resolvePath(fileName); // name of file to write
var outStream:FileStream = new FileStream();
// open output file stream in WRITE mode
outStream.open(outFile, FileMode.WRITE);
// write out the file
outStream.writeBytes(data, 0, data.length);
// close it
outStream.close();
}
}

readObject() AMF ByteArray


. order ByteArray (inBytes),
, readObject(), XML- orderXML.
for each(), .
objectEncoding order.
import
import
import
import

flash.filesystem.*;
flash.display.Sprite;
flash.display.TextField;
flash.utils.ByteArray;

public class ReadObjectExample extends Sprite


{
public function ReadObjectExample()
{
var inBytes:ByteArray = new ByteArray();
// define text area for displaying XML content
var myTxt:TextField = new TextField();
myTxt.width = 550;
myTxt.height = 400;
addChild(myTxt);
//display objectEncoding and file heading
myTxt.text = "Object encoding is: " + inBytes.objectEncoding + "\n\n" + "order file: \n\n";
readFileIntoByteArray("order", inBytes);
inBytes.position = 0; // reset position to beginning
inBytes.uncompress(CompressionAlgorithm.DEFLATE);
inBytes.position = 0;//reset position to beginning
// read XML Object
var orderXML:XML = inBytes.readObject();

23.11.2012.

840

841

ACTIONSCRIPT 3.0

// for each node in orderXML


for each (var child:XML in orderXML)
{
// append child node to text area
myTxt.text += child + "\n";
}
}
// read specified file into byte array
private function readFileIntoByteArray(fileName:String, data:ByteArray):void
{
var inFile:File = File.desktopDirectory; // source folder is desktop
inFile = inFile.resolvePath(fileName); // name of file to read
var inStream:FileStream = new FileStream();
inStream.open(inFile, FileMode.READ);
inStream.readBytes(data);
inStream.close();
}
}

ByteArray: zip-
Adobe AIR 1.0
, zip-, .
, ByteArray
.
zip- PKWARE,
http://www.pkware.com/documents/casestudies/APPNOTE.TXT.
zip-, . . (
). , zip- (
, zip- , ).
: , ,
, Zip64,
Zip64, .
zip-, ,
. .
:

2 (8=DEFLATE; 0=UNCOMPRESSED)

23.11.2012.

842

ACTIONSCRIPT 3.0

crc-32

, ,
. 0 (), ; 8,
DEFLATE; ,
.
(taFiles).
zip- :
, , . MXML
Flex :
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
creationComplete="init();">
<mx:Script>
<![CDATA[
// The application code goes here
]]>
</mx:Script>
<mx:Form>
<mx:FormItem label="Output">
<mx:TextArea id="taFiles" width="320" height="150"/>
</mx:FormItem>
</mx:Form>
</mx:WindowedApplication>


import flash.filesystem.*;
import flash.utils.ByteArray;
import flash.events.Event;

Flash

23.11.2012.

ACTIONSCRIPT 3.0

import fl.controls.*;
//requires TextArea and Label components in the Library
var taFiles = new TextArea();
var output = new Label();
taFiles.setSize(320, 150);
taFiles.move(10, 30);
output.move(10, 10);
output.width = 150;
output.text = "Contents of HelloAir.zip";
addChild(taFiles);
addChild(output);

ByteArray bytes
var bytes:ByteArray = new ByteArray();


//
var
var
var
var
var
var
var
var

variables for reading fixed portion of file header


fileName:String = new String();
flNameLength:uint;
xfldLength:uint;
offset:uint;
compSize:uint;
uncompSize:uint;
compMethod:int;
signature:int;

File (zfile) FileStream (zStream), zip-,


zip-, HelloAIR.zip .
// File variables for accessing .zip file
var zfile:File = File.desktopDirectory.resolvePath("HelloAIR.zip");
var zStream:FileStream = new FileStream();

Flex init(),
creationComplete mx:WindowedApplication.
// for Flex
private function init():void
{

zip- READ.
zStream.open(zfile, FileMode.READ);

endian bytes LITTLE_ENDIAN,


.
bytes.endian = Endian.LITTLE_ENDIAN;

while() , ,
.
while (zStream.position < zfile.size)
{

30 ByteArray bytes. 30
.

23.11.2012.

843

844

ACTIONSCRIPT 3.0

// read fixed metadata portion of local file header


zStream.readBytes(bytes, 0, 30);

(signature) 30- . ZIP ,


0x04034b50. , , zip-,
. while ,
.
bytes.position = 0;
signature = bytes.readInt();
// if no longer reading data files, quit
if (signature != 0x04034b50)
{
break;
}

8
compMethod. , ,
. , zip-
DEFLATE. DEFLATE,
compMethod 8; , compMethod 0.
bytes.position = 8;
compMethod = bytes.readByte();

// store compression method (8 == Deflate)

30 , , ,
. offset .
,
26 28.
offset = 0;// stores length of variable portion of metadata
bytes.position = 26; // offset to file name length
flNameLength = bytes.readShort();// store file name
offset += flNameLength; // add length of file name
bytes.position = 28;// offset to extra field length
xfldLength = bytes.readShort();
offset += xfldLength;// add length of extra field

,
offset.
// read variable length bytes between fixed-length header and compressed file data
zStream.readBytes(bytes, 30, offset);


.
// Flash version
bytes.position = 30;
fileName = bytes.readUTFBytes(flNameLength); // read file name
taFiles.appendText(fileName + "\n"); // write file name to text area
bytes.position = 18;
compSize = bytes.readUnsignedInt(); // store size of compressed portion
taFiles.appendText("\tCompressed size is: " + compSize + '\n');
bytes.position = 22; // offset to uncompressed size
uncompSize = bytes.readUnsignedInt(); // store uncompressed size
taFiles.appendText("\tUncompressed size is: " + uncompSize + '\n');

23.11.2012.

ACTIONSCRIPT 3.0

// Flex version
bytes.position = 30;
fileName = bytes.readUTFBytes(flNameLength); // read file name
taFiles.text += fileName + "\n"; // write file name to text area
bytes.position = 18;
compSize = bytes.readUnsignedInt(); // store size of compressed portion
taFiles.text += "\tCompressed size is: " + compSize + '\n';
bytes.position = 22; // offset to uncompressed size
uncompSize = bytes.readUnsignedInt(); // store uncompressed size
taFiles.text += "\tUncompressed size is: " + uncompSize + '\n';

bytes ,
, 30 .
, , .
// read compressed file to offset 0 of bytes; for uncompressed files
// the compressed and uncompressed size is the same
if (compSize == 0) continue;
zStream.readBytes(bytes, 0, compSize);

, outfile(),
. outfile() ,
.
if (compMethod == 8) // if file is compressed, uncompress
{
bytes.uncompress(CompressionAlgorithm.DEFLATE);
}
outFile(fileName, bytes);
// call outFile() to write out the file

bytes.uncompress(CompressionAlgorithm.DEFLATE)
AIR. , deflate, AIR,
Flash Player, inflate() ByteArray.
while, init() Flex;
outFile(). while
zip-. , , ,
zip- .
} // end of while loop
} // for Flex version, end of init() method and application

outfile() WRITE ,
filename. data
(outStream), .

23.11.2012.

845

ACTIONSCRIPT 3.0

// Flash version
function outFile(fileName:String, data:ByteArray):void
{
var outFile:File = File.desktopDirectory; // destination folder is desktop
outFile = outFile.resolvePath(fileName); // name of file to write
var outStream:FileStream = new FileStream();
// open output file stream in WRITE mode
outStream.open(outFile, FileMode.WRITE);
// write out the file
outStream.writeBytes(data, 0, data.length);
// close it
outStream.close();
}
private function outFile(fileName:String, data:ByteArray):void
{
var outFile:File = File.desktopDirectory; // dest folder is desktop
outFile = outFile.resolvePath(fileName); // name of file to write
var outStream:FileStream = new FileStream();
// open output file stream in WRITE mode
outStream.open(outFile, FileMode.WRITE);
// write out the file
outStream.writeBytes(data, 0, data.length);
// close it
outStream.close();
}

23.11.2012.

846

847

42.

Flash Player 9 , Adobe AIR 1.0
Flash Player AIR
. , -
.
. API- Flash Player AIR
, . API-
IP- , UDP, TCP, HTTP, RTMP RTMFP.
:

Loader

URLLoader

FileReference

NetConnection

Sound


SWF, PNG, JPEG, GIF

(text, XML, binary


. .)

HTTP, HTTPS

HTTP, HTTPS

HTTP

.
URLLoader 875
.

, ,
ActionScript Message
(AMF)

HTTP, HTTPS,
RTMP, RTMFP

.
FileReference 701
,
.

HTTP

XMLSocket

XML

TCP

Socket

TCP

SecureSocket (AIR)

ServerSocket (AIR)

.
214.
.

.

TCP

SSLv3
TLSv1

TCP

.
507.

.
.
476.
XML
XMLSocket.
. XML- 861.
- TCP.
.
856.
- TCP,

SSL TLS.
.
(AIR) 857.

TCP.
.
865.

23.11.2012.

848

ACTIONSCRIPT 3.0

DatagramSocket (AIR)

UDP

UDP.
. UDP- (AIR)
867

-
. HTML cookie.
Flash Player SharedObject. .
753. ( SharedObject AIR,
.)
Flash Player AIR Flash Player AIR
, LocalConnection. , ( ) SWF - . SWF-,
-, AIR. .
Flash Player AIR 890.
, SWF-,
NativeProcess, AIR 2. NativeProcess AIR
. . AIR
897.
, AIR,
:

NetworkInfo: , IP-
. . 849.

DNSResolver: DNS. . (DNS)


853.

ServiceMonitor: . .
851.

URLMonitor: URL-. .
HTTP 852.

SocketMonitor SecureSocketMonitor: . .
853.

,
.
, -

. , ,
, .
, URL- URL-

( ) .
name=value. (. . -)
: variable1=value1&variable2=value2.
.
MIME ,

. .

23.11.2012.

ACTIONSCRIPT 3.0

(, - Flash Player AIR)


.
HTTP , -

, .
(, AIR -)

( HTTP) -,
GET POST. , ,
, , ,
, ,
.
.
.
.


Adobe AIR 2
NetworkInfo
, . NetworkInfo ,
. , networkInfo,
NetworkInfo. NetworkInfo networkChange
.
findInterfaces() NetworkInterface.
NetworkInterface . NetworkInterface
, IP-, , , ,
.
NetworkInterface .

23.11.2012.

849

ACTIONSCRIPT 3.0

package {
import flash.display.Sprite;
import flash.net.InterfaceAddress;
import flash.net.NetworkInfo;
import flash.net.NetworkInterface;
public class NetworkInformationExample extends Sprite
{
public function NetworkInformationExample()
{
var networkInfo:NetworkInfo = NetworkInfo.networkInfo;
var interfaces:Vector.<NetworkInterface> = networkInfo.findInterfaces();
if( interfaces != null )
{
trace( "Interface count: " + interfaces.length );
for each ( var interfaceObj:NetworkInterface in interfaces )
{
trace( "\nname: " + interfaceObj.name );
trace( "display name: " + interfaceObj.displayName );
trace( "mtu: " + interfaceObj.mtu );
trace( "active?: " + interfaceObj.active );
trace( "parent interface: " + interfaceObj.parent );
trace( "hardware address: " + interfaceObj.hardwareAddress );
if( interfaceObj.subInterfaces != null )
{
trace( "# subinterfaces: " + interfaceObj.subInterfaces.length );
}
trace("# addresses: " + interfaceObj.addresses.length );
for each ( var address:InterfaceAddress in interfaceObj.addresses )
{
trace( " type: "
+ address.ipVersion );
trace( " address: " + address.address );
trace( " broadcast: " + address.broadcast );
trace( " prefix length: " + address.prefixLength );
}
}
}
}
}
}

. :

NetworkInfo
NetworkInterface
InterfaceAddress
Flexpert: Flex 4.5

23.11.2012.

850

ACTIONSCRIPT 3.0


Adobe AIR 1.0
AIR
. -, Adobe AIR
,
. NetworkInfo, NativeApplication,
networkChange. , :
NetworkInfo.networkInfo.addEventListener(Event.NETWORK_CHANGE, onNetworkChange);

:
function onNetworkChange(event:Event)
{
//Check resource availability
}

networkChange , ,
. AIR .
, , ,
. ,
.
(, VPN).
,
.
.
. , .
. -
, -
. .


Adobe AIR 1.0
, AIR, aircore.swc.
, aircore.swc .
Adobe Flash Builder .
ServiceMonitor
. ServiceMonitor
, . ServiceMonitor
, . ,
pollInterval ServiceMonitor
, . ServiceMonitor
, start().
URLMonitor, ServiceMonitor, HTTP URLRequest.

23.11.2012.

851

ACTIONSCRIPT 3.0

SocketMonitor, ServiceMonitor,
.
. AIR 2
servicemonitor.swc. .
aircore.swc.
Flash CS4 CS5 Professional
Adobe Flash CS4 CS5 Professional.
1 .
2 ActionScript 3.0. .
3 SWC AIK Flash Professional.
4 /frameworks/libs/air/aircore.swc ( AIR 2)

/frameworks/libs/air/servicemonitor.swc ( AIR 1.5).


5 .
6 ActionScript 3.0.
import air.net.*;

Flash CS3 Professional


Adobe Flash CS3 Professional ServiceMonitorShim
. import ActionScript 3.0.
import air.net.*;

HTTP
Adobe AIR 1.0
URLMonitor , HTTP- 80
( HTTP-). URLMonitor
Adobe:
import air.net.URLMonitor;
import flash.net.URLRequest;
import flash.events.StatusEvent;
var monitor:URLMonitor;
monitor = new URLMonitor(new URLRequest('http://www.example.com'));
monitor.addEventListener(StatusEvent.STATUS, announceStatus);
monitor.start();
function announceStatus(e:StatusEvent):void {
trace("Status change. Current status: " + monitor.available);
}

23.11.2012.

852

853

ACTIONSCRIPT 3.0


Adobe AIR 1.0
AIR .

. ,
.
SocketMonitor .
6667, IRC.
import air.net.ServiceMonitor;
import flash.events.StatusEvent;
socketMonitor = new SocketMonitor('www.example.com',6667);
socketMonitor.addEventListener(StatusEvent.STATUS, socketStatusChange);
socketMonitor.start();
function announceStatus(e:StatusEvent):void {
trace("Status change. Current status: " + socketMonitor.available);
}

- , SocketMonitor
SecureSocketMonitor.

(DNS)
Adobe AIR 2.0
DNS DNSResolver. DNS
, IP- IP-.
DNS:

ARecord IPv4- ;
AAAARecord IPv6- ;
MXRecord ;
PTRRecord IP-.
SRVRecord ..
, lookup() DNSResolver
, . .

ARecord

"example.com"

AAAARecord

"example.com"

MXRecord

"example.com"

PTRRecord

IP-

208.77.188.166

SRVRecord

: _service._protocol.host

"_sip._tcp.example.com"

23.11.2012.

ACTIONSCRIPT 3.0

IP- example.com.
package
{
import
import
import
import
import

flash.display.Sprite;
flash.events.DNSResolverEvent;
flash.events.ErrorEvent;
flash.net.dns.ARecord;
flash.net.dns.DNSResolver;

public class DNSResolverExample extends Sprite


{
public function DNSResolverExample()
{
var resolver:DNSResolver = new DNSResolver();
resolver.addEventListener( DNSResolverEvent.LOOKUP, lookupComplete );
resolver.addEventListener( ErrorEvent.ERROR, lookupError );
resolver.lookup( "example.com.", ARecord );
}
private function lookupComplete( event:DNSResolverEvent ):void
{
trace( "Query string: " + event.host );
trace( "Record count: " + event.resourceRecords.length );
for each( var record:* in event.resourceRecords )
{
if( record is ARecord ) trace( record.address );
}
}
private function lookupError( error:ErrorEvent ):void
{
trace("Error: " + error.text );
}
}
}

. :

DNSResolver
DNSResolverEvent
ARecord
AAAARecord
MXRecord
PTRRecord
SRVRecord

23.11.2012.

854

855

43.
Flash Player 9 , Adobe AIR 1.0
, .
, , IP-.
IP-
.
Adobe Flash Player TCP (Transport Control Protocol,
). Flash Player ,
-, .
, Flash Player TCP, .
API- Flash Player XMLSocket. XMLSocket Flash
Player, XML ,
. XMLSocket ActionScript 1
. Socket,
, Flash XMLSocket, .
Adobe AIR .
AIR - TCP ServerSocket
, SSL TLS, SecureSocket.
AIR UDP (Universal Datagram
Protocol, ) DatagramSocket.


flash.net
1151

TCP-
Flash Player 9 , Adobe AIR 1.0
Transmission Control Protocol (TCP)
. TCP
, (
). TCP . Flash Player
. Adobe AIR .
TCP API- ActionScript.

Socket . Socket
.

SecureSocket (AIR)
.

23.11.2012.

ACTIONSCRIPT 3.0

ServerSocket (AIR)
.

XMLSocket XMLSocket.


Flash Player 9 , Adobe AIR 1.0
XML-,
XML-.
. ,
(POP3, SMTP IMAP) (NNTP).

Socket
Flash Player 9 , Adobe AIR 1.0
Socket ,
. Socket ,
. , ,
-, POP3, SMTP, IMAP NNTP.
, ,
.
Flash Player ,
. ,
. ,
. ,
Intel x86. ,
, . , IDataInput
IDataOutput, , (ByteArray, Socket URLStream),
, .
Java
. ,
endian Endian.BIG_ENDIAN Endian.LITTLE_ENDIAN.
Socket , IDataInput IDataOutput (
flash.utils). Socket.
. :

Socket
IDataInput
IDataOutput
socketData

23.11.2012.

856

ACTIONSCRIPT 3.0

(AIR)
Adobe AIR 2
SecureSocket , SSL4
TLS1. : ,
.

.
SSL TLS,
.
SecureSocket
. Windows Mac
. Linux
.
,
ioError. , ,
serverCertificateStatus SecureSocket. ,
, .
CertificateStatus ,
.

Expired (): .
Invalid (): ,
. , , .

Invalid chain ( ):
.

Principal mismatch ( ):
. , .

Revoked (): .
Trusted (): . SecureSocket
, .

Unknown (): SecureSocket .


serverCertificateStatus connect()
connect ioError.

Untrusted signers ( ):
.
SecureSocket ,
. SecureSocket
, Socket.
SecureSocket . isSupported
SecureSocket, , SecureSocket
.
. :

SecureSocket

23.11.2012.

857

ACTIONSCRIPT 3.0

CertificateStatus
IDataInput
IDataOutput
socketData

TCP: Telnet
Flash Player 9 , Adobe AIR 1.0
Telnet
Socket. :

Telnet Socket;
ByteArray;
, .

www.adobe.com/go/learn_programmingAS3samples_flash_ru. Telnet
Samples/Telnet. .
File

TelnetSocket.fla

,
Flex (MXML) Flash (FLA).

TelnetSocket.mxml
TelnetSocket.as

, ( Flash).

com/example/programmingas3/Telnet/Telnet.as

Telnet ,
, ,
.

Telnet
Flash Player 9 , Adobe AIR 1.0
TelnetSocket.mxml .
, , login() sendCommand(),
.
ActionScript, .

23.11.2012.

858

ACTIONSCRIPT 3.0

import com.example.programmingas3.socket.Telnet;
private var telnetClient:Telnet;
private function connect():void
{
telnetClient = new Telnet(serverName.text, int(portNumber.text), output);
console.title = "Connecting to " + serverName.text + ":" + portNumber.text;
console.enabled = true;
}
private function sendCommand():void
{
var ba:ByteArray = new ByteArray();
ba.writeMultiByte(command.text + "\n", "UTF-8");
telnetClient.writeBytesToSocket(ba);
command.text = "";
}

Telnet com.example.programmingas.socket.
Telnet, telnetClient,
connect(). connect(),
telnetClient, . Telnet,
TextArea ,
-. connect() title
Panel Panel, .
, sendCommand(),
ByteArray.
Telnet
Flash Player 9 , Adobe AIR 1.0
Telnet Telnet, .
Telnet .
private
private
private
private
private

var
var
var
var
var

serverURL:String;
portNumber:int;
socket:Socket;
ta:TextArea;
state:int = 0;

, serverURL, ,
.
, portNumber , Telnet.
Telnet 23.
, socket Socket, ,
serverURL portNumber.
, ta TextArea, .
Telnet .
, state , ,
Telnet.
, Telnet connect()
.

23.11.2012.

859

ACTIONSCRIPT 3.0

Telnet : server, port output. server port


Telnet. , output
TextArea, , .
public function Telnet(server:String, port:int, output:TextArea)
{
serverURL = server;
portNumber = port;
ta = output;
socket = new Socket();
socket.addEventListener(Event.CONNECT, connectHandler);
socket.addEventListener(Event.CLOSE, closeHandler);
socket.addEventListener(ErrorEvent.ERROR, errorHandler);
socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
socket.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler);
Security.loadPolicyFile("http://" + serverURL + "/crossdomain.xml");
try
{
msg("Trying to connect to " + serverURL + ":" + portNumber + "\n");
socket.connect(serverURL, portNumber);
}
catch (error:Error)
{
msg(error.message + "\n");
socket.close();
}
}


Flash Player 9 , Adobe AIR 1.0
, Socket.
writeBoolean(), writeByte(), writeBytes(), writeDouble() .
flush(). Telnet
writeBytes(),
. writeBytesToSocket()
:
public function writeBytesToSocket(ba:ByteArray):void
{
socket.writeBytes(ba);
socket.flush();
}

sendCommand() .
-
Flash Player 9 , Adobe AIR 1.0
- msg().
TextArea setScroll(),
TextArea . msg() :

23.11.2012.

860

ACTIONSCRIPT 3.0

private function msg(value:String):void


{
ta.text += value;
setScroll();
}

TextArea,
, .
TextArea
Flash Player 9 , Adobe AIR 1.0
setScroll() ActionScript,
TextArea , .
setScroll():
public function setScroll():void
{
ta.verticalScrollPosition = ta.maxVerticalScrollPosition;
}

verticalScrollPosition,
, ,
maxVerticalScrollPosition.

XML-
Flash Player 9 , Adobe AIR 1.0
XML ,
. , XML,
. XML- ,
.
.
Flash Player Adobe AIR
XML- .
. - ( ) 1131
1151.
XMLSocket ,
Real-Time Messaging Protocol (RTMP) XMLSocket HTTP-.
HTTP-, Flash Remoting Flash Media
Server ( RTMP).

23.11.2012.

861

ACTIONSCRIPT 3.0

, , Flash Player
AIR, XMLSocket ,
.


XMLSocket.connect() TCP-,
1024. ,
, XMLSocket,
, 1024 . 1024 ,
FTP (21), Telnet (23), SMTP (25), HTTP (80) POP3 (110), XMLSocket
.
.


XMLSocket.connect() ,
, . ( ,
URLLoader.load().) ,
, , ,
.
. AIR 1159.

. XMLSocket
. ,
URLLoader XMLSocket.
XMLSocket.connect() XMLSocket.send() XMLSocket
XML , .
XMLSocket.connect() - . XMLSocket.send()
XML , .
XMLSocket.connect() TCP/IP
.

XMLSocket.close() XMLSocket.
XMLSocket.
Flash Player.
(, ).

XMLSocket
Flash Player 9 , Adobe AIR 1.0
,
Flash Player AIR.
AIR
, Java, Python Perl. XMLSocket
(daemon), ,
XMLSocket.

XML TCP/IP
.

XML XML, (0)


.

23.11.2012.

862

ACTIONSCRIPT 3.0

XMLSocket XML.
- Java XML
Flash Player 9 , Adobe AIR 1.0
XMLSocket, Java,
.
8080 ,
.
.
import java.io.*;
import java.net.*;
class SimpleServer
{
private static SimpleServer server;
ServerSocket socket;
Socket incoming;
BufferedReader readerIn;
PrintStream printOut;
public static void main(String[] args)
{
int port = 8080;
try
{
port = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
// Catch exception and keep going.
}
server = new SimpleServer(port);
}
private SimpleServer(int port)
{
System.out.println(">> Starting SimpleServer");
try
{
socket = new ServerSocket(port);
incoming = socket.accept();
readerIn = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
printOut = new PrintStream(incoming.getOutputStream());
printOut.println("Enter EXIT to exit.\r");
out("Enter EXIT to exit.\r");
boolean done = false;
while (!done)
{
String str = readerIn.readLine();
if (str == null)
{

23.11.2012.

863

ACTIONSCRIPT 3.0

done = true;
}
else
{
out("Echo: " + str + "\r");
if(str.trim().equals("EXIT"))
{
done = true;
}
}
incoming.close();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
private void out(String str)
{
printOut.println(str);
System.out.println(str);
}
}

SimpleServer.java
Java. Java SimpleServer.class.
XMLSocket , java SimpleServer.
SimpleServer.class ;
-.
- , Java,
java -classpath . SimpleServer.
XMLSocket ,
XMLSocket XMLSocket.connect(), , .
var xmlsock:XMLSocket = new XMLSocket();
xmlsock.connect("127.0.0.1", 8080);

data (flash.events.DataEvent.DATA).
xmlsock.addEventListener(DataEvent.DATA, onData);
private function onData(event:DataEvent):void
{
trace("[" + event.type + "] " + event.data);
}

XMLSocket, XMLSocket.send()
XML . Flash Player String
XMLSocket, (0).
xmlsock.send(xmlFormattedData);

XMLSocket.send() , , .
, IOError.

23.11.2012.

864

ACTIONSCRIPT 3.0

, - XML, (\n).
. XMLSocket.


Adobe AIR 2
ServerSocket,
TCP.
. ServerSocket , connect.
ServerSocketConnectEvent, , Socket.
Socket .
, .
1 ServerSocket .
2 connect.
3 listen().
4 connect, Socket .

ServerSocket , close().
.
8087. (
Connected. (.)) .
.
package
{
import
import
import
import
import
import
import

flash.display.Sprite;
flash.events.Event;
flash.events.IOErrorEvent;
flash.events.ProgressEvent;
flash.events.ServerSocketConnectEvent;
flash.net.ServerSocket;
flash.net.Socket;

public class ServerSocketExample extends Sprite


{
private var serverSocket:ServerSocket;
private var clientSockets:Array = new Array();
public function ServerSocketExample()
{
try
{
// Create the server socket
serverSocket = new ServerSocket();
// Add the event listener
serverSocket.addEventListener( Event.CONNECT, connectHandler );
serverSocket.addEventListener( Event.CLOSE, onClose );

23.11.2012.

865

ACTIONSCRIPT 3.0

// Bind to local port 8087


serverSocket.bind( 8087, "127.0.0.1" );
// Listen for connections
serverSocket.listen();
trace( "Listening on " + serverSocket.localPort );
}
catch(e:SecurityError)
{
trace(e);
}
}
public function connectHandler(event:ServerSocketConnectEvent):void
{
//The socket is provided by the event object
var socket:Socket = event.socket as Socket;
clientSockets.push( socket );
socket.addEventListener( ProgressEvent.SOCKET_DATA, socketDataHandler);
socket.addEventListener( Event.CLOSE, onClientClose );
socket.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
//Send a connect message
socket.writeUTFBytes("Connected.");
socket.flush();
trace( "Sending connect message" );
}
public function socketDataHandler(event:ProgressEvent):void
{
var socket:Socket = event.target as Socket
//Read the message from the socket
var message:String = socket.readUTFBytes( socket.bytesAvailable );
trace( "Received: " + message);
// Echo the received message back to the sender
message = "Echo -- " + message;
socket.writeUTFBytes( message );

23.11.2012.

866

ACTIONSCRIPT 3.0

socket.flush();
trace( "Sending: " + message );
}
private function onClientClose( event:Event ):void
{
trace( "Connection to client closed." );
//Should also remove from clientSockets array...
}
private function onIOError( errorEvent:IOErrorEvent ):void
{
trace( "IOError: " + errorEvent.text );
}
private function onClose( event:Event ):void
{
trace( "Server socket closed by OS." );
}
}}

. :

ServerSocket
ServerSocketConnectEvent
Socket

UDP- (AIR)
Adobe AIR 2
Universal Datagram Protocol (UDP)
, . UDP ,
. UDP
,
. UDP , TCP.
UDP , ,
.
,
.
TCP.
AIR UDP DatagramSocket
DatagramSocketDataEvent. UDP, .
1 DatagramSocket.
2 data.
3 IP- bind().
4 , send() IP- .

23.11.2012.

867

ACTIONSCRIPT 3.0

5 , data. DatagramSocketDataEvent,

, ByteArray .
, UDP.
, Hello ().
.
package
{
import flash.display.Sprite;
import flash.events.DatagramSocketDataEvent;
import flash.events.Event;
import flash.net.DatagramSocket;
import flash.utils.ByteArray;
public class DatagramSocketExample extends Sprite
{
private var datagramSocket:DatagramSocket;
//The IP and port for this computer
private var localIP:String = "192.168.0.1";
private var localPort:int = 55555;
//The IP and port for the target computer
private var targetIP:String = "192.168.0.2";
private var targetPort:int = 55555;
public function DatagramSocketExample()
{
//Create the socket
datagramSocket = new DatagramSocket();
datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived );
//Bind the socket to the local network interface and port
datagramSocket.bind( localPort, localIP );
//Listen for incoming datagrams
datagramSocket.receive();
//Create a message in a ByteArray
var data:ByteArray = new ByteArray();
data.writeUTFBytes("Hello.");
//Send the datagram message
datagramSocket.send( data, 0, 0, targetIP, targetPort);
}
private function dataReceived( event:DatagramSocketDataEvent ):void
{
//Read the data from the datagram
trace("Received from " + event.srcAddress + ":" + event.srcPort + "> " +
event.data.readUTFBytes( event.data.bytesAvailable ) );
}
}}

23.11.2012.

868

ACTIONSCRIPT 3.0

UDP .

(MTU),
.
ByteArray, send(), . (
TCP .)

.
,
.

connect(), , , .
UDP . ,
.

UDP .
. ( TCP
.)
. :

DatagramSocket
DatagramSocketDataEvent
ByteArray

IPv6
Flash Player 9 , Adobe AIR 1.0
Flash Player 9.0.115.0 IPv6 (-
6). IPv6 Internet Protocol (-), 128-
( IPv4, 32- ).
IPv6 . .
, .
IPv6, IPv6 URL-,
([]), :
[2001:db8:ccc3:ffff:0:444d:555e:666f]

Flash Player IPv6 .

Flash Player IPv6.


IP- .
.
IPv6 ([]).
0-4 , .
( ),
, .

23.11.2012.

869

ACTIONSCRIPT 3.0

IPv6, Flash Player, .

IPv6 ( ) [::].
IPv6 [::1].
IPv4 ( IPv6) [::ffff:a.b.c.d], a.b.c.d
IPv4 ( ).

, IPv4, [::a.b.c.d], a.b.c.d IPv4


( ).

23.11.2012.

870

871

44. HTTP
Flash Player 9 , Adobe AIR 1.0
Adobe AIR Adobe Flash Player HTTP ,
, , .


flash.net.URLLoader
flash.net.URLStream
flash.net.URLRequest
flash.net.URLRequestDefaults
flash.net.URLRequestHeader
flash.net.URLRequestMethod
flash.net.URLVariables


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 .
, , ,
-. ,
.
.

URLRequest
Flash Player 9 , Adobe AIR 1.0
API-, , URLRequest
.

URLRequest
Flash Player 9 , Adobe AIR 1.0
URLRequest:

23.11.2012.

ACTIONSCRIPT 3.0
HTTP

contentType

MIME- , URL. contentType ,


application/x-www-form-urlencoded.

data

, , URL.

digest

, Adobe,
( ) - Adobe Flash Player.

method

HTTP, GET POST. (,


AIR, , "GET" "POST", method.
HTTP, "GET". .
AIR 1159.)

requestHeaders

HTTP, HTTP. ,
Flash Player,
AIR, .

url

URL-.

AIR URLRequest,
AIR, .
URL-
URL- ( , file http).

followRedirects

, (true, )
(false). AIR.

manageCookies

, HTTP cookie (true,


) (false).
AIR.

authenticate

, (true) .
AIR.

, .
URLRequestDefaults (.
URLRequest ( AIR) 873).

cacheResponse

, .
AIR.
(true).

useCache

, URLRequest.
AIR.
( true) , .

userAgent

, HTTP.

. HTMLLoader , ,
HTMLLoader. . HTMLLoader
1053.

23.11.2012.

872

ACTIONSCRIPT 3.0
HTTP

URLRequest ( AIR)
Adobe AIR 1.0
URLRequestDefaults URLRequest.
, manageCookies useCache.
URLRequest
:
URLRequestDefaults.manageCookies = false;
URLRequestDefaults.useCache = false;

. URLRequestDefaults , Adobe
AIR. Flash Player.
URLRequestDefaults setLoginCredentialsForHost(),
, . ,
hostname , , "www.example.com",
, "www.example.com:80". , "example.com", "www.example.com"
"sales.example.com" .
.
(, ),
setLoginCredentialsForHost() .
,
- www.example.com:
URLRequestDefaults.setLoginCredentialsForHost("www.example.com", "Ada", "love1816$X");

URLRequestDefaults ,
. , setLoginCredentialsForHost(),
, AIR.
URLRequestDefaults . c ActionScript 3.0
Adobe Flash Platform.

URI
Flash Player 9 , Adobe AIR 1.0
URI, , ,
:
http: https:
URL- ( , -).
file:
file: URL- , .
:
file:///c:/AIR Test/test.txt

AIR URL- ,
:

23.11.2012.

873

ACTIONSCRIPT 3.0
HTTP

app:
app:, .
, ,
.
app:/resources

AIR AIR Debug Launcher (ADL),


, .
URL- ( url) File, File.applicationDirectory,
URI app, :
var dir:File = File.applicationDirectory;
dir = dir.resolvePath("assets");
trace(dir.url); // app:/assets

app-storage:
app-storage:,
. ( ) AIR
, , .
, prefs.xml
:
app-storage:/settings/prefs.xml

URL- ( url) File, File.applicationStorageDirectory,


URI app-storage, :
var prefsFile:File = File.applicationStorageDirectory;
prefsFile = prefsFile.resolvePath("prefs.xml");
trace(dir.prefsFile); // app-storage:/prefs.xml

mailto:
mailto URLRequest,
navigateToURL(). . URL- 888.
URLRequest, URI, URL
, FileStream Sound.
HTML, AIR, src img.
URI AIR (app: app-storage:)
. .
AIR 1159.

URL-
URL- , URLVariables
.
URLVariables:

URLVariables
URLVariables.decode()
URLVariables

23.11.2012.

874

ACTIONSCRIPT 3.0
HTTP

, URLRequest:
var urlVar:URLVariables = new URLVariables( "one=1&two=2" );
urlVar.decode("amp=" + encodeURIComponent( "&" ) );
urlVar.three = 3;
urlVar.amp2 = "&&";
trace(urlVar.toString()); //amp=%26&amp2=%26%26&one=1&two=2&three=3
var urlRequest:URLRequest = new URLRequest( "http://www.example.com/test.cfm" );
urlRequest.data = urlVar;

URLVariables URLVariables.decode() ,
URL- , URI. ,
,
& %26, .
encodeURIComponent() .

URLLoader
Flash Player 9 , Adobe AIR 1.0
URLLoader .
URLLoader
, (,
Flash Player AIR).
URLLoader URL- ,
URL. URLLoader , complete, httpStatus, ioError, open,
progress securityError.
ActionScript 3.0 ActionScript 2.0,
LoadVars.onData, LoadVars.onHTTPStatus LoadVars.onLoad.
ActionScript 3.0 .
134
.
( )
progress. , , progress
. complete.
dataFormat URLLoader ,
URLVariables.
URLLoader.load() ( URLLoader) , request,
URLRequest. URLRequest HTTP, URL-, (GET POST),
MIME.
, XML :

23.11.2012.

875

ACTIONSCRIPT 3.0
HTTP

var secondsUTC:Number = new Date().time;


var dataXML:XML =
<clock>
<time>{secondsUTC}</time>
</clock>;
var request:URLRequest = new URLRequest("http://www.yourdomain.com/time.cfm");
request.contentType = "text/xml";
request.data = dataXML.toXMLString();
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(request);

XML dataXML, XML


. contentType URLRequest text/xml,
XML data URLRequest. ,
URLLoader load().

URLStream
Flash Player 9 , Adobe AIR 1.0
URLStream . URLStream
.
.
URLStream bytesAvailable
. EOFError ,
.
httpResponseStatus (AIR)
Adobe AIR URLStream httpResponseStatus
httpStatus. httpResponseStatus - .
httpResponseStatus ( HTTPStatusEvent) responseURL,
URL-, , responseHeaders,
URLRequestHeader, .


Flash Player 9 , Adobe AIR 1.0

.
. , ,
, ,
. ,
.
URLRequest URLLoader,
params.txt:

23.11.2012.

876

ACTIONSCRIPT 3.0
HTTP

var request:URLRequest = new URLRequest("params.txt");


var loader:URLLoader = new URLLoader();
loader.load(request);

, Flash Player Adobe AIR


HTTP GET. POST, request.method
POST URLRequestMethod.POST,
:
var request:URLRequest = new URLRequest("sendfeedback.cfm");
request.method = URLRequestMethod.POST;

, params.txt, , :
monthNames=January,February,March,April,May,June,July,August,September,October,November,Dece
mber&dayNames=Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

: monthNames dayNames. ,
, .
String.split().

, .
complete,
data URLLoader, :
function completeHandler(event)
{
var loader2 = event.target;
air.trace(loader2.data);
}

-,
URLVariables, , :
private function completeHandler(event:Event):void
{
var loader2:URLLoader = URLLoader(event.target);
var variables:URLVariables = new URLVariables(loader2.data);
trace(variables.dayNames);
}

- URLVariables.
. ,
String.split(), :
var dayNameArray:Array = variables.dayNames.split(",");

,
, int(), uint() Number().
,
URLVariables, URLLoader.dataFormat
URLLoaderDataFormat. URLLoader.dataFormat .

URLLoaderDataFormat.BINARY URLLoader.data ,
ByteArray;

23.11.2012.

877

ACTIONSCRIPT 3.0
HTTP

URLLoaderDataFormat.TEXT URLLoader.data String;

URLLoaderDataFormat.VARIABLES URLLoader.data

URL, URLVariables.
, URLLoader.dataFormat
URLLoaderDataFormat.VARIABLES
URLVariables.
package
{
import
import
import
import
import

flash.display.Sprite;
flash.events.*;
flash.net.URLLoader;
flash.net.URLLoaderDataFormat;
flash.net.URLRequest;

public class URLLoaderDataFormatExample extends Sprite


{
public function URLLoaderDataFormatExample()
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/params.txt");
var variables:URLLoader = new URLLoader();
variables.dataFormat = URLLoaderDataFormat.VARIABLES;
variables.addEventListener(Event.COMPLETE, completeHandler);
try
{
variables.load(request);
}
catch (error:Error)
{
trace("Unable to load URL: " + error);
}
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
trace(loader.data.dayNames);
}
}
}

. URLLoader.dataFormat URLLoaderDataFormat.TEXT.
, XML URLVariables.
URLRequest URLLoader
XML. , Event.COMPLETE,
XML, XML.

23.11.2012.

878

ACTIONSCRIPT 3.0
HTTP

package
{
import
import
import
import
import

flash.display.Sprite;
flash.errors.*;
flash.events.*;
flash.net.URLLoader;
flash.net.URLRequest;

public class ExternalDocs extends Sprite


{
public function ExternalDocs()
{
var request:URLRequest = new URLRequest("http://www.[yourdomain].com/data.xml");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred.");
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
}
private function completeHandler(event:Event):void
{
var dataXML:XML = XML(event.target.data);
trace(dataXML.toXMLString());
}
}
}


Flash Player 9 , Adobe AIR 1.0
URLVariables ,
, , . ,
, - ,
, ,
, .
,
.
URLVariables variables,
name. URLRequest, URL- ,
. method URLRequest
HTTP POST. URLVariables URL, data
URLRequest URLVariables. ,
URLLoader URLLoader.load(), .

23.11.2012.

879

ACTIONSCRIPT 3.0
HTTP

var variables:URLVariables = new URLVariables("name=Franklin");


var request:URLRequest = new URLRequest();
request.url = "http://www.[yourdomain].com/greeting.cfm";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load URL");
}
function completeHandler(event:Event):void
{
trace(event.target.data.welcomeMessage);
}

Adobe ColdFusion greeting.cfm,


.
<cfif NOT IsDefined("Form.name") OR Len(Trim(Form.Name)) EQ 0>
<cfset Form.Name = "Stranger" />
</cfif>
<cfoutput>welcomeMessage=#UrlEncodedFormat("Welcome, " & Form.name)#
</cfoutput>

-
Flash Player 9 , Adobe AIR 1.0
HTTP -. :

REST
XML-RPC
SOAP
- ActionScript 3, URLRequest, URL- XML
URLLoader. Flex , SOAP. Flash Professional CS3,
Flex , Flash Professional,
, Flash Builder.
HTML AIR URLRequest URLLoader
Javascript XMLHttpRequest. SWF,
Flex Javascript.

23.11.2012.

880

ACTIONSCRIPT 3.0
HTTP

, -,
-, SWF-, , -,
, .
, , ,
. Adobe Blaze DS Adobe LiveCycle
-.
AIR , -
. AIR
, ,
. HTML AIR
XMLHttpRequests .

XMLHttpRequests, iframe.


- ( ) 1131
Adobe BlazeDS
Adobe LiveCycle ES2
REST
XML-RPC
SOAP

- REST
Flash Player 9 , Adobe AIR 1.0
- REST HTTP URL
. ,
GET URL .
URL :
http://service.example.com/?method=getItem&id=d3452

- REST ActionScript URLRequest,


URLVariables URLLoader. Javascript AIR
XMLHttpRequest.
- REST ActionScript :
1 URLRequest.
2 URL HTTP .
3 URLVariables.
4 .
5 .
6 URLLoader.

23.11.2012.

881

ACTIONSCRIPT 3.0
HTTP

7 complete, URLLoader

. ,
URLLoader.
, -, ,
. ActionScript
:
import
import
import
import
import
import
import
import

flash.events.Event;
flash.events.ErrorEvent;
flash.events.IOErrorEvent;
flash.events.SecurityErrorEvent;
flash.net.URLLoader;
flash.net.URLRequest;
flash.net.URLRequestMethod;
flash.net.URLVariables;

private var requestor:URLLoader = new URLLoader();


public function restServiceCall():void
{
//Create the HTTP request object
var request:URLRequest = new URLRequest( "http://service.example.com/" );
request.method = URLRequestMethod.GET;
//Add the URL variables
var variables:URLVariables = new URLVariables();
variables.method = "test.echo";
variables.api_key = "123456ABC";
variables.message = "Able was I, ere I saw Elba.";
request.data = variables;
//Initiate the transaction
requestor = new URLLoader();
requestor.addEventListener( Event.COMPLETE, httpRequestComplete );
requestor.addEventListener( IOErrorEvent.IOERROR, httpRequestError );
requestor.addEventListener( SecurityErrorEvent.SECURITY_ERROR, httpRequestError );
requestor.load( request );
}
private function httpRequestComplete( event:Event ):void
{
trace( event.target.data );
}
private function httpRequestError( error:ErrorEvent ):void{
trace( "An error occured: " + error.message );
}

Javascript AIR XMLHttpRequest:

23.11.2012.

882

ACTIONSCRIPT 3.0
HTTP

<html>
<head><title>RESTful web service request</title>
<script type="text/javascript">
function makeRequest()
{
var requestDisplay = document.getElementById( "request" );
var resultDisplay = document.getElementById( "result" );
//Create a conveninece object to hold the call properties
var request = {};
request.URL = "http://service.example.com/";
request.method = "test.echo";
request.HTTPmethod = "GET";
request.parameters = {};
request.parameters.api_key = "ABCDEF123";
request.parameters.message = "Able was I ere I saw Elba.";
var requestURL = makeURL( request );
xmlhttp = new XMLHttpRequest();
xmlhttp.open( request.HTTPmethod, requestURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
resultDisplay.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
requestDisplay.innerHTML = requestURL;
}
//Convert the request object into a properly formatted URL
function makeURL( request )
{
var url = request.URL + "?method=" + escape( request.method );
for( var property in request.parameters )
{
url += "&" + property + "=" + escape( request.parameters[property] );
}
return url;
}
</script>
</head>
<body onload="makeRequest()">
<h1>Request:</h1>
<div id="request"></div>
<h1>Result:</h1>
<div id="result"></div>
</body>
</html>

23.11.2012.

883

ACTIONSCRIPT 3.0
HTTP

- XML-RPC
Flash Player 9 , Adobe AIR 1.0
XML-RPC XML, URL.
XML-RPC
XML - HTTP- POST. ,
Content-Type , XML.
-, REST,
XML-RPC:
import flash.events.Event;
import flash.events.ErrorEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
public function xmlRPCRequest():void
{
//Create the XML-RPC document
var xmlRPC:XML = <methodCall>
<methodName></methodName>
<params>
<param>
<value>
<struct/>
</value>
</param>
</params>
</methodCall>;
xmlRPC.methodName = "test.echo";
//Add the method parameters
var parameters:Object = new Object();
parameters.api_key = "123456ABC";
parameters.message = "Able was I, ere I saw Elba.";
for( var propertyName:String in parameters )
{
xmlRPC..struct.member[xmlRPC..struct.member.length + 1] =
<member>
<name>{propertyName}</name>
<value>
<string>{parameters[propertyName]}</string>
</value>
</member>;
}
//Create the HTTP request object
var request:URLRequest = new URLRequest( "http://service.example.com/xml-rpc/" );
request.method = URLRequestMethod.POST;
request.cacheResponse = false;
request.requestHeaders.push(new URLRequestHeader("Content-Type", "application/xml"));

23.11.2012.

884

ACTIONSCRIPT 3.0
HTTP

request.data = xmlRPC;
//Initiate the request
requestor = new URLLoader();
requestor.dataFormat = URLLoaderDataFormat.TEXT;
requestor.addEventListener( Event.COMPLETE, xmlRPCRequestComplete );
requestor.addEventListener( IOErrorEvent.IO_ERROR, xmlRPCRequestError );
requestor.addEventListener( SecurityErrorEvent.SECURITY_ERROR, xmlRPCRequestError );
requestor.load( request );
}
private function xmlRPCRequestComplete( event:Event ):void
{
trace( XML(event.target.data).toXMLString() );
}
private function xmlRPCRequestError( error:ErrorEvent ):void
{
trace( "An error occurred: " + error );
}

WebKit AIR E4X, ,


XML , Javascript.
DOM XML Javascript
DOMParser XML.
DOM XML-RPC
XMLHttpRequest -:
<html>
<head>
<title>XML-RPC web service request</title>
<script type="text/javascript">
function makeRequest()
{
var requestDisplay = document.getElementById( "request" );
var resultDisplay = document.getElementById( "result" );
var request = {};
request.URL = "http://services.example.com/xmlrpc/";
request.method = "test.echo";
request.HTTPmethod = "POST";
request.parameters = {};
request.parameters.api_key = "123456ABC";
request.parameters.message = "Able was I ere I saw Elba.";
var requestMessage = formatXMLRPC( request );
xmlhttp = new XMLHttpRequest();
xmlhttp.open( request.HTTPmethod, request.URL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
resultDisplay.innerText = xmlhttp.responseText;
}
}
xmlhttp.send( requestMessage );

23.11.2012.

885

ACTIONSCRIPT 3.0
HTTP

requestDisplay.innerText = xmlToString( requestMessage.documentElement );


}
//Formats a request as XML-RPC document
function formatXMLRPC( request )
{
var xmldoc = document.implementation.createDocument( "", "", null );
var root = xmldoc.createElement( "methodCall" );
xmldoc.appendChild( root );
var methodName = xmldoc.createElement( "methodName" );
var methodString = xmldoc.createTextNode( request.method );
methodName.appendChild( methodString );
root.appendChild( methodName );
var params = xmldoc.createElement( "params" );
root.appendChild( params );
var param = xmldoc.createElement( "param" );
params.appendChild( param );
var value = xmldoc.createElement( "value" );
param.appendChild( value );
var struct = xmldoc.createElement( "struct" );
value.appendChild( struct );
for( var property in request.parameters )
{
var member = xmldoc.createElement( "member" );
struct.appendChild( member );
var name = xmldoc.createElement( "name" );
var paramName = xmldoc.createTextNode( property );
name.appendChild( paramName )
member.appendChild( name );
var value = xmldoc.createElement( "value" );
var type = xmldoc.createElement( "string" );
value.appendChild( type );
var paramValue = xmldoc.createTextNode( request.parameters[property] );
type.appendChild( paramValue )
member.appendChild( value );
}
return xmldoc;
}
//Returns a string representation of an XML node
function xmlToString( rootNode, indent )
{
if( indent == null ) indent = "";
var result = indent + "<" + rootNode.tagName + ">\n";
for( var i = 0; i < rootNode.childNodes.length; i++)
{
if(rootNode.childNodes.item( i ).nodeType == Node.TEXT_NODE )
{
result += indent + "
" + rootNode.childNodes.item( i ).textContent + "\n";
}
}

23.11.2012.

886

887

ACTIONSCRIPT 3.0
HTTP

if( rootNode.childElementCount > 0 )


{
result += xmlToString( rootNode.firstElementChild, indent + "
}
if( rootNode.nextElementSibling )
{
result += indent + "</" + rootNode.tagName + ">\n";
result += xmlToString( rootNode.nextElementSibling, indent );
}
else
{
result += indent +"</" + rootNode.tagName + ">\n";
}
return result;

" );

}
</script>
</head>
<body onload="makeRequest()">
<h1>Request:</h1>
<pre id="request"></pre>
<h1>Result:</h1>
<pre id="result"></pre>
</body>
</html>

- SOAP
Flash Player 9 , Adobe AIR 1.0
SOAP - XML-RPC ,
, . - SOAP
WSDL (Web Service Description Language), -,
URL- . ActionScript 3 SOAP,
SOAP XML ,
. - SOAP, , ,
SOAP.
Flex - SOAP. Flash Builder (
rpc.swc) Flex, Flex.
Flash Professional Flex framework.swc rpc.swc ,
Flex ActionScript.


- Flex Flash Professional
(Christophe Coenraets): Real-time Trader Desktop Android

23.11.2012.

ACTIONSCRIPT 3.0
HTTP

URL-
Flash Player 9 , Adobe AIR 1.0
navigateToURL() URL- -
. , AIR, navigateToURL()
- .
URLRequest, request ,
url.
navigateToURL(), navigate, URLRequest (.
URLRequest 871).
window, . , -
www.adobe.com:
var url:String = "http://www.adobe.com";
var urlReq:URLRequest = new URLRequest(url);
navigateToURL(urlReq);

. navigateToURL()
URLRequest, POST (. . , method
URLRequestMethod.POST) , GET.
navigateToURL() URI
, navigateToURL().
API- -.
URI API- AIR.
, API-. (
. AIR
1159.)
( AIR)
URL-, ,
AIR, URI. ,
URI. .
.

http:

https:

file:

mailto: AIR

sms: AIR sms: . URL , ,


. , Android URI .
navigateToURL( new URLRequest( "sms:+15555550101") );

tel: AIR tel: . URL-

, ,
. , Android URI .
navigateToURL( new URLRequest( "tel:5555555555") );

23.11.2012.

888

ACTIONSCRIPT 3.0
HTTP

market: AIR market: ,

Android.
navigateToURL( new URLRequest( "market://search?q=Adobe Flash") );
navigateToURL( new URLRequest( "market://search?q=pname:com.adobe.flashplayer") );

,
URI. URL AIR.

. , -.

http:

https:

mailto: AIR

URI .

. , -.

file:

mailto: AIR

URI .

. , -.

http:

https:

mailto: AIR

URI .

. , -.

file:

http:

https:

mailto: AIR

URI .

23.11.2012.

889

890

45.
Flash Player AIR
Flash Player 9 , Adobe AIR 1.0
LocalConnection Adobe AIR,
SWF, . LocalConnection
AIR SWF, .
LocalConnection ,
Flash Player AIR.

LocalConnection
Flash Player 9 , Adobe AIR 1.0
LocalConnection SWF-, SWF, fscommand() JavaScript. LocalConnection
SWF-, , , ,
. , SWF-, , SWF-, ,
, , SWF-
. ( SWF-, ,
,
Flash Player, .)
LocalConnection SWF-,
ActionScript:

ActionScript 3.0 LocalConnection LocalConnection,


ActionScript 1.0 2.0.

LocalConnection ActionScript 1.0 2.0


LocalConnection, ActionScript 3.0.
Flash Player LocalConnection
.
LocalConnection
LocalConnection, AIR.
.
, . .
connectionName send() allowDomain() domain LocalConnection
c ActionScript 3.0 Adobe Flash Platform.
LocalConnection SWF-,
Adobe . .
LocalConnection:

LocalConnection ;
23.11.2012.

ACTIONSCRIPT 3.0
Flash Player AIR

LocalConnection.client , ;
, LocalConnection,
.

LocalConnection. ,
LocalConnection. .
package
{
import flash.net.LocalConnection;
public class CustomLocalConnection extends LocalConnection
{
public function CustomLocalConnection(connectionName:String)
{
try
{
connect(connectionName);
}
catch (error:ArgumentError)
{
// server already created/connected
}
}
public function onMethod(timeString:String):void
{
trace("onMethod called at: " + timeString);
}
}
}

CustomLocalConnection, :
var serverLC:CustomLocalConnection;
serverLC = new CustomLocalConnection("serverName");


LocalConnection.client.
client, .
var lc:LocalConnection = new LocalConnection();
lc.client = new CustomClient();

LocalConnection.client .
client ,
CustomClient. client LocalConnection.
client , ,
, ,
.
CustomClient, :

23.11.2012.

891

ACTIONSCRIPT 3.0
Flash Player AIR

package
{
public class CustomClient extends Object
{
public function onMethod(timeString:String):void
{
trace("onMethod called at: " + timeString);
}
}
}


. LocalConnection
ActionScript, .
import flash.net.LocalConnection;
dynamic class DynamicLocalConnection extends LocalConnection {}

.
var connection:DynamicLocalConnection = new DynamicLocalConnection();
connection.onMethod = this.onMethod;
// Add your code here.
public function onMethod(timeString:String):void
{
trace("onMethod called at: " + timeString);
}

,
. ,
,
, .
isPerUser
isPerUser Flash Player (10.0.32) AIR (1.5.2)
, , Mac .
,
. isPerUser true.
false.
.


Flash Player 9 , Adobe AIR 1.0
LocalConnection AIR,
Adobe Flash Player (SWF), .
LocalConnection AIR SWF,
.
, - Flash Player, Flash
Player Flash Player .

23.11.2012.

892

ACTIONSCRIPT 3.0
Flash Player AIR

LocalConnection,
LocalConnection :
package
{
import flash.net.LocalConnection;
import flash.display.Sprite;
public class ServerLC extends Sprite
{
public function ServerLC()
{
var lc:LocalConnection = new LocalConnection();
lc.client = new CustomClient1();
try
{
lc.connect("conn1");
}
catch (error:Error)
{
trace("error:: already connected");
}
}
}
}

LocalConnection lc client
clientObject. LocalConnection,
clientObject.
, ArgumentError,
, , .
, Flash Player SWF-
, , client
CustomClient1.

23.11.2012.

893

ACTIONSCRIPT 3.0
Flash Player AIR

package
{
import flash.events.*;
import flash.system.fscommand;
import flash.utils.Timer;
public class CustomClient1 extends Object
{
public function doMessage(value:String = ""):void
{
trace(value);
}
public function doQuit():void
{
trace("quitting in 5 seconds");
this.close();
var quitTimer:Timer = new Timer(5000, 1);
quitTimer.addEventListener(TimerEvent.TIMER, closeHandler);
}
public function closeHandler(event:TimerEvent):void
{
fscommand("quit");
}
}
}

LocalConnection, LocalConnection.connect()
. , ArgumentError,
, .
LocalConnection conn1:
try
{
connection.connect("conn1");
}
catch (error:ArgumentError)
{
trace("Error! Server already exists\n");
}


LocalConnection LocalConnection, LocalConnection.send()
, . , doQuit
LocalConnection, , :
sendingConnection.send("conn1", "doQuit");

LocalConnection conn1
doMessage() .
, send(),
:
sendingConnection.send("conn1", "doMessage", "Hello world");

23.11.2012.

894

ACTIONSCRIPT 3.0
Flash Player AIR


AIR
Flash Player 9 , Adobe AIR 1.0
,
allowDomain() allowInsecureDomain() LocalConnection
, LocalConnection.
ActionScript LocalConnection.allowDomain()
LocalConnection.allowInsecureDomain()

. ActionScript 3.0 LocalConnection.allowDomain()


LocalConnection.allowInsecureDomain() . ,

Security.allowDomain() Security.allowInsecureDomain(),
.
Flash Player 8 SWF-.
SWF-, , .
localhost, SWF- SWF-.
LocalConnection.send() SWF-
, , securityError
(SecurityErrorEvent.SECURITY_ERROR).
LocalConnection.allowDomain() .
LocalConnection.allowDomain() LocalConnection.allowInsecureDomain()
: * localhost. (*) .
localhost , ,
.
LocalConnection.send() ,
, ,
securityError (SecurityErrorEvent.SECURITY_ERROR).
LocalConnection.allowDomain() .

connectionName, (_)
(, myDomain:connectionName).
LocalConnection.connect(connectionName).
connectionName,
.
LocalConnection .
:

connectionName ,
(, myDomain:connectionName).
,
LocalConnection (,
myDomain:connectionName). HTML SWF
LocalConnection
(, anotherDomain:connectionName). LocalConnection
.

23.11.2012.

895

ACTIONSCRIPT 3.0
Flash Player AIR

connectionName (, _connectionName),
. ,
LocalConnection connectionName.
LocalConnection.allowDomain() ,
, HTML SWF LocalConnection
LocalConnection.
connectionName
, ,
connectionName. , ,
.
.
.
Adobe AIR
AIR (,
AIR) ,
, AIR. app#,
, (.) ( ). ,
connectionName
com.example.air.MyApp :
"app#com.example.air.MyApp". , appConnection,
connectionName
"app#com.example.air.MyApp:appConnection". ,
:
"app#com.example.air.MyApp.B146A943FBD637B68C334022D304CEA226D129B4.1".
AIR
, allowDomain() LocalConnection,
. AIR
, . , AIR
com.example.air.FriendlyApp
214649436BD677B62C33D02233043EA236D13934.1, ,
, :
app#com.example.air.FriendlyApp.214649436BD677B62C33D02233043EA236D13934.1. ( AIR 1.5.3
AIR.)

23.11.2012.

896

897

46.
AIR
Adobe AIR 2
Adobe AIR 2, AIR
. , AIR
.
AIR
.
, :

DMG- Mac OS.


EXE- Windows.
RPM DEB Linux.
.
, -target native -package
ADT.


flash.filesystem.File.openWithDefaultApplication()
flash.desktop.NativeProcess


Adobe AIR 2
AIR ,
. .
(stdin), (stdout)
(stderr).
.
File.openWithDefaultApplication().
AIR . .
731
, test.exe .
"hello"
:

23.11.2012.

ACTIONSCRIPT 3.0
AIR

var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();


var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("hello");
nativeProcessStartupInfo.arguments = processArgs;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.start(nativeProcessStartupInfo);
public function onOutputData(event:ProgressEvent):void
{
var stdOut:ByteArray = process.standardOutput;
var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
trace("Got: ", data);
}


Adobe AIR 2
, NativeProcessInfo, :

, ;
()
().
, NativeProcessInfo
start() NativeProcess.
, , test.exe .
"hello" :
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "hello";
nativeProcessStartupInfo.arguments = processArgs;
nativeProcessStartupInfo.workingDirectory = File.documentsDirectory;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);

, exit() NativeProcess.
, ,
, . ( Mac Linux
executable chmod.)

23.11.2012.

898

ACTIONSCRIPT 3.0
AIR


Adobe AIR 2
AIR ,
, .
NativeProcess:

standardInput .

standardOutput .

standardError .


standardInput
NativeProcess. AIR , NativeProcess
standardInputProgress.
, NativeProcess
ioErrorStandardInput.

, closeInput() NativeProcess.
, NativeProcess standardInputClose.
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.standardInput.writeUTF("foo");
if(process.running)
{
process.closeInput();
}


.
AIR , NativeProcess
standardOutputData.
, NativeProcess
standardOutputError.
, NativeProcess standardOutputClose.

23.11.2012.

899

ACTIONSCRIPT 3.0
AIR

, .
, standardOutputData.
standardOutputData standardOutput NativeProcess.
standardOutputClose exit.
,
.
. ,
standardOutputData, .
.
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, dataHandler);
process.start(nativeProcessStartupInfo);
var bytes:ByteArray = new ByteArray();
function dataHandler(event:ProgressEvent):void
{
bytes.writeBytes(process.standardOutput.readBytes(process.standardOutput.bytesAvailable);
}


.
AIR , NativeProcess
standardErrorData.
, NativeProcess
standardErrorIoError.
, NativeProcess standardErrorClose.
, .
, standardErrorData.
standardErrorData standardError NativeProcess.
standardErrorClose exit.
,
.
. ,
standardErrorData, .
.
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, errorDataHandler);
process.start(nativeProcessStartupInfo);
var errorBytes:ByteArray = new ByteArray();
function errorDataHandler(event:ProgressEvent):void
{
bytes.writeBytes(process.standardError.readBytes(process.standardError.bytesAvailable);
}

23.11.2012.

900

ACTIONSCRIPT 3.0
AIR

Adobe AIR 2
API- .
.
,
. , AIR ,
.
. ,
(, EXE- Windows), API. API- ,
. ,
.
AIR Windows .bat.
(cmd.exe) .bat Windows. .bat
, , ,
.
cmd.exe . ,
AIR myBat.bat myArguments c:/evil.exe.
cmd.exe .bat evil.exe.

23.11.2012.

901

902

47. API
Flash Player 9 , Adobe AIR 1.0
API- ActionScript 3.0 (flash.external.ExternalInterface) ActionScript
, Adobe Flash Player,
. API- ExternalInterface, SWF JavaScript HTML-.
API- ,
ActionScript JavaScript HTML-.
API- :

;
ActionScript -,
AIR

ActionScript -
-, ActionScript -
. ActionScript
SWF- , Flash Player
, SWF-. Flash Player
. Flash Player
- ( ).
.
API AIR
AIR , ,
. AIR SWF- ,
ActionScript SWF- (
).
, AIR SWF- HTML
HTMLLoader ( HTML Flex), HTMLLoader .
ActionScript SWF-
JavaScript HTML, HTMLLoader.

23.11.2012.

ACTIONSCRIPT 3.0
API

API
Flash Player 9 , Adobe AIR 1.0
SWF- (,
Adobe Flash Professional SWF-), SWF
. , , SWF-,
HTML. SWF-
.
, ,
SWF- -. , -
HTML, SWF-
(, ). ,
-, - SWF-. ActionScript
, API ActionScript SWF .

, .
, Flash Player SWF-, -
HTML-, Flash Player AIR, SWF
.
, SWF- Flash Player.

, Flash Professional Flash Player.


SWF- - ,
, SWF- ,
SWF- , Flash Player .
- , (
) ( )
. .


, .

,
.
,

(,
, ).

,
, , .
API ( ) ActionScript,
, (, -, SWF) .

23.11.2012.

903

ACTIONSCRIPT 3.0
API

ActionScript JavaScript, .
1 Flash Professional .
2 > .
3 ,

Flash HTML.
4 . SWF- HTML-

,
, O.
5 HTML. , HTML- , ,

JavaScript. HTML ,
HTML- Flash , HTML-
SWF-.
6 , O.
7 HTML HTML, Flash SWF-

. HTML script,
JavaScript :
<script>
// add the sample JavaScript code here
</script>

8 HTML Flash.
9 1 .
10 ActionScript .
11 > , SWF-, .
12 - HTML-, ,

ActionScript HTML.
ActionScript, .
1 Flash Professional .
, SWF-.
2 > .
3 ,

Flash.
4 , Flash, , ,

SWF-. SWF-; , ,
Flash , SWF- (,
, ).
5 1 .
6 ActionScript .
7 > , SWF-.
8 , ActionScript

23.11.2012.

904

ACTIONSCRIPT 3.0
API

API- HTML-
. :

API: ActionScript JavaScript - 910


, ActionScript ,
API.
API ExternalInterface ActionScript 3.0 Adobe Flash
Professional CS5.

API
Flash Player 9 , Adobe AIR 1.0
API ActionScript, ActionScript
, , Flash Player
( - ). ActionScript 3.0
API ExternalInterface. ,
Flash Player 8, fscommand() .
ExternalInterface fscommand().
. fscommand() (,
SWF
Flash Player),
flash.system.
ExternalInterface ,
ActionScript Flash Player JavaScript HTML-.
ExternalInterface :

Internet Explorer Windows (5.0 );


, NPRuntime, ,
Firefox 1.0, Mozilla 1.7.5, Netscape 8.0 Safari 1.3.

AIR, SWF- HTML-,


HTMLLoader.
(, )
ExternalInterface.available false.
ActionScript JavaScript HTML. API
fscommand():

JavaScript, ,
fscommand().

,
. API , fscommand().

(, Boolean, Number String),


String.

, ActionScript (
).

23.11.2012.

905

ACTIONSCRIPT 3.0
API

. , Flash Player HTML ( id


object), (-) , JavaScript (,
+, *, /, \, . ), ExternalInterface ActionScript -
Internet Explorer . , HTML,
Flash Player ( object embed), HTML form, ExternalInterface ActionScript
.

ExternalInterface
Flash Player 9 , Adobe AIR 1.0
ActionScript : ActionScript
( JavaScript), ,
ActionScript, .
, , .
, ExternalInterface
.
, ActionScript , ActionScript
.


Flash Player 9 , Adobe AIR 1.0
ExternalInterface.available , Flash Player ,
. , true;
false. ExternalInterface
,
. :
if (ExternalInterface.available)
{
// Perform ExternalInterface method calls here.
}

. ExternalInterface.available ,
, ExternalInterface. ,
JavaScript .
ExternalInterface.objectID Flash
Player ( id object Internet Explorer name embed
NPRuntime). SWF-
. SWF- (,
JavaScript HTML ). Flash Player -,
null.

23.11.2012.

906

ACTIONSCRIPT 3.0
API

ActionScript
Flash Player 9 , Adobe AIR 1.0
ExternalInterface.call() .
(, ,
). , ExternalInterface.call(),
.
// calls the external function "addNumbers"
// passing two parameters, and assigning that function's result
// to the variable "result"
var param1:uint = 3;
var param2:uint = 7;
var result:uint = ExternalInterface.call("addNumbers", param1, param2);

HTML, JavaScript ,
script HTML, .
JavaScript ActionScript.
<script language="JavaScript">
// adds two numbers, and sends the result back to ActionScript
function addNumbers(num1, num2)
{
return (num1 + num2);
}
</script>

- ActiveX,
ActiveX Flash Player FlashCall. Flash Player
XML.
request .
ActionScript, SetReturnValue() ActiveX,
( XML)
. XML, , .
XML API 909.
, - ActiveX,
, null.
ExternalInterface.call() SecurityError,
, .
, allowScriptAccess , . ,
allowScriptAccess HTML,
object embed.

ActionScript
Flash Player 9 , Adobe AIR 1.0
ActionScript,
ActionScript. ActionScript ,
: ExternalInterface,
.

23.11.2012.

907

ACTIONSCRIPT 3.0
API

-, ActionScript, ,
. ExternalInterface.addCallback() :
function callMe(name:String):String
{
return "busy signal";
}
ExternalInterface.addCallback("myFunction", callMe);

addCallback() . String.
, .
ActionScript, .
, , ,
ActionScript . ,
(,
).
ActionScript ExternalInterface .
. , JavaScript -
ActionScript ,
Flash Player ( , JavaScript, object embed).
, , , .
<script language="JavaScript">
// callResult gets the value "busy signal"
var callResult = flashObject.myFunction("my name");
</script>
...
<object id="flashObject"...>
...
<embed name="flashObject".../>
</object>

, ActionScript SWF-,
,
XML. CallFunction()
ActiveX, XML. XML,
, . XML API 909.
, ActionScript, .
, JavaScript
, XML, ActiveX.

23.11.2012.

908

909

ACTIONSCRIPT 3.0
API

XML API
Flash Player 9 , Adobe AIR 1.0
ActionScript , ActiveX Shockwave
Flash, XML, .
XML, API.
. .
, ,
. XML ActionScript
ActionScript. ActionScript Flash Player XML .
, Flash Player , XML
. XML XML:
<invoke name="functionName" returntype="xml">
<arguments>
... (individual argument values)
</arguments>
</invoke>

invoke. : name ,
returntype xml. , invoke
arguments, ,
, .
, ,
, .
ActionScript.
XML.
/
ActionScript

/ C#

null

null

<null/>

Boolean true

bool true

<true/>

Boolean false

bool false

<false/>

String

string

<string> </string>

Number, int, uint

single, double, int, uint

<number>27.5</number>
<number>-12</number>

23.11.2012.

910

ACTIONSCRIPT 3.0
API

/
ActionScript

/ C#

(

)

,


(, ArrayList
object[])

<array>
<property id="0">
<number>27.5</number>
</property>
<property id="1">
<string>Hello there!</string>
</property>
...
</array>

property

,
id

,

.

Object



(,
HashTable
)

<object>
<property id="name">
<string>John Doe</string>
</property>
<property id="age">
<string>33</string>
</property>
...
</object>

property

,
id

().

<null/> or
<object></object>

ActionScript


.


.

. C#
ActionScript. API
, ActiveX
C#.
API ActiveX,
, , -,
XML. -,
C#, ExternalInterfaceProxy.

API: ActionScript
JavaScript -
Flash Player 9 , Adobe AIR 1.0

ActionScript JavaScript - ,
( : Introvert IM).
HTML - SWF
API. , , :

API
JavaScript ActionScript,

23.11.2012.

911

ACTIONSCRIPT 3.0
API

JavaScript ActionScript


www.adobe.com/go/learn_programmingAS3samples_flash_ru. Introvert IM
Samples/IntrovertIM_HTML. .
File

IntrovertIMApp.fla

Flash (FLA) Flex (MXML).

IntrovertIMApp.mxml
com/example/programmingas3/introvertIM/IMManager.as

, ActionScript
.

com/example/programmingas3/introvertIM/IMMessageEvent.as

, IMManager
.

com/example/programmingas3/introvertIM/IMStatus.as

,
, .

html-flash/IntrovertIMApp.html

HTML- Flash (htmlflash/IntrovertIMApp.html) ,


HTML- Adobe Flex (htmltemplate/index.template.html).
JavaScript, .

html-template/index.template.html

ActionScript
Flash Player 9 , Adobe AIR 1.0
API ,
ActionScript . API ActionScript ,
JavaScript, . -
, , SWF
, JavaScript HTML-.
SWF- JavaScript SWF- HTML, , SWF- .
, IMManager, Introvert IM ,
, SWF- . ,
. IMManager :

23.11.2012.

ACTIONSCRIPT 3.0
API

public function IMManager(initialStatus:IMStatus)


{
_status = initialStatus;
// Check if the container is able to use the external API.
if (ExternalInterface.available)
{
try
{
// This calls the isContainerReady() method, which in turn calls
// the container to see if Flash Player has loaded and the container
// is ready to receive calls from the SWF.
var containerReady:Boolean = isContainerReady();
if (containerReady)
{
// If the container is ready, register the SWF's functions.
setupCallbacks();
}
else
{
// If the container is not ready, set up a Timer to call the
// container at 100ms intervals. Once the container responds that
// it's ready, the timer will be stopped.
var readyTimer:Timer = new Timer(100);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
}
...
}
else
{
trace("External interface is not available for this container.");
}
}

, API
ExternalInterface.available. . ,
, ,
try ( catch ).
isContainerReady():
private function isContainerReady():Boolean
{
var result:Boolean = ExternalInterface.call("isReady");
return result;
}

isContainerReady() ExternalInterface.call(),
JavaScript isReady() :

23.11.2012.

912

ACTIONSCRIPT 3.0
API

<script language="JavaScript">
<!-// ------- Private vars ------var jsReady = false;
...
// ------- functions called by ActionScript ------// called to check if the page has initialized and JavaScript is available
function isReady()
{
return jsReady;
}
...
// called by the onload event of the <body> tag
function pageInit()
{
// Record that JavaScript is ready to go.
jsReady = true;
}
...
//-->
</script>

isReady() jsReady.
false; onload - true.
, ActionScript isReady() , JavaScript
false ExternalInterface.call("isReady"), ActionScript isContainerReady()
false. JavaScript isReady()
true. isContainerReady() ActionScript true.
IMManager .
isContainerReady() true, setupCallbacks(),
JavaScript. , isContainerReady() false,
. Timer,
timerHandler() 100 :
private function timerHandler(event:TimerEvent):void
{
// Check if the container is now ready.
var isReady:Boolean = isContainerReady();
if (isReady)
{
// If the container has become ready, we don't need to check anymore,
// so stop the timer.
Timer(event.target).stop();
// Set up the ActionScript methods that will be available to be
// called by the container.
setupCallbacks();
}
}

, timerHandler(),
isContainerReady(). true.
Timer setupCallbacks(),
.

23.11.2012.

913

ACTIONSCRIPT 3.0
API

ActionScript JavaScript
Flash Player 9 , Adobe AIR 1.0
, , , ,
setupCallbacks(). ActionScript JavaScript,
:
private function setupCallbacks():void
{
// Register the SWF client functions with the container
ExternalInterface.addCallback("newMessage", newMessage);
ExternalInterface.addCallback("getStatus", getStatus);
// Notify the container that the SWF is ready to be called.
ExternalInterface.call("setSWFIsReady");
}

setCallBacks()
ExternalInterface.addCallback() ,
JavaScript. (, JavaScript ("newMessage"
"getStatus") ActionScript.
, .
ExternalInterface.call() JavaScriptsetSWFIsReady(),
, ActionScript .

ActionScript
Flash Player 9 , Adobe AIR 1.0
Introvert IM JavaScript
. ( setupCallbacks()) setSWFIsReady()
JavaScript - :
ExternalInterface.call("setSWFIsReady");

isContainerReady() ActionScript isReady()


:
var result:Boolean = ExternalInterface.call("isReady");

JavaScript API. , ,
sendMessage() IMManager, ,
:
public function sendMessage(message:String):void
{
ExternalInterface.call("newMessage", message);
}

ExternalInterface.call() JavaScript,
. ,
ExternalInterface.call()
JavaScriptnewMessage().

23.11.2012.

914

ACTIONSCRIPT 3.0
API

ActionScript JavaScript
Flash Player 9 , Adobe AIR 1.0
, Introvert IM .
Flash Player JavaScript
. HTML- JavaScript
SWF-. , SWF- ,
, getStatus()
IMManager,
SWF. - updateStatus() :
<script language="JavaScript">
...
function updateStatus()
{
if (swfReady)
{
var currentStatus = getSWF("IntrovertIMApp").getStatus();
document.forms["imForm"].status.value = currentStatus;
}
}
...
</script>

swfReady, , SWF-
, ExternalInterface. SWF- ,
(var currentStatus = ...) getStatus() IMManager.
.

getSWF() JavaScript, JavaScript,


SWF-. , getSWF(), ,
, HTML- SWF-. ,
, id object name embed,
SWF-.

SWF- getStatus() ,
SWF. getStatus, ,
ActionScript ExternalInterface.addCallback().

getStatus() ActionScript ,
currentStatus, ( value)
status.

. , , , ,
updateStatus() , getSWF(),
: var currentStatus = getSWF("${application}").getStatus(). ${application}
HTML. Adobe Flash Builder
HTML , ,
id object name embed (
IntrovertIMApp). getSWF().
sendMessage() JavaScript ActionScript.
(sendMessage() , ,
HTML-.)

23.11.2012.

915

ACTIONSCRIPT 3.0
API

<script language="JavaScript">
...
function sendMessage(message)
{
if (swfReady)
{
...
getSWF("IntrovertIMApp").newMessage(message);
}
}
...
</script>

newMessage() ActionScript . message JavaScript


ActionScript. newMessage() JavaScript.


Flash Player 9 , Adobe AIR 1.0
- JavaScript,

, getSWF()
JavaScript :
<script language="JavaScript">
...
function getSWF(movieName)
{
if (navigator.appName.indexOf("Microsoft") != -1)
{
return window[movieName];
}
else
{
return document[movieName];
}
}
...
</script>

,
SWF- HTML.

23.11.2012.

916

917

48. XML
AIR
Adobe AIR 1.5
API- Adobe AIR XMLSignatureValidator
W3C XML-
(http://http://www.w3.org/TR/xmldsig-core/). XML-
.
XML- , .
, ,
XML- . - ,
.
XML- , ,
, . ,
, ,
. , SWF-
,
.

XML-
Adobe AIR 1.5
c XML .
Adobe Developer Connection:

XML- (Flex)
XML- (Flash)
Adobe AIR XMLSignatureValidator IURIDereferencer XML. XML-, XMLSignatureValidator,
W3C XML-. (
, .) Adobe AIR
XML-.

XML
Adobe AIR 1.5
XML- :

23.11.2012.

ACTIONSCRIPT 3.0
XML AIR

flash.security

XMLSignatureValidator

IURIDereferencer ()

XMLSignatureValidator :

flash.events

ReferencesValidationSetting

RevocationCheckSettings

SignatureStatus

SignerTrustSettings

Event

ErrorEvent

XML-
Adobe AIR 1.5
XMLSignatureValidator XML-,
:

XMLSignatureValidator
IURIDereferencer. XMLSignatureValidator
dereference() IURIDereferencer, URI

. dereference() URI
( , ,
).

,
XMLSignatureValidator, .

complete error.
verify(), .
complete error, .
validate(), XML-.
XMLSignatureValidator ,

. , IURIDereferencer
XMLDereferencer.

23.11.2012.

918

ACTIONSCRIPT 3.0
XML AIR

private function validate( xmlSignature:XML ):void


{
var verifier:XMLSignatureValidator = new XMLSignatureValidator();
verifier.addEventListener(Event.COMPLETE, verificationComplete);
verifier.addEventListener(ErrorEvent.ERROR, verificationError);
try
{
verifier.uriDereferencer = new XMLDereferencer();
verifier.referencesValidationSetting =
ReferencesValidationSetting.VALID_IDENTITY;
verifier.revocationCheckSetting = RevocationCheckSettings.BEST_EFFORT;
verifier.useSystemTrustStore = true;
//Verify the signature
verifier.verify( xmlSignature );
}
catch (e:Error)
{
trace("Verification error.\n" + e);
}
}
//Trace verification results
private function verificationComplete(event:Event):void
var signature:XMLSignatureValidator = event.target as XMLSignatureValidator;
trace("Signature status: " + signature.validityStatus + "\n");
trace(" Digest status: " + signature.digestStatus + "\n");
trace(" Identity status: " + signature.identityStatus + "\n");
trace(" Reference status: " + signature.referencesStatus + "\n");
}
private function verificationError(event:ErrorEvent):void
{
trace("Verification error.\n" + event.text);
}

XML-
Adobe AIR 1.5
verify() XMLSignatureValidator AIR :

,
.

,
XMLSignatureValidator.
.
,
.
, :

23.11.2012.

919

ACTIONSCRIPT 3.0
XML AIR

, ,
,
, .

, .
,
.

.
IURIDereferencer.
dereference() IURIDereferencer. ,
dereference(), .
, . , ,
, .
XML- ,
. ,
, . XMLSignatureValidator ,
, . ,
,
.
.
( , )
, .
.


Adobe AIR 1.5
XMLSignatureValidator.
, validator complete.
: validityStatus, digestStatus, identityStatus referencesStatus.
validityStatus
Adobe AIR 1.5
validityStatus . validityStatus
:

valid digestStatus, identityStatus referencesStatus valid.

invalid invalid.

unknown unknown
invalid.

23.11.2012.

920

ACTIONSCRIPT 3.0
XML AIR

digestStatus
Adobe AIR 1.5
digestStatus .
digestStatus :

valid .

invalid .

unknown verify() .

identityStatus
Adobe AIR 1.5
identityStatus .
:

;
;
;
XMLSignatureValidator (
, ,
useSystemTrustStore revocationCheckSettings)
identityStatus :

valid ,

.

, ,
. ,
. (,

.)

. ,

useSystemTrustStore true.
, addCertificate() XMLSignatureValidator.

, , .

invalid ; ,

; ,
.

unknown , , .

, , unknown (
). identityStatus unknown,
verify() ,
- .

23.11.2012.

921

ACTIONSCRIPT 3.0
XML AIR

referencesStatus
Adobe AIR 1.5
referencesStatus SignedData
.

valid

, XML-. valid ,
.

invalid .

unknown . ,

invalid .
identityStatus unknown, ,

referencesValidationSetting validOrUnknown.

XML-
Adobe AIR 1.5
XML- , XML-.
XML- ,
. ,

.
XML- ( XML-). XML :

, ;
, ;
.

XML-
Adobe AIR 1.5
Adobe AIR W3C
XML-:

( 4 W3C),
KeyInfo,

KeyInfo X509Data
X509Data X509Certificate
SHA256
RSA-SHA1 (PKCS1)
XML

23.11.2012.

922

ACTIONSCRIPT 3.0
XML AIR



XML- (
).
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="URI_to_signed_data">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#envelopedsignature"/></Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>uoo...vY=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>Ked...w==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>i7d...w==</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>

SignedInfo
. , XML-,
.

SignatureValue SignedInfo,
.

KeyInfo , ,
. , , KeyInfo
, AIR .
XML-:

XML-, .
XML- - .
XML-.
. ,
XML-, ,
.
XML- URI .

URI. XMLSignatureValidator
IURIDereferencer. URI
ByteArray. ByteArray
. .

23.11.2012.

923

ACTIONSCRIPT 3.0
XML AIR


Adobe AIR 1.5
, , , ,
, .
.
, ,
, , SSL.

.
, ,
.

. .
,
.
. , AIR
,
.
. ( ,
, ,
AIR, .)
.
, ,
. , ,
.
.

Adobe AIR 1.5
.
, , .
,
, .
XMLSignatureValidator , ,
.
, ,
.
.
, ,
, . XMLSignatureValidator
,
.

23.11.2012.

924

ACTIONSCRIPT 3.0
XML AIR

IURIDereferencer
Adobe AIR 1.5
XML- IURIDereferencer.
URI Reference XML- ,
.
, .
. HTML- AIR SWF-,
ActionScript, XML-. IURIDereferencer
JavaScript.
IURIDerefencer , dereference(uri:String),
. XMLSignatureValidator .
ByteArray.
,
dereferencer . ,
, , member, XML.
dereference() URI
. ,
, dereference() ,
, .
XMLSignatureValidator dereferencer
URI. URI
4.3.3 W3C XML-.

URI
Adobe AIR 1.5
XML- . ,
.
<message>
<data>...</data>
</message>

23.11.2012.

925

ACTIONSCRIPT 3.0
XML AIR

<message>
<data>...</data>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#envelopedsignature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>yv6...Z0Y=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>cCY...LQ==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MII...4e</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</message>

, Reference
URI. .
, ,
.
XMLSignatureValidator . ,
dereferencer Signature .
dereferencer :
package
{
import
import
import
import
import

flash.events.ErrorEvent;
flash.events.EventDispatcher;
flash.security.IURIDereferencer;
flash.utils.ByteArray;
flash.utils.IDataInput;

public class EnvelopedDereferencer


extends EventDispatcher implements IURIDereferencer
{
private var signedMessage:XML;
public function EnvelopedDereferencer( signedMessage:XML )
{
this.signedMessage = signedMessage;
}
public function dereference( uri:String ):IDataInput
{
try
{

23.11.2012.

926

ACTIONSCRIPT 3.0
XML AIR

if( uri.length != 0 )
{
throw( new Error("Unsupported signature type.") );
}
var data:ByteArray = new ByteArray();
data.writeUTFBytes( signedMessage.toXMLString() );
data.position = 0;
}
catch (e:Error)
{
var error:ErrorEvent =
new ErrorEvent("Ref error " + uri + " ", false, false, e.message);
this.dispatchEvent(error);
data = null;
throw new Error("Reference not resolvable: " + uri + ", " + e.message);
}
finally
{
return data;
}
}
}
}

dereferencer signedMessage
, dereference().
, dereferencer()
Byte Array .

URI

Adobe AIR 1.5


, , URI
XPath XPointer .
W3C XML-
, ,
(
).
AIR .
Manifest. Manifest Reference URI,
"#PackageContents", Manifest:

23.11.2012.

927

ACTIONSCRIPT 3.0
XML AIR

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#" Id="PackageSignature">


<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/TR/xmldsig-core#rsa-sha1"/>
<Reference URI="#PackageContents">
<Transforms>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>ZMGqQdaRKQc1HirIRsDpeBDlaElS+pPotdziIAyAYDk=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue Id="PackageSignatureValue">cQK...7Zg==</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MII...T4e</X509Certificate>
</X509Data>
</KeyInfo>
<Object>
<Manifest Id="PackageContents">
<Reference URI="mimetype">
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256">
</DigestMethod>
<DigestValue>0/oCb84THKMagtI0Dy0KogEu92TegdesqRr/clXct1c=</DigestValue>
</Reference>
<Reference URI="META-INF/AIR/application.xml">
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256">
</DigestMethod>
<DigestValue>P9MqtqSdqcqnFgeoHCJysLQu4PmbUW2JdAnc1WLq8h4=</DigestValue>
</Reference>
<Reference URI="XMLSignatureValidation.swf">
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256">
</DigestMethod>
<DigestValue>OliRHRAgc9qt3Dk0m0Bi53Ur5ur3fAweIFwju74rFgE=</DigestValue>
</Reference>
</Manifest>
</Object>
</Signature>

dereferencer URI, "#PackageContents"


Reference, Manifest ByteArray. #
.
dereferencer AIR.
, .. AIR.
dereferencer .

23.11.2012.

928

ACTIONSCRIPT 3.0
XML AIR

package
{
import
import
import
import

flash.events.ErrorEvent;
flash.security.IURIDereferencer;
flash.utils.ByteArray;
flash.utils.IDataInput;

public class AIRSignatureDereferencer implements IURIDereferencer {


private const XML_SIG_NS:Namespace =
new Namespace( "http://www.w3.org/2000/09/xmldsig#" );
private var airSignature:XML;
public function AIRSignatureDereferencer( airSignature:XML ) {
this.airSignature = airSignature;
}
public function dereference( uri:String ):IDataInput {
var data:ByteArray = null;
try
{
if( uri != "#PackageContents" )
{
throw( new Error("Unsupported signature type.") );
}
var manifest:XMLList =
airSignature.XML_SIG_NS::Object.XML_SIG_NS::Manifest;
data = new ByteArray();
data.writeUTFBytes( manifest.toXMLString());
data.position = 0;
}
catch (e:Error)
{
data = null;
throw new Error("Reference not resolvable: " + uri + ", " + e.message);
}
finally
{
return data;
}
}
}
}

, Manifest.
.
, , SHA256
, . XMLSignatureValidator
.
. , .
, AIR .
, .

23.11.2012.

929

ACTIONSCRIPT 3.0
XML AIR


Adobe AIR 1.5
Adobe AIR SHA256, Flex SDK
SHA256. Base64,
, .
, AIR:
import mx.utils.Base64Encoder;
import mx.utils.SHA256;
private
{
var
var
var

function verifyManifest( sigFile:File, manifest:XML ):Boolean


result:Boolean = true;
message:String = '';
nameSpace:Namespace = manifest.namespace();

if( manifest.nameSpace::Reference.length() <= 0 )


{
result = false;
message = "Nothing to validate.";
}
for each (var reference:XML in manifest.nameSpace::Reference)
{
var file:File = sigFile.parent.parent.resolvePath( reference.@URI );
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var fileData:ByteArray = new ByteArray();
stream.readBytes( fileData, 0, stream.bytesAvailable );
var digestHex:String = SHA256.computeDigest( fileData );
//Convert hexidecimal string to byte array
var digest:ByteArray = new ByteArray();
for( var c:int = 0; c < digestHex.length; c += 2 ){
var byteChar:String = digestHex.charAt(c) + digestHex.charAt(c+1);
digest.writeByte( parseInt( byteChar, 16 ));
}
digest.position = 0;

23.11.2012.

930

ACTIONSCRIPT 3.0
XML AIR

var base64Encoder:Base64Encoder = new Base64Encoder();


base64Encoder.insertNewLines = false;
base64Encoder.encodeBytes( digest, 0, digest.bytesAvailable );
var digestBase64:String = base64Encoder.toString();
if( digestBase64 == reference.nameSpace::DigestValue )
{
result = result && true;
message += "
" + reference.@URI + " verified.\n";
}
else
{
result = false;
message += " ---- " + reference.@URI + " has been modified!\n";
}
base64Encoder.reset();
}
trace( message );
return result;
}

Manifest.
SHA256, base64, .
URI AIR .
, META-INF
. , Flex SHA256
. ByteArray,
, .
mx.utils.SHA256 Base64Encoder Flash CS4,
, SWF,
Flex SDK.

URI ,

Adobe AIR 1.5
URI ,
ByteArray. URI URL,
URL. , , , ,
URI , IURIDereferencer
.
File,
dereferencer .

23.11.2012.

931

ACTIONSCRIPT 3.0
XML AIR

package
{
import flash.events.ErrorEvent;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.security.IURIDereferencer;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
public class RelativeFileDereferencer
extends EventDispatcher implements IURIDereferencer
{
private var base:File;
public function RelativeFileDereferencer( base:File )
{
this.base = base;
}
public function dereference( uri:String ):IDataInput
{
var data:ByteArray = null;
try{
var referent:File = this.base.resolvePath( uri );
var refStream:FileStream = new FileStream();
data = new ByteArray();
refStream.open( referent, FileMode.READ );
refStream.readBytes( data, 0, data.bytesAvailable );
} catch ( e:Error ) {
data = null;
throw new Error("Reference not resolvable: " + referent.nativePath + ", " +
e.message );
} finally {
return data;
}
}
}
}

dereference() , URI ,
ByteArray.
. ,

.

23.11.2012.

932

933

49.
Flash Player 9 , Adobe AIR 1.0
. ,

(IME), .
.


flash.system.System
flash.system.Capabilities


Flash Player 9 , Adobe AIR 1.0
,
. flash.system ,
, :

, ;
Flash ( Flash Player
Adobe AIR), (), ,
mp3;

(IME);
Flash ( HTML-
).

.
flash.system IMEConversionMode SecurityPanel.
, IME Security .

.
, ,

Microsoft Windows, Mac OS X Linux.


(

), .
, SWF-.
, SWF-
.

23.11.2012.

ACTIONSCRIPT 3.0

(IME) ( ),

.
( ),
.
.

System
Flash Player 9 , Adobe AIR 1.0
System ,
. ,
System imeComposition,

.


Flash Player 9 , Adobe AIR 1.0
System.totalMemory, ( ),

. ,
, ,
.
System.ime (IME).
imeComposition (flash.events.IMEEvent.IME_COMPOSITION)
addEventListener().
System useCodePage. useCodePage
true,
. false,
.
System.useCodePage true, ,
, ,
. , ,
, ,
Windows , .

, ,
System.useCodePage false. ,
.

23.11.2012.

934

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
System setClipboard(), Flash
. Security.getClipboard()
,
, .
, ,
. ,
.
private function securityErrorHandler(event:SecurityErrorEvent):void
{
var errorString:String = "[" + event.type + "] " + event.text;
trace(errorString);
System.setClipboard(errorString);
}

Flash Player 10 AIR 1.0


Clipboard
. AIR , ,
, .

Capabilities
Flash Player 9 , Adobe AIR 1.0
Capabilities , .
Capabilities ,
,
Flash.
Capabilities,
. , Capabilities.screenResolutionX
Capabilities.screenResolutionY
. Capabilities.hasMP3, ,
mp3, mp3-.
Flash
.

23.11.2012.

935

ACTIONSCRIPT 3.0

var versionString:String = Capabilities.version;


var pattern:RegExp = /^(\w*) (\d*),(\d*),(\d*),(\d*)$/;
var result:Object = pattern.exec(versionString);
if (result != null)
{
trace("input: " + result.input);
trace("platform: " + result[1]);
trace("majorVersion: " + result[2]);
trace("minorVersion: " + result[3]);
trace("buildNumber: " + result[4]);
trace("internalBuildNumber: " + result[5]);
}
else
{
trace("Unable to match RegExp.");
}

,
, ActionScript:
var url:String = "log_visitor.cfm";
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
request.data = new URLVariables(Capabilities.serverString);
var loader:URLLoader = new URLLoader(request);

Flash Player 9
CapabilitiesExplorer , flash.system.Capabilities ,
Flash.
:

Flash
Capabilities;

ExternalInterface ,
;

www.adobe.com/go/learn_programmingAS3samples_flash_ru. CapabilitiesExplorer
Samples/CapabilitiesExplorer. :

23.11.2012.

936

937

ACTIONSCRIPT 3.0

File

CapabilitiesExplorer.fla

Flash (FLA) Flex (MXML).

CapabilitiesExplorer.mxml
com/example/programmingas3/capabilities/CapabilitiesGrabber.as

, ,
,

ExternalInterface
.

capabilities.html

HTML-, JavaScript
API-.

CapabilitiesExplorer
Flash Player 9
CapabilitiesExplorer.mxml
CapabilitiesExplorer. Flash
DataGrid .
, HTML-
API-.
creationComplete initApp().
initApp() getCapabilities()
com.example.programmingas3.capabilities.CapabilitiesGrabber. initApp().
private function initApp():void
{
var dp:Array = CapabilitiesGrabber.getCapabilities();
capabilitiesGrid.dataProvider = dp;
}

CapabilitiesGrabber.getCapabilities()
Flash , dataProvider
DataGrid capabilitiesGrid .

CapabilitiesGrabber
Flash Player 9
getCapabilities() CapabilitiesGrabber
flash.system.Capabilities (capDP). getBrowserObjects()
CapabilitiesGrabber. getBrowserObjects() API-
navigator , . getCapabilities()
:

23.11.2012.

ACTIONSCRIPT 3.0

public static function getCapabilities():Array


{
var capDP:Array = new Array();
capDP.push({name:"Capabilities.avHardwareDisable", value:Capabilities.avHardwareDisable});
capDP.push({name:"Capabilities.hasAccessibility", value:Capabilities.hasAccessibility});
capDP.push({name:"Capabilities.hasAudio", value:Capabilities.hasAudio});
...
capDP.push({name:"Capabilities.version", value:Capabilities.version});
var navArr:Array = CapabilitiesGrabber.getBrowserObjects();
if (navArr.length > 0)
{
capDP = capDP.concat(navArr);
}
capDP.sortOn("name", Array.CASEINSENSITIVE);
return capDP;
}

getBrowserObjects() navigator .
, (navArr)
Flash Player (capDP),
. , ,
. getBrowserObjects().
private static function getBrowserObjects():Array
{
var itemArr:Array = new Array();
var itemVars:URLVariables;
if (ExternalInterface.available)
{
try
{
var tempStr:String = ExternalInterface.call("JS_getBrowserObjects");
itemVars = new URLVariables(tempStr);
for (var i:String in itemVars)
{
itemArr.push({name:i, value:itemVars[i]});
}
}
catch (error:SecurityError)
{
// ignore
}
}
return itemArr;
}

API-, Flash
JS_getBrowserObjects() JavaScript, navigator
URL ActionScript.
URLVariables (itemVars) itemArr, .

23.11.2012.

938

ACTIONSCRIPT 3.0

JavaScript
Flash Player 9
CapabilitiesExplorer JavaScript,
navigator . JavaScript JS_getBrowserObjects()
container.html.
<script language="JavaScript">
function JS_getBrowserObjects()
{
// Create an array to hold each of the browser's items.
var tempArr = new Array();
// Loop over each item in the browser's navigator object.
for (var name in navigator)
{
var value = navigator[name];
// If the current value is a string or Boolean object, add it to the
// array, otherwise ignore the item.
switch (typeof(value))
{
case "string":
case "boolean":
// Create a temporary string which will be added to the array.
// Make sure that we URL-encode the values using JavaScript's
// escape() function.
var tempStr = "navigator." + name + "=" + escape(value);
// Push the URL-encoded name/value pair onto the array.
tempArr.push(tempStr);
break;
}
}
// Loop over each item in the browser's screen object.
for (var name in screen)
{
var value = screen[name];
// If the current value is a number, add it to the array, otherwise
// ignore the item.
switch (typeof(value))
{
case "number":
var tempStr = "screen." + name + "=" + escape(value);
tempArr.push(tempStr);
break;
}
}
// Return the array as a URL-encoded string of name-value pairs.
return tempArr.join("&");
}
</script>

23.11.2012.

939

ACTIONSCRIPT 3.0

- navigator.
navigator for..in,
.
, ( ) .
navigator tempArr. screen
for..in, tempArr. ,
Array.join().
(&), ActionScript
URLVariables.

23.11.2012.

940

941

50.
AIR
Adobe AIR 1.0
Adobe AIR,
, , , .
. SWF,
AIR, NativeApplication, InvokeEvent BrowserInvokeEvent. SWF,
Flash Player, , ()
AIR , .
AIR .
Adobe Developer Connection:


flash.desktop.NativeApplication
flash.events.InvokeEvent
flash.events.BrowserInvokeEvent


Adobe AIR 1.0
AIR , ( ):

;
.
, ;
Dock Mac OS (, );
(
AIR );

AIR, ,
( <customUpdateUI>true</customUpdateUI> );

iOS: push- Apple (Apple Push Notification service,


APNs);

URL-;

23.11.2012.

ACTIONSCRIPT 3.0
AIR

- Flash badge ,
com.adobe.air.AIR launchApplication(), AIR. (


<allowBrowserInvocation>true</allowBrowserInvocation> .)

AIR AIR InvokeEvent invoke


NativeApplication.
, invoke , .
, .
. NativeApplication
invoke , .
invoke addEventListener() NativeApplication
(NativeApplication.nativeApplication).
invoke, invoke, . invoke,
,
addEventListener(). invoke,
, .
invoke, . ,
( ),
invoke, .
AIR.
AIR invoke . AIR
invoke (, ).
InvokeEvent , , ,
.
, . ,
, AIR.
, Mac OS X InvokeEvent.
arguments. Windows Linux
InvokeEvent .
invoke
NativeApplication:
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvokeEvent);

:
var arguments:Array;
var currentDir:File;
public function onInvokeEvent(invocation:InvokeEvent):void {
arguments = invocation.arguments;
currentDir = invocation.currentDirectory;
}

23.11.2012.

942

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
, AIR,
InvokeEvent, NativeApplication. InvokeEvent arguments
, AIR.
,
currentDirectory.
, AIR, , ,
:

tick tock

{tick,tock}

tick "tick tock"

{tick,tick tock}

"tick" tock

{tick,tock}

\"tick\" \"tock\"

{"tick","tock"}

currentDirectory InvokeEvent File, ,


.
, ,
. (
). ,
( AIR),
AIR , AIR,
ID.
resolve() File currentDirectory:
if((invokeEvent.currentDirectory != null)&&(invokeEvent.arguments.length > 0)){
dir = invokeEvent.currentDirectory;
fileToOpen = dir.resolvePath(invokeEvent.arguments[0]);
}

, .

:
Adobe AIR 1.0
, invoke.
,
.

23.11.2012.

943

ACTIONSCRIPT 3.0
AIR

ActionScript
package
{
import
import
import
import

flash.display.Sprite;
flash.events.InvokeEvent;
flash.desktop.NativeApplication;
flash.text.TextField;

public class InvokeEventLogExample extends Sprite


{
public var log:TextField;
public function InvokeEventLogExample()
{
log = new TextField();
log.x = 15;
log.y = 15;
log.width = 520;
log.height = 370;
log.background = true;
addChild(log);
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
}
public function onInvoke(invokeEvent:InvokeEvent):void
{
var now:String = new Date().toTimeString();
logEvent("Invoke event received: " + now);
if (invokeEvent.currentDirectory != null)
{
logEvent("Current directory=" + invokeEvent.currentDirectory.nativePath);
}
else
{

23.11.2012.

944

ACTIONSCRIPT 3.0
AIR

logEvent("--no directory information available--");


}
if (invokeEvent.arguments.length > 0)
{
logEvent("Arguments: " + invokeEvent.arguments.toString());
}
else
{
logEvent("--no arguments--");
}
}
public function logEvent(entry:String):void
{
log.appendText(entry + "\n");
trace(entry);
}
}
}

Flex
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
invoke="onInvoke(event)" title="Invocation Event Log">
<mx:Script>
<![CDATA[
import flash.events.InvokeEvent;
import flash.desktop.NativeApplication;
public function onInvoke(invokeEvent:InvokeEvent):void {
var now:String = new Date().toTimeString();
logEvent("Invoke event received: " + now);
if (invokeEvent.currentDirectory != null){
logEvent("Current directory=" + invokeEvent.currentDirectory.nativePath);
} else {
logEvent("--no directory information available--");
}
if (invokeEvent.arguments.length > 0){
logEvent("Arguments: " + invokeEvent.arguments.toString());
} else {
logEvent("--no arguments--");
}
}
public function logEvent(entry:String):void {
log.text += entry + "\n";
trace(entry);
}
]]>
</mx:Script>
<mx:TextArea id="log" width="100%" height="100%" editable="false"
valueCommit="log.verticalScrollPosition=log.textHeight;"/>
</mx:WindowedApplication>

23.11.2012.

945

ACTIONSCRIPT 3.0
AIR

AIR

Adobe AIR 1.0


AIR , .
startAtLogin NativeApplication true.
.
, false,
, .
. .
startAtLogin true, . ,
(, , ADL), .
. , .
, ,
reason InvokeEvent.
InvokeEventReason.LOGIN, .
, reason :

InvokeEventReason.NOTIFICATION ( iOS) APNs.


APNs push-.

InvokeEventReason.OPEN_URL .

InvokeEventReason.Standard .

reason AIR 1.5.1


( ).
reason InvokeEvent,
. reason login,
. .
, , , ,
,
, .

23.11.2012.

946

ACTIONSCRIPT 3.0
AIR

package {
import
import
import
import

flash.desktop.InvokeEventReason;
flash.desktop.NativeApplication;
flash.display.Sprite;
flash.events.InvokeEvent;

public class StartAtLogin extends Sprite


{
public function StartAtLogin()
{
try
{
NativeApplication.nativeApplication.startAtLogin = true;
}
catch ( e:Error )
{
trace( "Cannot set startAtLogin:" + e.message );
}
NativeApplication.nativeApplication.addEventListener( InvokeEvent.INVOKE, onInvoke );
}
private function onInvoke( event:InvokeEvent ):void
{
if( event.reason == InvokeEventReason.LOGIN )
{
//do background processing...
trace( "Running in background..." );
}
else
{
this.stage.nativeWindow.activate();
}
}
}
}

. , .
startAtLogin .

AIR
Adobe AIR 1.0
- AIR,
. ,
allowBrowserInvocation true:
<allowBrowserInvocation>true</allowBrowserInvocation>

, NativeApplication
BrowserInvokeEvent.

23.11.2012.

947

ACTIONSCRIPT 3.0
AIR

BrowserInvokeEvent addEventListener() NativeApplication


(NativeApplication.nativeApplication) AIR.
BrowserInvokeEvent, BrowserInvokeEvent,
. addEventListener(),
BrowserInvokeEvent,
. BrowserInvokeEvent,
(, ). ,
( ),
BrowserInvokeEvent, .
BrowserInvokeEvent.

arguments

(), .

isHTTPS

, URL- https (true, , false,


).

isUserEvent

, (, ).
AIR 1.0 true; AIR
.

sandboxType

.
, Security.sandboxType, . . :

Security.APPLICATION

Security.LOCAL_TRUSTED

Security.LOCAL_WITH_FILE

securityDomain

Security.LOCAL_WITH_NETWORK
.

Security.REMOTE () .

, "www.adobe.com"
"www.example.org".
( ).
.

, . -
AIR, arguments
BrowserInvokeEvent. , API , .
, . ,
securityDomain BrowserInvokeEvent. ,
-, , HTTPs
isHTTPS BrowserInvokeEvent.
. ,
URL- , , URL-
.
.

23.11.2012.

948

ACTIONSCRIPT 3.0
AIR

BrowserInvokeEvent,
. , File ,
. , ,
file:// .


Adobe AIR 1.0
exit() NativeApplication.
, , , ,
. exit() . ,
,
, exit()
.
;
, . ( )
:

, NativeApplication.nativeApplication.autoExit true.
, ,
. ( Mac OS. Windows Linux
Chrome.)

.
,
NativeApplication exiting.
exiting, . closing, close.
- closing, .
, exiting
NativeApplication . , ,
, . ,
, , . Windows
exiting ( autoExit
NativeApplication true).
,
(, : Chrome,
).
1 exiting NativeApplication,
exit() , ,
.

23.11.2012.

949

ACTIONSCRIPT 3.0
AIR

public function applicationExit():void {


var exitingEvent:Event = new Event(Event.EXITING, false, true);
NativeApplication.nativeApplication.dispatchEvent(exitingEvent);
if (!exitingEvent.isDefaultPrevented()) {
NativeApplication.nativeApplication.exit();
}
}

2 exiting NativeApplication.nativeApplication,

( closing).
, ,
. ,
, .
,
NativeApplication.nativeApplication.openedWindows . ,

.
private function onExiting(exitingEvent:Event):void {
var winClosingEvent:Event;
for each (var win:NativeWindow in NativeApplication.nativeApplication.openedWindows) {
winClosingEvent = new Event(Event.CLOSING,false,true);
win.dispatchEvent(winClosingEvent);
if (!winClosingEvent.isDefaultPrevented()) {
win.close();
} else {
exitingEvent.preventDefault();
}
}
if (!exitingEvent.isDefaultPrevented()) {
//perform cleanup
}
}

3 closing.
4 exiting,

, exiting (
).

23.11.2012.

950

951

51.
AIR

Adobe AIR 1.0


, AIR
,
Adobe AIR.


flash.desktop.NativeApplication


Adobe AIR 1.0
.
AIR AIR
,
. AIR
. ,
NativeApplication.setAsDefaultApplication() .
. ,
AIR ,
.
,
.
NativeApplication .
:

isSetAsDefaultApplication()

true, AIR
.

setAsDefaultApplication()

AIR .

removeAsDefaultApplication()

AIR .

getDefaultApplication()

, .

23.11.2012.

ACTIONSCRIPT 3.0
AIR

AIR ,
. ,
.
,
, .

Adobe AIR 1.0


NativeApplication runtimeVersion, ,
(, "1.0.5"). NativeApplication
runtimePatchLevel, (, 2960).
:
trace(NativeApplication.nativeApplication.runtimeVersion);
trace(NativeApplication.nativeApplication.runtimePatchLevel);

AIR
Adobe AIR 1.0
, Adobe AIR, Security.sandboxType
, Security.APPLICATION. (
API- AIR) ,
Adobe AIR, :
if (Security.sandboxType == Security.APPLICATION)
{
// Load SWF that contains AIR APIs
}
else
{
// Load SWF that does not contain AIR APIs
}

, AIR,
, Adobe Flash Player .
, :
, .
, Capabilities.playerType "Desktop",
, ( Flash Player,
).
. AIR 1159.

23.11.2012.

952

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
NativeApplication , .
, NativeApplication.idleThreshold,
, NativeApplication userIdle.
NativeApplication userPresent.
idleThreshold , 300 (5 ).
NativeApplication.nativeApplication.lastUserInput ,
.
2 :
userIdle userPresent:
NativeApplication.nativeApplication.idleThreshold = 120;
NativeApplication.nativeApplication.addEventListener(Event.USER_IDLE, function(event:Event) {
trace("Idle");
});
NativeApplication.nativeApplication.addEventListener(Event.USER_PRESENT,
function(event:Event) {
trace("Present");
});

. userIdle userPresent.

23.11.2012.

953

954

52.
AIR
Adobe AIR 1.0
, API- Adobe AIR,
.

AIR
Adobe AIR 1.0
AIR
Adobe Developer Connection:

(Flex)
(Flex)
(Flex)
(Flex)
(Flex)
(Flex)
(Flex)
(Flash)
(Flash)
(Flash)
(Flash)
(Flash)
AIR API-
Flash, Flex HTML.
AIR .
, Apple,
Mac, Microsoft Windows,
Linux, -
- .
Chrome, Flex,
, .
Chrome
. ? .

23.11.2012.

ACTIONSCRIPT 3.0
AIR

AIR
Adobe AIR 1.0
Adobe AIR .

ActionScript NativeWindow
. NativeWindow
, ActionScript Flash Professional.
NativeWindow , .

HTML JavaScript Window , . JavaScript Window


NativeWindow.

mx:WindowedApplication mx:Window Flex Flex


NativeWindow. WindowedApplication Application
AIR Flex Flex.
ActionScript
NativeWindow
Flash Player . NativeWindow,
.
HTML
HTML HTML, CSS JavaScript.
HTML, HTML DOM. HTML
NativeWindow. AIR nativeWindow
HTML, NativeWindow.
, NativeWindow, .
. JavaScript Window , moveTo() close(). , ,
.
Flex
Flex MXML.
Flex , MXML- .
ActionScript.
mx:WindowedApplication mx:Window Flex
Flex, NativeWindow .
NativeWindow WindowedApplication Window,
nativeWindow.

AIR . AIR
, initialWindow .
SWF-, AIR NativeWindow, SWF-
. HTML, AIR
HTML HTML.

23.11.2012.

955

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
API- :

flash.display

NativeWindow

NativeWindowInitOptions

NativeWindowDisplayState

NativeWindowResize

NativeWindowSystemChrome

NativeWindowType

NativeWindowBoundsEvent

NativeWindowDisplayStateEvent

flash.events


Adobe AIR 1.0

, . ,
, . .
, . ,
. ,
.
1 NativeWindow displayStateChanging.
2 , .
3 NativeWindow displayStateChange.

NativeWindow ,
.
. :
a move

.
b resize .

NativeWindow ,
, , .
,
Chrome , .
, ,
.
dispatchEvent() ,
.

23.11.2012.

956

ACTIONSCRIPT 3.0
AIR

, , API- .
c ActionScript 3.0 Adobe Flash Platform.

,
Flash Player 9 , Adobe AIR 1.0
:

type

systemChrome

transparent

owner

NativeWindowInitOptions,
. AIR . (
type, normal.)
.
: systemChrome
standard, transparent true type lightweight.


Adobe AIR 1.0
AIR Chrome
. ,
NativeWindowType, . AIR
:

Normal

. normal Chrome
Windows Mac OS X.

Utility

. utility Chrome
Windows Mac OS X.

Lightweight

lightweight Chrome Windows Mac


OS X. , lightweight ,
Alt+, Windows. lightweight
, .
lightweight type, systemChrome
none.

Chrome
Adobe AIR 1.0
Chrome ,
. Chrome : , ,
.

23.11.2012.

957

ACTIONSCRIPT 3.0
AIR

Chrome
systemChrome standard none. Chrome standard
,
. none, Chrome .
, NativeWindowSystemChrome,
Chrome .
Chrome .
, , .
Chrome transparent false,
type normal utility.
Chrome Flex
Flex WindowedApplication Window
, , Flex. Chrome Flex
systemChrome, , none. Flex 4
spark, mx , Chrome Flex.
, .
WindowedApplication spark
:
<?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/mx">
<fx:Style>
@namespace "library://ns.adobe.com/flex/spark";
WindowedApplication
{
skinClass:ClassReference("spark.skins.spark.SparkChromeWindowedApplicationSkin");
}
</fx:Style>
</s:WindowedApplication>

. Flex 4: AIR: Chrome

Chrome
Chrome
.
, .
Chrome mx:WindowedApplication mx:Window
showFlexChrome false. Flex
Chrome .


Adobe AIR 1.0
-
transparent true. transparent ,
, .

23.11.2012.

958

ACTIONSCRIPT 3.0
AIR

. , ,
, . ,
, .
, ,
. -
, .
. Linux
. , ,
,
. Mac OS X Windows .
, Chrome. , SWF PDF
HTML . .
SWF PDF HTML 1080.
NativeWindow.supportsTransparency ,
. , .
.
false . ,

.
, Mac Windows.
Linux ,
, -
.

MXML-
Adobe AIR 1.0
MXML- , transparent. (
.) ,
<mx:Style>, MXML .
, :
WindowedApplication
{
background-alpha:".8";
background-color:"0x448234";
}

HTML-
Adobe AIR 1.0
HTML, HTML, HTMLLoader
, - . ,
HTML, paintsDefaultBackground false.
HTMLLoader :
var htmlView:HTMLLoader = new HTMLLoader();
htmlView.paintsDefaultBackground = false;

23.11.2012.

959

ACTIONSCRIPT 3.0
AIR

JavaScript HTML:
window.htmlLoader.paintsDefaultBackground = false;

HTML , .
( ) .
PNG
.


.
,
, . -
. ,
.
,
. ,
,
.

NativeWindow.owner
(Christian Cantrell). AIR 2.6


Adobe AIR 1.0
,
Mac OS X, Windows Linux:

23.11.2012.

960

961

ACTIONSCRIPT 3.0
AIR

Mac OS X

Microsoft Windows

Type: normal
SystemChrome: standard
Transparent: false

Type: utility
SystemChrome: standard
Transparent: false

Type: Any
SystemChrome: none
Transparent: false

Type: Any
SystemChrome: none
Transparent: true

mxWindowedApplication
mx:Window
Type: Any
SystemChrome: none
Transparent: true

Ubuntu Compiz

23.11.2012.

Linux*

ACTIONSCRIPT 3.0
AIR

. Chrome AIR: Mac


OS X, - Mac OS X, Windows
Chrome.


Adobe AIR 1.0
AIR , .
NativeWindow.
HTML HTMLLoader createRootWindow(),
JavaScript window.open() HTML. NativeWindow,
HTMLLoader. HTMLLoader
HTML JavaScript . NativeWindow
JavaScript window.nativeWindow. ( ,
AIR.)
, ,
,
. ,
.
<visible>false</visible>
( , false).
NativeWindow . HTML
createRootWindow() HTMLLoader visible false.
activate() NativeWindow visible true,
.


Adobe AIR 1.0
.
.

systemChrome

standard

type

normal

transparent

false

owner

null

maximizable

true

minimizable

true

resizable

true

23.11.2012.

962

ACTIONSCRIPT 3.0
AIR

, AIR, .
AIR normal. (
, visible, width height, .)
HTML, ,
NativeWindowInitOptions. NativeWindowInitOptions,
, NativeWindow, HTMLLoader
createRootWindow().
NativeWindowInitOptions utility:
var options:NativeWindowInitOptions = new NativeWindowInitOptions();
options.systemChrome = NativeWindowSystemChrome.STANDARD;
options.type = NativeWindowType.UTILITY
options.transparent = false;
options.resizable = false;
options.maximizable = false;

systemChrome standard, transparent true


type lightweight.
. , JavaScript window.open(),
.
HTMLHost. .
JavaScript window.open() 1092.
Flex mx:Window
, MXML- , .
NativeWindow , open().
.


Adobe AIR 1.0
AIR , ,
, . SWF HTML-.
.
.

ActionScript
Adobe AIR 1.0
AIR Flex SDK ActionScript
Sprite ( Sprite).
.
AIR ,
. addedToStage,
nativeWindow Stage NativeWindow.
AIR,
ActionScript:

23.11.2012.

963

ACTIONSCRIPT 3.0
AIR

package {
import flash.display.NativeWindow;
import flash.display.Sprite;
import flash.events.Event;
public class MainClass extends Sprite
{
private var mainWindow:NativeWindow;
public function MainClass(){
this.addEventListener(Event.ADDED_TO_STAGE, initialize);
}
private function initialize(event:Event):void{
mainWindow = this.stage.nativeWindow;
//perform initialization...
mainWindow.activate(); //show the window
}
}
}

. nativeWindow
. .
Flash Professional ,
ActionScript. NativeWindow
nativeWindow . ,
( ):
import flash.display.NativeWindow;
var mainWindow:NativeWindow = this.stage.nativeWindow;
mainWindow.maximize();
mainWindow.activate();

Flex
Adobe AIR 1.0
AIR Flex mx:WindowedApplication
MXML-. ( mx:Application,
AIR .) WindowedApplication
.
AIR , Flex
WindowedApplication .
WindowedApplication applicationComplete.
nativeWindow WindowedApplication.
WindowedApplication x y:

23.11.2012.

964

ACTIONSCRIPT 3.0
AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
applicationComplete="placeWindow()">
<mx:Script>
<![CDATA[
private function placeWindow():void{
this.nativeWindow.x = 300;
this.nativeWindow.y = 300;
}
]]>
</mx:Script>
<mx:Label text="Hello World" horizontalCenter="0" verticalCenter="0"/>
</mx:WindowedApplication>

NativeWindow
Adobe AIR 1.0
NativeWindow NativeWindowInitOptions
NativeWindow:
var options:NativeWindowInitOptions = new NativeWindowInitOptions();
options.systemChrome = NativeWindowSystemChrome.STANDARD;
options.transparent = false;
var newWindow:NativeWindow = new NativeWindow(options);

, visible true
activate().
,
Flash.
scaleMode
noScale ( StageScaleMode.NO_SCALE).
Flash ,
.
: ,
. AIR ( ) ,
.
Flex HTML noScale.
. ,
, NativeWindow:
var maxOSSize:Point = NativeWindow.systemMaxSize;
var minOSSize:Point = NativeWindow.systemMinSize;

HTML
Adobe AIR 1.0
HTML JavaScript Window.open(),
createRootWindow() AIR HTMLLoader.

23.11.2012.

965

ACTIONSCRIPT 3.0
AIR

HTML
JavaScript Window.open().
, open() ,
. open()
Chrome URL-. :
newWindow = window.open("xmpl.html", "logWindow", "height=600, width=400, top=10, left=10");

. HTMLHost ActionScript, ,
JavaScript window.open(). . HTMLHost 1084.
, ,
HTMLLoader.createRootWindow(). ,
. , JavaScript lightweight
Chrome 300x400 :
var options = new air.NativeWindowInitOptions();
options.systemChrome = "none";
options.type = "lightweight";
var windowBounds = new air.Rectangle(200,250,300,400);
newHTMLLoader = air.HTMLLoader.createRootWindow(true, options, true, windowBounds);
newHTMLLoader.load(new air.URLRequest("xmpl.html"));

. , ,
, AIR, runtime, nativeWindow
htmlLoader.
, SWF, HTML,
. wmode ,
SWF, opaque transparent. wmode
window, SWF . PDF
wmode. ( AIR 1.5.2
SWF .)
, createRootWindow(), .
parent opener JavaScript Window null.
Window HTMLLoader,
createRootWindow(). newHTMLLoader.window
JavaScript Window .
. createRootWindow() JavaScript ActionScript.

mx:Window
Adobe AIR 1.0
mx:Window MXML- mx:Window
, Window.
mx:Window Window:

23.11.2012.

966

ACTIONSCRIPT 3.0
AIR

var newWindow:Window = new Window();


newWindow.systemChrome = NativeWindowSystemChrome.NONE;
newWindow.transparent = true;
newWindow.title = "New Window";
newWindow.width = 200;
newWindow.height = 200;
newWindow.open(true);


Adobe AIR 1.0
AIR . , MXML HTML
. SWF-
. Flex, Flash HTML
.
SWF HTML, JavaScript,
AIR. ,
, . .
URL- app:, API- AIR. ,
, API- AIR.
JavaScript
runtime, nativeWindow htmlLoader JavaScript Window.

,
. HTML
, ,
. . AIR
1159.
SWF-
SWF- Adobe Flash
flash.display.Loader:

23.11.2012.

967

ACTIONSCRIPT 3.0
AIR

package {
import
import
import
import

flash.display.Sprite;
flash.events.Event;
flash.net.URLRequest;
flash.display.Loader;

public class LoadedSWF extends Sprite


{
public function LoadedSWF(){
var loader:Loader = new Loader();
loader.load(new URLRequest("visual.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadFlash);
}
private function loadFlash(event:Event):void{
addChild(event.target.loader);
}
}
}

. SWF-, ActionScript 1 2, ,
, ,
. SWF- ,
SWF-,
.
.
HTML NativeWindow
HTML NativeWindow HTMLLoader
HTML HTMLLoader, ,
HTMLLoader, HTMLLoader.createRootWindow().
HTML 300 500
:
//newWindow is a NativeWindow instance
var htmlView:HTMLLoader = new HTMLLoader();
htmlView.width = 300;
htmlView.height = 500;
//set the stage so display objects are added to the top-left and not scaled
newWindow.stage.align = "TL";
newWindow.stage.scaleMode = "noScale";
newWindow.stage.addChild( htmlView );
//urlString is the URL of the HTML page to load
htmlView.load( new URLRequest(urlString) );

HTML Flex Flex HTML.


SWF HTML- (
transparent true), wmode ,
SWF-, opaque transparent. wmode
window, SWF .
PDF wmode.

23.11.2012.

968

ACTIONSCRIPT 3.0
AIR

, SWF PDF
HTMLLoader, alpha HTMLLoader , 1,0.
SWF HTML
HTML NativeWindow, Flash
HTML .
HTML addChild()
window.nativeWindow.stage. addChild()
.
HTML addChildAt()
window.nativeWindow.stage, index.
, HTML,
. HTML ,
paintsDefaultBackground HTMLlLoader false. ,
, , .
, .
Flash HTML .
, HTML,
. enterFrame.
<html>
<head>
<title>Bouncers</title>
<script src="AIRAliases.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
air.Shape = window.runtime.flash.display.Shape;
function Bouncer(radius, color){
this.radius = radius;
this.color = color;
//velocity
this.vX = -1.3;
this.vY = -1;
//Create a Shape object and draw a circle with its graphics property
this.shape = new air.Shape();
this.shape.graphics.lineStyle(1,0);
this.shape.graphics.beginFill(this.color,.9);
this.shape.graphics.drawCircle(0,0,this.radius);
this.shape.graphics.endFill();
//Set the starting position
this.shape.x = 100;
this.shape.y = 100;

//Moves the sprite by adding (vX,vY) to the current position


this.update = function(){
this.shape.x += this.vX;
this.shape.y += this.vY;
//Keep the sprite within the window

23.11.2012.

969

ACTIONSCRIPT 3.0
AIR

if( this.shape.x - this.radius < 0){


this.vX = -this.vX;
}
if( this.shape.y - this.radius < 0){
this.vY = -this.vY;
}
if( this.shape.x + this.radius > window.nativeWindow.stage.stageWidth){
this.vX = -this.vX;
}
if( this.shape.y + this.radius > window.nativeWindow.stage.stageHeight){
this.vY = -this.vY;
}
};
}
function init(){
//turn off the default HTML background
window.htmlLoader.paintsDefaultBackground = false;
var bottom = new Bouncer(60,0xff2233);
var top = new Bouncer(30,0x2441ff);
//listen for the enterFrame event
window.htmlLoader.addEventListener("enterFrame",function(evt){
bottom.update();
top.update();
});
//add the bouncing shapes to the window stage
window.nativeWindow.stage.addChildAt(bottom.shape,0);
window.nativeWindow.stage.addChild(top.shape);
}
</script>
<body onload="init();">
<h1>de Finibus Bonorum et Malorum</h1>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis
et quasi architecto beatae vitae dicta sunt explicabo.</p>
<p style="background-color:#FFFF00; color:#660000;">This paragraph has a background color.</p>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias
excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui
officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
</body>
</html>

,
JavaScript ActionScript AIR.
ActionScript, .  162
ActionScript 3.0.

:
Adobe AIR 1.0
:

23.11.2012.

970

ACTIONSCRIPT 3.0
AIR

public function createNativeWindow():void {


//create the init options
var options:NativeWindowInitOptions = new NativeWindowInitOptions();
options.transparent = false;
options.systemChrome = NativeWindowSystemChrome.STANDARD;
options.type = NativeWindowType.NORMAL;
//create the window
var newWindow:NativeWindow = new NativeWindow(options);
newWindow.title = "A title";
newWindow.width = 600;
newWindow.height = 400;
newWindow.stage.align = StageAlign.TOP_LEFT;
newWindow.stage.scaleMode = StageScaleMode.NO_SCALE;
//activate and show the new window
newWindow.activate();
}


Adobe AIR 1.0
NativeWindow ,
.
. Flex, ,
. NativeWindow
mx:WindowedApplication mx:Window.

NativeWindow
Adobe AIR 1.0
.
:

NativeWindow.
var win:NativeWindow = new NativeWindow(initOptions);

nativeWindow .
var win:NativeWindow = stage.nativeWindow;

stage display .
var win:NativeWindow = displayObject.stage.nativeWindow;

target NativeWindow, .
private function onNativeWindowEvent(event:NativeWindowBoundsEvent):void
{
var win:NativeWindow = event.target as NativeWindow;
}

23.11.2012.

971

ACTIONSCRIPT 3.0
AIR

nativeWindow HTML, .
var win:NativeWindow = htmlLoader.window.nativeWindow;

activeWindow openedWindows NativeApplication.


var nativeWin:NativeWindow = NativeApplication.nativeApplication.activeWindow;
var firstWindow:NativeWindow = NativeApplication.nativeApplication.openedWindows[0];
NativeApplication.nativeApplication.activeWindow

( null, AIR).
NativeApplication.nativeApplication.openedWindows AIR,

.
Flex mx:WindowedApplication mx:Window ,
MXML- stage, :
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
applicationComplete="init();">
<mx:Script>
<![CDATA[
import flash.display.NativeWindow;
public function init():void{
var appWindow:NativeWindow = this.stage.nativeWindow;
//set window properties
appWindow.visible = true;
}
]]>
</mx:Script>
</WindowedApplication

. WindowedApplication Window
Flex, stage null.
Flex Application, ,
NativeWindow ,
WindowedApplication Window,
creationComplete. NativeWindow
applicationComplete .

,
Adobe AIR 1.0
NativeWindow activate().
,
visible true.
. activate() activate.
visible true.
, .
, visible false.
, , , Mac OS X, Windows.

23.11.2012.

972

ACTIONSCRIPT 3.0
AIR

, . ,
, .
. Mac OS X ,
. visible false,
. .


Adobe AIR 1.0
AIR .
, .
.
, alwaysInFront
true. ,
, , alwaysInFront
false.
, ,
, AIR . ,
alwaysInFront true .
:

, , ,
. ,
, .

.
,
.
.

.
. AIR alwaysInFront.
, , .
, . ,
, orderToFront() alwaysInFront
true, : -
, - -.
,
,
, . , orderToFront()
, , ,
.
NativeWindow :

23.11.2012.

973

ACTIONSCRIPT 3.0
AIR

alwaysInFront

, , .
false. false
true ( ).
true false , ,
.
.
alwaysInFront , .

orderToFront()

orderInFrontOf()

orderToBack()

orderBehind()

activate()

( ).

. (visible false) ,
.
Linux
:

.
, alwaysInFront
true, , alwaysInFront
true.


Adobe AIR 1.0
, NativeWindow.close().
,
, . NativeWindow.close()
, , , . close
close . NativeWindow
,
IllegalOperationError. . ,
, closed . ,
NativeWindow.visible false.
Nativeapplication.autoExit true,
, .
, , -.
closing , , .
.

23.11.2012.

974

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
Chrome, , , ,
. ,
Chrome closing. -
preventDefault() , .
Chrome,
. , ,
.

dispatchEvent()
.
, ,
:
public function onCloseCommand(event:MouseEvent):void{
var closingEvent:Event = new Event(Event.CLOSING,true,true);
dispatchEvent(closing);
if(!closingEvent.isDefaultPrevented()){
win.close();
}
}

dispatchEvent() false,
preventDefault(). false ,
isDefaultPrevented() , ,
.

,
Adobe AIR 1.0
, NativeWindow maximize().
myWindow.maximize();

, NativeWindow minimize().
myWindow.minimize();

(. . ),
NativeWindow restore().
myWindow.restore();

, ,
-. ,
.
. AIR
Mac OS X. , ,
, , AIR ,
, , .

23.11.2012.

975

ACTIONSCRIPT 3.0
AIR

Linux
:

.
,
.
, .
.

maximizable minimizable.
. Linux .
, ,
. NativeWindow
displayStateChange . -
,
displayStateChange. . 982.

: , ,

Adobe AIR 1.0


MXML- maximize(), minimize(), restore()
close() :

23.11.2012.

976

ACTIONSCRIPT 3.0
AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
public function minimizeWindow():void
{
this.stage.nativeWindow.minimize();
}
public function maximizeWindow():void
{
this.stage.nativeWindow.maximize();
}
public function restoreWindow():void
{
this.stage.nativeWindow.restore();
}
public function closeWindow():void
{
this.stage.nativeWindow.close();
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button
<mx:Button
<mx:Button
<mx:Button
</mx:VBox>

label="Minimize" click="minimizeWindow()"/>
label="Restore" click="restoreWindow()"/>
label="Maximize" click="maximizeWindow()"/>
label="Close" click="closeWindow()"/>

</mx:WindowedApplication>

ActionScript Flash ,
NativeWindow minimize(), maximize(), restore() close():

23.11.2012.

977

ACTIONSCRIPT 3.0
AIR

package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
public class MinimizeExample extends Sprite
{
public function MinimizeExample():void
{
var minTextBtn:TextField = new TextField();
minTextBtn.x = 10;
minTextBtn.y = 10;
minTextBtn.text = "Minimize";
minTextBtn.background = true;
minTextBtn.border = true;
minTextBtn.selectable = false;
addChild(minTextBtn);
minTextBtn.addEventListener(MouseEvent.CLICK, onMinimize);
var maxTextBtn:TextField = new TextField();
maxTextBtn.x = 120;
maxTextBtn.y = 10;
maxTextBtn.text = "Maximize";
maxTextBtn.background = true;
maxTextBtn.border = true;
maxTextBtn.selectable = false;
addChild(maxTextBtn);
maxTextBtn.addEventListener(MouseEvent.CLICK, onMaximize);
var restoreTextBtn:TextField = new TextField();
restoreTextBtn.x = 230;
restoreTextBtn.y = 10;
restoreTextBtn.text = "Restore";
restoreTextBtn.background = true;
restoreTextBtn.border = true;
restoreTextBtn.selectable = false;
addChild(restoreTextBtn);
restoreTextBtn.addEventListener(MouseEvent.CLICK, onRestore);
var closeTextBtn:TextField = new TextField();
closeTextBtn.x = 340;
closeTextBtn.y = 10;
closeTextBtn.text = "Close Window";
closeTextBtn.background = true;
closeTextBtn.border = true;
closeTextBtn.selectable = false;
addChild(closeTextBtn);

23.11.2012.

978

ACTIONSCRIPT 3.0
AIR

closeTextBtn.addEventListener(MouseEvent.CLICK, onCloseWindow);
}
function onMinimize(event:MouseEvent):void
{
this.stage.nativeWindow.minimize();
}
function onMaximize(event:MouseEvent):void
{
this.stage.nativeWindow.maximize();
}
function onRestore(event:MouseEvent):void
{
this.stage.nativeWindow.restore();
}
function onCloseWindow(event:MouseEvent):void
{
this.stage.nativeWindow.close();
}
}
}


Adobe AIR 1.0
Chrome, Chrome
. Chrome,
,
.
.
NativeWindow. , , .
NativeWindow 971.

, startResize()
NativeWindow. mouseDown,
mouseUp.
startResize() , ,
.
, : width, height
bounds. .
, , . Linux
.
, .
. , Y
, ,
Y.

23.11.2012.

979

ACTIONSCRIPT 3.0
AIR

. Linux .
, ,
. NativeWindow resize
. - ,
, ,
resize. . 982.

. ,
, , -,
. ,
scaleMode StageScaleMode.NO_SCALE. ,
scaleX scaleY .

, , NativeWindow startMove().
startResize(), startMove() mouseDown
mouseUp.
startResize() startMove() . c ActionScript 3.0
Adobe Flash Platform.
, x, y bounds
. .
. Linux .
, ,
. NativeWindow move
. - ,
move. .
982.

:
Adobe AIR 1.0
:

23.11.2012.

980

ACTIONSCRIPT 3.0
AIR

package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.NativeWindowResize;
public class NativeWindowResizeExample extends Sprite
{
public function NativeWindowResizeExample():void
{
// Fills a background area.
this.graphics.beginFill(0xFFFFFF);
this.graphics.drawRect(0, 0, 400, 300);
this.graphics.endFill();
// Creates a square area where a mouse down will start the resize.
var resizeHandle:Sprite =
createSprite(0xCCCCCC, 20, this.width - 20, this.height - 20);
resizeHandle.addEventListener(MouseEvent.MOUSE_DOWN, onStartResize);
// Creates a square area where a mouse down will start the move.
var moveHandle:Sprite = createSprite(0xCCCCCC, 20, this.width - 20, 0);
moveHandle.addEventListener(MouseEvent.MOUSE_DOWN, onStartMove);
}
public function createSprite(color:int, size:int, x:int, y:int):Sprite
{
var s:Sprite = new Sprite();
s.graphics.beginFill(color);
s.graphics.drawRect(0, 0, size, size);
s.graphics.endFill();
s.x = x;
s.y = y;
this.addChild(s);
return s;
}
public function onStartResize(event:MouseEvent):void
{
this.stage.nativeWindow.startResize(NativeWindowResize.BOTTOM_RIGHT);
}
public function onStartMove(event:MouseEvent):void
{
this.stage.nativeWindow.startMove();
}
}
}

23.11.2012.

981

ACTIONSCRIPT 3.0
AIR


Adobe AIR 1.0
, ,
. , closing
:
myWindow.addEventListener(Event.CLOSING, onClosingEvent);

target , .
.
( ), ,
. ,
closing. ,
close.
, , closing, ,
Chrome. close() , , closing
close.
closing dispatchEvent() .
, Event, :

activate

deactivate

, .

closing

.
Chrome ( Mac OS X) Quit.

close

, NativeWindowBoundsEvent, :

moving


, .

move

resizing

resize

NativeWindowBoundsEvent beforeBounds afterBounds


.
, NativeWindowDisplayStateEvent, :

23.11.2012.

982

ACTIONSCRIPT 3.0
AIR

displayStateChanging

displayStateChange

NativeWindowDisplayStateEvent beforeDisplayState
afterDisplayState
.
Linux ,
,
. ( ,
.)


Adobe AIR 1.0
displayState
StageDisplayState.FULL_SCREEN_INTERACTIVE ,
. ( SWF, ,
.) Escape.
. Linux ,
( Chrome ).
, Flex AIR,
:

23.11.2012.

983

ACTIONSCRIPT 3.0
AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
applicationComplete="init()" backgroundColor="0x003030" focusRect="false">
<mx:Script>
<![CDATA[
private function init():void
{
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
focusManager.setFocus(terminal);
terminal.text = "Welcome to the dumb terminal app. Press the ESC key to
exit..\n";
terminal.selectionBeginIndex = terminal.text.length;
terminal.selectionEndIndex = terminal.text.length;
}
]]>
</mx:Script>
<mx:TextArea
id="terminal"
height="100%" width="100%"
scroll="false"
backgroundColor="0x003030"
color="0xCCFF00"
fontFamily="Lucida Console"
fontSize="44"/>
</mx:WindowedApplication>

ActionScript Flash :

23.11.2012.

984

ACTIONSCRIPT 3.0
AIR

import
import
import
import

flash.display.Sprite;
flash.display.StageDisplayState;
flash.text.TextField;
flash.text.TextFormat;

public class FullScreenTerminalExample extends Sprite


{
public function FullScreenTerminalExample():void
{
var terminal:TextField = new TextField();
terminal.multiline = true;
terminal.wordWrap = true;
terminal.selectable = true;
terminal.background = true;
terminal.backgroundColor = 0x00333333;
this.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
addChild(terminal);
terminal.width = 550;
terminal.height = 400;
terminal.text = "Welcome to the dumb terminal application. Press the ESC key to
exit.\n_";
var tf:TextFormat = new TextFormat();
tf.font = "Courier New";
tf.color = 0x00CCFF00;
tf.size = 12;
terminal.setTextFormat(tf);
terminal.setSelection(terminal.text.length - 1, terminal.text.length);
}
}

23.11.2012.

985

986

53. AIR
Adobe AIR 1.0
Screen Adobe AIR ,
.


flash.display.Screen

AIR
Adobe AIR 1.0

(Flex)
) (Flash)
API- , Screen,
.
,
, . AIR
Screen , .
, .
, ,
.
.
. ,
, . ,
, .

23.11.2012.

987

ACTIONSCRIPT 3.0
AIR




.
(1) (0,0). 2
1 . ,
.

, , API- .
c ActionScript 3.0 Flash Platform.


Adobe AIR 1.0
:

Screen.screens

Screen, .
.

Screen.mainScreen

Screen . Mac OS X
, . Windows
.

Screen.getScreensForRectangle() Screen, ,
. , ,
, .
, . ,
.

, Screen.
.

23.11.2012.

ACTIONSCRIPT 3.0
AIR

API-
. ,
screens ( ).
,
. , ,
Screen.getScreensForRectangle(), .
package {
import
import
import
import
import
import

flash.display.Sprite;
flash.display.Screen;
flash.events.KeyboardEvent;
flash.ui.Keyboard;
flash.display.StageAlign;
flash.display.StageScaleMode;

public class ScreenExample extends Sprite


{
public function ScreenExample()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKey);
}
private function onKey(event:KeyboardEvent):void{
if(Screen.screens.length > 1){
switch(event.keyCode){
case Keyboard.LEFT :
moveLeft();
break;
case Keyboard.RIGHT :
moveRight();
break;
case Keyboard.UP :
moveUp();
break;
case Keyboard.DOWN :
moveDown();
break;
}
}
}
private function moveLeft():void{
var currentScreen = getCurrentScreen();
var left:Array = Screen.screens;
left.sort(sortHorizontal);
for(var i:int = 0; i < left.length - 1; i++){
if(left[i].bounds.left < stage.nativeWindow.bounds.left){
stage.nativeWindow.x +=
left[i].bounds.left - currentScreen.bounds.left;
stage.nativeWindow.y += left[i].bounds.top - currentScreen.bounds.top;
}
}
}

23.11.2012.

988

ACTIONSCRIPT 3.0
AIR

private function moveRight():void{


var currentScreen:Screen = getCurrentScreen();
var left:Array = Screen.screens;
left.sort(sortHorizontal);
for(var i:int = left.length - 1; i > 0; i--){
if(left[i].bounds.left > stage.nativeWindow.bounds.left){
stage.nativeWindow.x +=
left[i].bounds.left - currentScreen.bounds.left;
stage.nativeWindow.y += left[i].bounds.top - currentScreen.bounds.top;
}
}
}
private function moveUp():void{
var currentScreen:Screen = getCurrentScreen();
var top:Array = Screen.screens;
top.sort(sortVertical);
for(var i:int = 0; i < top.length - 1; i++){
if(top[i].bounds.top < stage.nativeWindow.bounds.top){
stage.nativeWindow.x += top[i].bounds.left - currentScreen.bounds.left;
stage.nativeWindow.y += top[i].bounds.top - currentScreen.bounds.top;
break;
}
}
}
private function moveDown():void{
var currentScreen:Screen = getCurrentScreen();
var top:Array = Screen.screens;
top.sort(sortVertical);
for(var i:int = top.length - 1; i > 0; i--){
if(top[i].bounds.top > stage.nativeWindow.bounds.top){
stage.nativeWindow.x += top[i].bounds.left - currentScreen.bounds.left;
stage.nativeWindow.y += top[i].bounds.top - currentScreen.bounds.top;
break;
}
}
}
private function sortHorizontal(a:Screen,b:Screen):int{
if (a.bounds.left > b.bounds.left){
return 1;
} else if (a.bounds.left < b.bounds.left){

23.11.2012.

989

ACTIONSCRIPT 3.0
AIR

return -1;
} else {return 0;}
}
private function sortVertical(a:Screen,b:Screen):int{
if (a.bounds.top > b.bounds.top){
return 1;
} else if (a.bounds.top < b.bounds.top){
return -1;
} else {return 0;}
}
private function getCurrentScreen():Screen{
var current:Screen;
var screens:Array = Screen.getScreensForRectangle(stage.nativeWindow.bounds);
(screens.length > 0) ? current = screens[0] : current = Screen.mainScreen;
return current;
}
}
}

23.11.2012.

990

991

54.
Flash Player 9 , Adobe AIR 1.0
Flash ( Adobe Flash Player Adobe AIR)
, .
, , ,
, . ,
flash.printing.PrintJob ,
.
flash.printing.PrintJob
,
Flash .


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 PrintJob ,
. ,
:
. , . ,
.
, .
.
, ,
ActionScript. , ,
. PrintJob ,
.

, .
, ,

, , .
.

() ().
, .

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
PrintJob.
Flash Player AIR, :

new PrintJob(): ;

PrintJob.start(): ,

, , .

PrintJob.addPage(): , Sprite (

), ( ).
addPage() ;

PrintJob.send(): .

( package, import
class ).
package
{
import flash.printing.PrintJob;
import flash.display.Sprite;
public class BasicPrintExample extends Sprite
{
var myPrintJob:PrintJob = new PrintJob();
var mySprite:Sprite = new Sprite();
public function BasicPrintExample()
{
myPrintJob.start();
myPrintJob.addPage(mySprite);
myPrintJob.send();
}
}
}

.
. ,
, . 993.
PrintJob, PrintJob null (,
myPrintJob = null).

23.11.2012.

992

ACTIONSCRIPT 3.0

Flash
Flash Player 9 , Adobe AIR 1.0
Flash ,
, Flash,
. Flash ,
,
, .
, ,
, . Flash
, ,
.
, .


Flash Player 9 , Adobe AIR 1.0
, PrintJob.start() true,
addPage() send(), , . ,
, if.
if (myPrintJob.start())
{
// addPage() and send() statements here
}

PrintJob.start() true, (
Flash, Flash Player AIR).
addPage() send().
, , Flash
PrintJob.addPage(),
. PrintJob.addPage() ,
.
addPage() try..catch, . [params]
, , .
if (myPrintJob.start())
{
try
{
myPrintJob.addPage([params]);
}
catch (error:Error)
{
// Handle error,
}
myPrintJob.send();
}

23.11.2012.

993

ACTIONSCRIPT 3.0

PrintJob.addPage()
(, ).
, catch , (
Flash) , .

PrintJob.send().
Flash (,
),
(,
). , ,
if..else, .
if (myPrintJob.start())
{
try
{
myPrintJob.addPage([params]);
}
catch (error:Error)
{
// Handle error.
}
myPrintJob.send();
}
else
{
myAlert.text = "Print job canceled";
}

. : ,
1002.


Flash Player 9 , Adobe AIR 1.0
PrintJob.start()
true, , .
(pageHeight pageWidth),
. Flash, .
, ,
. . ,
996.

23.11.2012.

994

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
,
.
, .
-
, . ,
PostScript, .
PrintJobOptions
PrintJob.addPage().
Flash Player AIR, AIR 2, printAsBitmap
PrintJobOptions true, :
var options:PrintJobOptions = new PrintJobOptions();
options.printAsBitmap = true;
myPrintJob.addPage(mySprite, null, options);

, ,
.
AIR 2 printMethod .
, PrintMethod:

PrintMethod.AUTO:

. , ,
. , - ,
.

PrintMethod.BITMAP:

PrintMethod.VECTOR:


Flash Player 9 , Adobe AIR 1.0
ActionScript 3.0 PrintJob (
ActionScript).
,
PrintJob.addPage() PrintJob.send(),
. , PrintJob.send(),
.
ActionScript 3.0 , 15 .
15 .
, (15 ) :

PrintJob.start() PrintJob.addPage();
PrintJob.addPage() PrintJob.addPage();
PrintJob.addPage() PrintJob.send().

23.11.2012.

995

ACTIONSCRIPT 3.0

15 , PrintJob.start()
PrintJob false, PrintJob.addPage()
PrintJob Flash Player AIR .

Flash Player 9 , Adobe AIR 1.0


992
,
. ,
.
Flash ,
: , . ,

. .
, ,

.


Flash Player 9 , Adobe AIR 1.0
PrintJob.addPage() , .
, printArea, Rectangle.
.

Rectangle ,
addPage(), .
private var rect1:Rectangle = new Rectangle(0, 0, 400, 200);
myPrintJob.addPage(sheet, rect1);

Rectangle , , .
myPrintJob.addPage(sheet, new Rectangle(0, 0, 100, 100));

addPage(),
, null, .
myPrintJob.addPage(sheet, null, options);

23.11.2012.

996

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
.
. (1/72 ),
.
Sprite.
Sprite, 72 , 1 ,
.

( 1/20 ):

1 = 1/72 = 20
1 = 72 = 1440
1 = 567
printArea , .

Flash Player 9 , Adobe AIR 1.0


Sprite, (.
193),
PrintJob.addPage(), .
Sprite printArea. , 50 50
, 2500 . Sprite , 2500
, Sprite .
. : ,
1002.


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR , ActionScript

, .
if (myPrintJob.orientation == PrintJobOrientation.LANDSCAPE)
{
mySprite.rotation = 90;
}

. ,
PrintJobOrientation. PrintJobOrientation ,
.
:
import flash.printing.PrintJobOrientation;

23.11.2012.

997

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
, ,
, if.
:
if (mySprite.height > myPrintJob.pageHeight)
{
mySprite.scaleY = .75;
}

, , , .
margin_height = (myPrintJob.paperHeight - myPrintJob.pageHeight) / 2;
margin_width = (myPrintJob.paperWidth - myPrintJob.pageWidth) / 2;


Adobe AIR 2
Adobe AIR 2, PrintJob
: PrintUIOptions, PaperSize PrintMethod.
.
:

:
.
, , .

: , ,
.

: ,
.

:
.

:
PrintJob.
.

new PrintJob(): PrintJob ( ).


PrintJob, selectPaperSize().
PrintJob.showPageSetupDialog(): ()

23.11.2012.

998

ACTIONSCRIPT 3.0

PrintJob.start() PrintJob.start2(): start(), start2()

. start2()
, .

PrintJob.addPage(): . .

PrintJob.send() PrintJob.terminate():

. .
PrintJob , - .
, ,
PrintJob.


showPageSetupDialog() ,
.
supportsPageSetupDialog . .
import flash.printing.PrintJob;
var myPrintJob:PrintJob = new PrintJob();
//check for static property supportsPageSetupDialog of PrintJob class
if (PrintJob.supportsPageSetupDialog) {
myPrintJob.showPageSetupDialog();
}

PrintUIOptions
. ,
. .
import flash.printing.PrintJob;
var myPrintJob:PrintJob = new PrintJob();
if (PrintJob.supportsPageSetupDialog) {
var uiOpt:PrintUIOptions = new PrintUIOptions();
uiOpt.minPage = 1;
uiOpt.maxPage = 3;
myPrintJob.showPageSetupDialog(uiOpt);
}


PrintJob .
addPage()
. , printer, ,
. start() start2().
selectPaperSize()
.
.
, PaperSize.
.

23.11.2012.

999

ACTIONSCRIPT 3.0

import flash.printing.PrintJob;
import flash.printing.PaperSize;
var myPrintJob:PrintJob = new PrintJob();
myPrintJob.selectPaperSize(PaperSize.ENV_10);

printer .
. printer null,
. ,
printers. Vector, String
. printer
String, . printer
. start() start2()
. .
import flash.printing.PrintJob;
var myPrintJob:PrintJob = new PrintJob();
myPrintJob.printer = "HP_LaserJet_1";
myPrintJob.start();

copies
. firstPage lastPage .
orientation .
. .
import flash.printing.PrintJob;
import flash.printing.PrintJobOrientation;
var myPrintJob:PrintJob = new PrintJob();
myPrintJob.copies = 3;
myPrintJob.firstPage = 1;
myPrintJob.lastPage = 3;
myPrintJob.orientation = PrintJobOrientation.LANDSCAPE;

, PrintJob,
.

paperArea: , .

printableArea: , .

maxPixelsPerInch: , .

isColor: ( true,
).

. : 1004.

:
Flash Player 9 , Adobe AIR 1.0
,
( sheet1 sheet2) PrintJob.addPage().
:

23.11.2012.

1000

ACTIONSCRIPT 3.0

package
{
import
import
import
import
import
import
import

flash.display.MovieClip;
flash.printing.PrintJob;
flash.printing.PrintJobOrientation;
flash.display.Stage;
flash.display.Sprite;
flash.text.TextField;
flash.geom.Rectangle;

public class PrintMultiplePages extends MovieClip


{
private var sheet1:Sprite;
private var sheet2:Sprite;
public function PrintMultiplePages():void
{
init();
printPages();
}
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 printPages():void
{
var pj:PrintJob = new PrintJob();

23.11.2012.

1001

ACTIONSCRIPT 3.0

var pagesToPrint:uint = 0;
if (pj.start())
{
if (pj.orientation == PrintJobOrientation.LANDSCAPE)
{
throw new Error("Page is not set to 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 (error:Error)
{
// Respond to error.
}
try
{
pj.addPage(sheet2);
pagesToPrint++;
}
catch (error:Error)
{
// Respond to error.
}
if (pagesToPrint > 0)
{
pj.send();
}
}
}
}
}

: ,

Flash Player 9 , Adobe AIR 1.0
( )
, , .
(, scaleX scaleY), ,
, ,
. , , , .

23.11.2012.

1002

ACTIONSCRIPT 3.0

txt ( ),
.
.
, Flash ,
, .
package
{
import
import
import
import
import

flash.printing.PrintJob;
flash.display.Sprite;
flash.text.TextField;
flash.display.Stage;
flash.geom.Rectangle;

public class PrintScaleExample extends Sprite


{
private var bg:Sprite;
private var txt:TextField;
public function PrintScaleExample():void
{
init();
draw();
printPage();
}
private function printPage():void
{
var pj:PrintJob = new PrintJob();
txt.scaleX = 3;
txt.scaleY = 2;
if (pj.start())
{
trace(">> pj.orientation: " + pj.orientation);
trace(">> pj.pageWidth: " + pj.pageWidth);
trace(">> pj.pageHeight: " + pj.pageHeight);
trace(">> pj.paperWidth: " + pj.paperWidth);
trace(">> pj.paperHeight: " + pj.paperHeight);
try
{
pj.addPage(this, new Rectangle(0, 0, 100, 100));
}
catch (error:Error)
{
// Do nothing.
}
pj.send();
}
else
{
txt.text
}
// Reset the
txt.scaleX =
txt.scaleY =

= "Print job canceled";


txt scale properties.
1;
1;

23.11.2012.

1003

ACTIONSCRIPT 3.0

}
private function init():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 draw():void
{
addChild(bg);
addChild(txt);
txt.x = 50;
txt.y = 50;
}
}
}

Adobe AIR 2
PrintJob, ,
(legal) ().
.
package
{
import
import
import
import
import
import
import
import

flash.printing.PrintJob;
flash.printing.PrintJobOrientation;
flash.printing.PaperSize;
flash.printing.PrintUIOptions;
flash.display.Sprite;
flash.text.TextField;
flash.display.Stage;
flash.geom.Rectangle;

public class PrintAdvancedExample extends Sprite


{
private var bg:Sprite = new Sprite();
private var txt:TextField = new TextField();
private var pj:PrintJob = new PrintJob();
private var uiOpt:PrintUIOptions = new PrintUIOptions();
public function PrintAdvancedExample():void
{

23.11.2012.

1004

ACTIONSCRIPT 3.0

initPrintJob();
initContent();
draw();
printPage();
}
private function printPage():void
{
//test for dialog support as a static property of PrintJob class
if (PrintJob.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.graphics.beginFill(0x00FF00);
bg.graphics.drawRect(0, 0, 100, 200);
bg.graphics.endFill();
txt.border = true;

23.11.2012.

1005

ACTIONSCRIPT 3.0

txt.text = "Hello World";


}
private function initPrintJob():void
{
pj.selectPaperSize(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;
}
}
}

23.11.2012.

1006

1007

55. Geolocation
, API-
.
, .
, , ,
.
Geolocation update .
update GeolocationEvent.


flash.sensors.Geolocation
flash.events.GeolocationEvent


, Geolocation
update. update Geolocation.
:

altitude: .

heading: ( ) .

horizontalAccuracy: .

latitude: .

longitude: .

speed: .

timestamp: , .

verticalAccuracy: .

timestamp int. Number.


:

23.11.2012.

ACTIONSCRIPT 3.0
Geolocation

var geo:Geolocation;
if (Geolocation.isSupported)
{
geo = new Geolocation();
geo.addEventListener(GeolocationEvent.UPDATE, updateHandler);
}
else
{
geoTextField.text = "Geolocation feature not supported";
}
function updateHandler(event:GeolocationEvent):void
{
geoTextField.text = "latitude: " + event.latitude.toString() + "\n"
+ "longitude: " + event.longitude.toString() + "\n"
+ "altitude: " + event.altitude.toString()
+ "speed: " + event.speed.toString()
+ "heading: " + event.heading.toString()
+ "horizontal accuracy: " + event.horizontalAccuracy.toString()
+ "vertical accuracy: " + event.verticalAccuracy.toString()
}

, geoTextField
.
,
setRequestedUpdateInterval() Geolocation. interval,
:
var geo:Geolocation = new Geolocation();
geo.setRequestedUpdateInterval(10000);


. .
setRequestedUpdateInterval()
, .
. ,
iPhone , .
.
Geolocation status,
. , muted Geolocation true,
. Geolocation status
muted.
:

23.11.2012.

1008

ACTIONSCRIPT 3.0
Geolocation

package
{
import
import
import
import
import
import
import
import
import

flash.display.Sprite;
flash.display.StageAlign;
flash.display.StageScaleMode;
flash.events.GeolocationEvent;
flash.events.MouseEvent;
flash.events.StatusEvent;
flash.sensors.Geolocation;
flash.text.TextField;
flash.text.TextFormat;

public class GeolocationTest extends Sprite


{
private var geo:Geolocation;
private var log:TextField;
public function GeolocationTest()
{
super();
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
setUpTextField();
if (Geolocation.isSupported)
{
geo = new Geolocation();
if (!geo.muted)
{
geo.addEventListener(GeolocationEvent.UPDATE, geoUpdateHandler);
}
geo.addEventListener(StatusEvent.STATUS, geoStatusHandler);
}
else
{
log.text = "Geolocation not supported";
}
}
public function geoUpdateHandler(event:GeolocationEvent):void
{
log.text = "latitude : " + event.latitude.toString() + "\n";
log.appendText("longitude : " + event.longitude.toString() + "\n");
}
public function geoStatusHandler(event:StatusEvent):void
{
if (geo.muted)
geo.removeEventListener(GeolocationEvent.UPDATE, geoUpdateHandler);
else
geo.addEventListener(GeolocationEvent.UPDATE, geoStatusHandler);
}
private function setUpTextField():void

23.11.2012.

1009

ACTIONSCRIPT 3.0
Geolocation

{
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;
log.addEventListener(MouseEvent.CLICK, clearLog);
addChild(log);
}
private function clearLog(event:MouseEvent):void
{
log.text = "";
}
}
}

. iPhone , GPS,
update . Geolocation
update. update
.


Geolocation.isSupported,
:
if (Geolocation.isSupported)
{
// Set up geolocation event listeners and code.
}

ActionScript
iPhone Flash Lite 4. Geolocation.isSupported
true, .
iPhone GPS .
(, ) .
iPhone GPS Geolocation
update.

23.11.2012.

1010

1011

56.

Flash Player 10.1 , Adobe AIR 2.0


flash.globalization ,
.


flash.globalization
1029
(Charles Bihis): Flex/AIR?


.
-,
.
.
-

. ,
, , (
), -, ,
, .
G11n ( . Globalization, G , 11 , n
). .
,
, ( , ,
) .
: .

I18n. .
,

. L10n.
.
,

.
, Adobe InDesign, Adobe Acrobat.

23.11.2012.

ACTIONSCRIPT 3.0

, .
, .
, (, ),
, .
.
,
, ( ).
( ).
, , ,
.
, ,

. ,
. .
,
. ,
, .

flash.globalization
Flash Player 10.1 , Adobe AIR 2.0
flash.globalization ,
.
.
.

Collator .
CurrencyFormatter
.

DateTimeFormatter .
LocaleID
NumberFormatter .
StringTools
.

flash.globalization
flash.globalization .
flash.globalization
. , , Flex
ResourceManager ResourceBundle. .
Flex.
Adobe AIR 1.1 , AIR,
AIR 1030.

23.11.2012.

1012

ACTIONSCRIPT 3.0



flash.globalization:
1 .
2 (Collator, CurrencyFormatter, DateTimeFormatter,

NumberFormatter StringTools).
3 lastOperationStatus.
4 , .

,
. , :

;
FTE ;
.


flash.globalization ,
,
.

.
lastOperationStatus, .
var nf:NumberFormatter = new NumberFormatter("de-DE");
if(nf.lastOperationStatus != LastOperationStatus.NO_ERROR)
{
if(nf.lastOperationStatus == LastOperationStatus.USING_FALLBACK_WARNING)
{
// perform fallback logic here, if needed
trace("Warning - Fallback locale ID: " + nf.actualLocaleIDName);
}
else
{
// perform error handling logic here, if needed
trace("Error: " + nf.lastOperationStatus);
}
}

,
.
. ,
.

23.11.2012.

1013

ACTIONSCRIPT 3.0


Flash Player 10.1 , Adobe AIR 2.0
.
. LocaleID
, .
LocaleID :
var locale:LocaleID = new LocaleID("es-MX");

LocaleID .
getKeysAndValues(), getLanguage(), getRegion(), getScript(), getVariant(),
isRightToLeft() name.
, ,
, .
, ,
. ,
.
Flash Player .

. :
var loc:LocaleID = new LocaleID("es");
trace(loc.getLanguage()); // es
trace(loc.getScript()); // Latn
trace(loc.getRegion()); // ES

LocaleID() ,
es .


, :

. ,
.


.
, .
, . ,

.


.
, .

23.11.2012.

1014

ACTIONSCRIPT 3.0

:
1 ,

, cookie. (
. flash.globalization .)
2 , ,

. LocaleID.determinePreferredLocales()
,
.
3 ,


fl.lang.Locale
, .
, , , . .
, Flash Professional.

flash.system.Capabilities.language.
ISO 639-1, , .
AIR 1.5 flash.system.Capabilities.languages.
. ,
Capabilities.language.


Flash Player 10.1 , Adobe AIR 2.0
. ,
123456,78 :

en-US (, )

-123,456.78

de-DE (, )

-123.456,78

fr-FR (, )

-123 456,78

de-CH (, )

-123'456.78

en-IN (, )

-1,23,456.78

123,456.78-

, :

. .
, .
, , .

23.11.2012.

1015

ACTIONSCRIPT 3.0

.
, .

.
. , 19
-19, 19- (19).

.
. , 0,17 , , .17, 0.17
0.170.

. , , ,
. flash.globalization ,
0-9.
NumberFormatter .

NumberFormatter
NumberFormatter ( int, uint Number)
, .

, :
var nf:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT);
trace(nf.formatNumber(-123456.789))


. , fr-FR,
:
-123.456,789

, . :
var nf:NumberFormatter = new NumberFormatter("de-CH");
trace(nf.formatNumber(-123456.789));

:
-123'456.789
formatNumber() Number. NumberFormatter
formatInt(), int , formatUint(),
uint.
NumberFormatter,
:
var nf:NumberFormatter = new NumberFormatter("de-CH");
nf.negativeNumberFormat = 0;
nf.fractionalDigits = 5;
nf.trailingZeros = true;
nf.decimalSeparator = ",";
nf.useGrouping = false;
trace(nf.formatNumber(-123456.789)); //(123456.78900)

23.11.2012.

1016

ACTIONSCRIPT 3.0

NumberFormatter, :

( );
, 5;
;
;
.
.
. ,
,
, , ,
, Windows.


NumberFormatter ,
. NumberFormatter.parseNumber()
. :
var nf:NumberFormatter = new NumberFormatter( "en-US" );
var inputNumberString:String = "-1,234,567.890"
var parsedNumber:Number = nf.parseNumber(inputNumberString);
trace("Value:" + parsedNumber); // -1234567.89
trace("Status:" + nf.lastOperationStatus); // noError

parseNumber() , ,
. ,
:
var nf:NumberFormatter = new NumberFormatter( "en-US" );
var inputNumberString:String = "The value is 1,234,567.890"
var parsedNumber:Number = nf.parseNumber(inputNumberString);
trace("Value:" + parsedNumber); // NaN
trace("Status:" + nf.lastOperationStatus); // parseError

, ,
NumberFormatter.parse():
var nf:NumberFormatter = new NumberFormatter( "en-US" );
var inputNumberString:String = "The value is 123,456,7.890";
var parseResult:NumberParseResult = nf.parse(inputNumberString);
trace("Value:" + parseResult.value); // 1234567.89
trace("startIndex: " + parseResult.startIndex); // 14
trace("Status:" + nf.lastOperationStatus); // noError

parse() NumberParseResult,
. startIndex .
startIndex endIndex .

23.11.2012.

1017

ACTIONSCRIPT 3.0


Flash Player 10.1 , Adobe AIR 2.0
, . ,
($123456,78) :

en-US (, )

$123,456.78

de-DE (, )

123.456,78 $

en-IN (, )

$ 1,23,456.78

, ,
:

ISO . ISO 4217 , USD EUR.


. , $ .
.
.

.
.

CurrencyFormatter
CurrencyFormatter ,
, .
CurrencyFormatter ,
.
CurrencyFormatter,
:
var cf:CurrencyFormatter = new CurrencyFormatter( "de-DE" );
trace(cf.format(1234567.89)); // 1.234.567,89 EUR

.
, CurrencyFormatter .
. , ,
, .
, ,
.
CurrencyFormatter.setCurrency() ,
.
:
var cf:CurrencyFormatter = new CurrencyFormatter( "fr-CA" );
cf.setCurrency("EUR", "");
trace(cf.format(1234567.89)); // 1.234.567,89 EUR

23.11.2012.

1018

ACTIONSCRIPT 3.0

setCurrency()
. :
cf.setCurrency("USD","US$");

format() ISO 4217 .


ISO 4217 .
, ISO.
CurrencyFormatter ,
: , , ISO,
USD EUR. ,
$200. CAD 200.
formattingWithCurrencySymbolIsSafe() ,
.
en-US.
ISO .
var cf:CurrencyFormatter = new CurrencyFormatter( "en-CA");
if (cf.formattingWithCurrencySymbolIsSafe("USD"))
{
trace(cf.format(1234567.89, true)); // $1,234,567.89
}
else
{
cf.setCurrency("USD", "$");
trace(cf.format(1234567.89)); // USD1,234,567.89
}

,
CurrencyFormatter ,
. CurrencyFormatter.parse()
CurrencyParseResult, :
var cf:CurrencyFormatter = new CurrencyFormatter( "en-US" );
var inputCurrencyString:String = "(GBP 123,56,7.890)";
var parseResult:CurrencyParseResult = cf.parse(inputCurrencyString);
trace("parsed amount: " + parseResult.value); // -1234567.89
trace("currencyString: " + parseResult.currencyString ); // GBP

, ISO
. ,
, negativeCurrencyFormat
positiveCurrencyFormat. :

23.11.2012.

1019

ACTIONSCRIPT 3.0

var cf:CurrencyFormatter = new CurrencyFormatter( "en-US" );


var inputCurrencyString:String = "Total $-123,56,7.890";
var parseResult:CurrencyParseResult = cf.parse(inputCurrencyString);
trace("status: " + cf.lastOperationStatus ); // parseError
trace("parsed amount: " + parseResult.value); // NaN
trace("currencyString: " + parseResult.currencyString ); //
cf.negativeCurrencyFormat = 2;
parseResult = cf.parse(inputCurrencyString);
trace("status: " + cf.lastOperationStatus ); // noError
trace("parsed amount: " + parseResult.value); // -123567.89
trace("currencyString: " + parseResult.currencyString ); // Total $

, .
negativeCurrencyFormat en-US ,
. parse() , NaN.
negativeCurrencyFormat 2,
, parse() .


Flash Player 10.1 , Adobe AIR 2.0
.
, ( 1962 , 13:01)
:

en-US (, )

1/2/62 1:01pm

fr-FR (, )

2/1/62 13:01

ja-JP (, )

1962/2/1 13:01

DateTimeFormatter
DateTimeFormatter Date ,
.
, ,
. , yyyy/MM yyyy
, /
.
setDateTimePattern().

.
DateTimeFormatter (LONG,
MEDIUM SHORT) CUSTOM.
, . ,
, .

23.11.2012.

1020

ACTIONSCRIPT 3.0

DateTimeFormatter. ,
DateTimeStyle.LONG.
setDateTimeStyles(), :
var date:Date = new Date(2009, 2, 27, 13, 1);
var dtf:DateTimeFormatter = new DateTimeFormatter("en-US",
DateTimeStyle.LONG, DateTimeStyle.LONG);
var longDate:String = dtf.format(date);
trace(longDate); // March 27, 2009 1:01:00 PM
dtf.setDateTimeStyles(DateTimeStyle.SHORT, DateTimeStyle.SHORT);
var shortDate:String = dtf.format(date);
trace(shortDate); // 3/27/09 1:01 PM



.

DateTimeFormatter.getMonthNames().
. DateTimeNameStyle.FULL
. DateTimeNameStyle.LONG_ABBREVIATION
DateTimeNameStyle.SHORT_ABBREVIATION .
( ),
. ,
DateTimeNameContext.STANDALONE getMonthNames().
, DateTimeNameContext.FORMAT.
var dtf:DateTimeFormatter = new DateTimeFormatter("fr-FR");
var months:Vector.<String> = dtf.getMonthNames(DateTimeNameStyle.FULL,
DateTimeNameContext.STANDALONE);
trace(months[0]); // janvier
months = dtf.getMonthNames(DateTimeNameStyle.SHORT_ABBREVIATION,
DateTimeNameContext.STANDALONE);
trace(months[0]); // janv.

DateTimeFormatter.getWeekdayNames() .
getWeekdayNames() nameStyle context, getMonthNames().
var dtf:DateTimeFormatter = new DateTimeFormatter("fr-FR");
var weekdays:Vector.<String> = dtf.getWeekdayNames(DateTimeNameStyle.FULL,
DateTimeNameContext.STANDALONE);
trace(weekdays[0]); // dimanche
weekdays = dtf.getWeekdayNames(DateTimeNameStyle.LONG_ABBREVIATION,
DateTimeNameContext.STANDALONE);
trace(weekdays[0]); // dim.

, getFirstWeekday() ,
.

23.11.2012.

1021

ACTIONSCRIPT 3.0


Flash Player 10.1 , Adobe AIR 2.0
.
. ,
,
.
, ,
, . , (o ), ,
o .
z . ,
.

. , , cote
cote, cte cot.

Collator
Collator compare(), ,
equals(), .
compare() equals().
var words:Array = new

Array("cot", "cte");

var sorter:Collator = new Collator("fr-FR", CollatorMode.SORTING);


words.sort(sorter.compare);
trace(words); // cte,cot
var matcher:Collator = new Collator("fr-FR", CollatorMode.MATCHING);
if (matcher.equals(words[0], words[1]))
{
trace(words[0] + " = " + words[1]); // cte = cot
}

Collator SORTING French-France.


, . ,
SORTING .
sort() Collator
Array.sort(). Collator
.
Collator MATCHING. Collator
, . , MATCHING
.

23.11.2012.

1022

ACTIONSCRIPT 3.0

Collator
Collator ,
.
compare() equals() .
:
Collator

numericComparison

, .

ignoreCase

, .

ignoreCharacterWidth

,
.

ignoreDiacritics

, ,
, .

ignoreKanaType

, ,
.

ignoreSymbols

, , ,
.

, ignoreDiacritics true
:
var words:Array = new Array("COTE", "cot", "cte", "Cot","cote");
var sorter:Collator = new Collator("fr-CA", CollatorMode.SORTING);
words.sort(sorter.compare);
trace(words); // cote,COTE,cte,cot,Cot
sorter.ignoreDiacritics = true;
words.sort(sorter.compare);
trace(words); // cte,cot,cote,Cot,COTE


Flash Player 10.1 , Adobe AIR 2.0
()
().
, , ,
I i. (, )
.
I. i .
StringTools ,
.

23.11.2012.

1023

ACTIONSCRIPT 3.0

StringTools
StringTools : toLowerCase()
toUpperCase(). StringTools .
StringTools ( )
. .
toUpperCase() toLowerCase()
, ( S).
var phrase:String = "Schlo Neuschwanstein";
var converter:StringTools = new StringTools("de-DE");
var upperPhrase:String = converter.toUpperCase(phrase);
trace(upperPhrase); // SCHLOSS NEUSCHWANSTEIN
var lowerPhrase:String = converter.toLowerCase(upperPhrase);
trace(lowerPhrase);// schloss neuschwanstein

toUpperCase() SS.
. SS ,
ss, .

. ,

Flash Player 10.1 , Adobe AIR 2.0
Global Stock Ticker
: , .
, .
flash.globalization:

.
.
ISO .
.
.

www.adobe.com/go/learn_programmingAS3samples_flash_ru. Global Stock Ticker
Samples/GlobalStockTicker. .

23.11.2012.

1024

ACTIONSCRIPT 3.0

File

GlobalStockTicker.mxm Flex (MXML) Flash (FLA).


l

GlobalStockTicker.fla
styles.css

( Flex).

com/example/program MXML, (
mingas3/stockticker/fle Flex).
x/FinGraph.mxml
com/example/program , ( Flash).
mingas3/stockticker/fla
sh/GlobalStockTicker.as
comp/example/progra Flash DataGrid ( Flash).
mmingas3/stockticker/f
lash/RightAlignedColu
mn.as
com/example/program ActionScript, .
mingas3/stockticker/Fi
nancialGraph.as
com/example/program ActionScript,
mingas3/stockticker/Lo , .
calizer.as
com/example/program ActionScript, Global Stock Ticker.
mingas3/stockticker/St
ockDataModel.as

;
;
DataGrid, ;
,
.
,
StockDataModel. ,
StockDataModel. StockDataModel.
. , ,
, DataGrid.
. .


Localizer.setLocale()
. setLocale() ,
.

23.11.2012.

1025

ACTIONSCRIPT 3.0

public function setLocale(newLocale:String):void


{
locale = new LocaleID(newLocale);
nf = new NumberFormatter(locale.name);
traceError(nf.lastOperationStatus, "NumberFormatter", nf.actualLocaleIDName);
cf = new CurrencyFormatter(locale.name);
traceError(cf.lastOperationStatus, "CurrencyFormatter", cf.actualLocaleIDName);
symbolIsSafe = cf.formattingWithCurrencySymbolIsSafe(currentCurrency);
cf.setCurrency(currentCurrency, currentSymbol);
cf.fractionalDigits = currentFraction;
df = new DateTimeFormatter(locale.name, DateTimeStyle.LONG, DateTimeStyle.SHORT);
traceError(df.lastOperationStatus, "DateTimeFormatter", df.actualLocaleIDName);
monthNames = df.getMonthNames(DateTimeNameStyle.LONG_ABBREVIATION);
}
public function traceError(status:String, serviceName:String, localeID:String) :void
{
if(status != LastOperationStatus.NO_ERROR)
{
if(status == LastOperationStatus.USING_FALLBACK_WARNING)
{
trace("Warning - Fallback locale ID used by "
+ serviceName + ": " + localeID);
}
else if (status == LastOperationStatus.UNSUPPORTED_ERROR)
{
trace("Error in " + serviceName + ": " + status);
//abort application
throw(new Error("Fatal error", 0));
}
else
{
trace("Error in " + serviceName + ": " + status);
}
}
else
{
trace(serviceName + " created for locale ID: " + localeID);
}
}

setLocale() LocaleID.
.
NumberFormatter, CurrencyFormatter DateTimeFormatter .
traceError().
, . (
, ).
CurrencyFormatter setLocale() ISO,
fractionalDigits . (
, ).

23.11.2012.

1026

ACTIONSCRIPT 3.0

DateTimeFormatter setLocale()
.


DataGrid.
DataGrid label,
.
Flash, , DataGrid:
var col1:DataGridColumn = new DataGridColumn("ticker");
col1.headerText = "Company";
col1.sortOptions = Array.NUMERIC;
col1.width = 200;
var col2:DataGridColumn = new DataGridColumn("volume");
col2.headerText = "Volume";
col2.width = 120;
col2.cellRenderer = RightAlignedCell;
col2.labelFunction = displayVolume;
var col3:DataGridColumn = new DataGridColumn("price");
col3.headerText = "Price";
col3.width = 70;
col3.cellRenderer = RightAlignedCell;
col3.labelFunction = displayPrice;
var col4:DataGridColumn = new DataGridColumn("change");
col4.headerText = "Change";
col4.width = 120;
col4.cellRenderer = RightAlignedCell;
col4.labelFunction = displayPercent;

Flex DataGrid MXML.


label .
labelFunction ,
Localizer:
private function displayVolume(item:Object):String
{
return localizer.formatNumber(item.volume, 0);
}
private function displayPercent(item:Object):String
{
return localizer.formatPercent(item.change ) ;
}
private function displayPrice(item:Object):String
{
return localizer.formatCurrency(item.price);
}

Localizer :

23.11.2012.

1027

ACTIONSCRIPT 3.0

public function formatNumber(value:Number, fractionalDigits:int = 2):String


{
nf.fractionalDigits = fractionalDigits;
return nf.formatNumber(value);
}
public function formatPercent(value:Number, fractionalDigits:int = 2):String
{
// HACK WARNING: The position of the percent sign, and whether a space belongs
// between it and the number, are locale-sensitive decisions. For example,
// in Turkish the positive format is %12 and the negative format is -%12.
// Like most operating systems, flash.globalization classes do not currently
// provide an API for percentage formatting.
nf.fractionalDigits = fractionalDigits;
return nf.formatNumber(value) + "%";
}
public function formatCurrency(value:Number):String
{
return cf.format(value, symbolIsSafe);
}
public function formatDate(dateValue:Date):String
{
return df.format(dateValue);
}
|

23.11.2012.

1028

1029

57.
Flash Player 9 , Adobe AIR 1.0
.
. , en_US (), fr_FR
().
: en_US, fr_FR.
. , en_US en_GB ()
. , , ,
. , en_US
color, en_GB colour. , : , ,
.
. , en
en_US ,
().
.
: , .


Flash Player 9 , Adobe AIR 1.0
, , :

flash.globalization , flash.globalization,
.
, Flash
Player 10.1 AIR 2.0 . .
1014.

. ,
.

(AIR only) Capabilities.languages. Capabilities.languages


, ,
. , ( , ),
RFC4646 (http://www.ietf.org/rfc/rfc4646.txt).
(, "en-US" "ja-JP").
ID , language. , languages[0] "en-US",
language "en". , language "xu" ( ),
languages .

Capabilities.language. Capabilities.language

. 20
. , .
Capabilities.languages.

23.11.2012.

ACTIONSCRIPT 3.0

Flex
Flash Player 9 , Adobe AIR 1.0
Adobe Flex Flex.
Locale, ResourceBundle ResourceManagerImpl, IResourceBundle
IResourceManagerImpl.
Adobe Flex, ,
Google Code (http://code.google.com/p/as3localelib/).


http://code.google.com/p/as3localelib/

Flash
Flash Player 9 , Adobe AIR 1.0
Adobe Flash Professional Locale ActionScript 3.0. Locale
, SWF- . Flash
ID . SWF-,
, XML- .
Locale . ActionScript 3.0 Adobe Flash Platform.

AIR
Adobe AIR 1.0
AIR SDK HTML ( AIRLocalizer.js).
API-,
HTML. ActionScript
http://code.google.com/p/as3localelib/.


http://code.google.com/p/as3localelib/

,
Flash Player 9 , Adobe AIR 1.0
, . ,
//,
//.

23.11.2012.

1030

ACTIONSCRIPT 3.0

, . , Date
// //. locale
( ) "en_US", //.
Date //:
function convertDate(date)
{
if (locale == "en_US")
{
return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
}
else
{
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
}
}

ADOBE FLEX
Flex , .
DateFormatter CurrencyFormatter.

mx:DateFormatter
mx:CurrencyFormatter

23.11.2012.

1031

1032

58. HTML
Adobe AIR 1.0
Adobe AIR WebKit (www.webkit.org), - Safari,
, , HTML JavaScript.
API- AIR HTML- .
HTMLLoader HTML HTML JavaScript.
HTML- (
, HTML, CSS, DOM JavaScript, WebKit).
: Adobe AIR WebKit.
WebKit AIR
AIR. HTML
. , WebKit
.
.
WebKit, AIR,
AIR
.
- Safari, WebKit,
, AIR:
AIR
1.0
1.1
1.5
2.0
2.5
2.6
2.7
3

Safari
2.04
3.04
4.0 Beta
4.03
4.03
4.03
4.03
5.0.3

WebKit
, HTMLLoader:
var htmlLoader:HTMLLoader = new HTMLLoader();
trace( htmlLoader.userAgent );

, WebKit, AIR, .
AIR, AIR ,
WebKit. . WebKit
AIR 1048.
AIR
, HTML- , . AIR ,
.
API- AIR. AIR
. ,

23.11.2012.

ACTIONSCRIPT 3.0
HTML

, . ,
http https,
.
AIR , .
HTML- AIR SWF- PDF-,
-, . .
SWF PDF HTML 1080
958.


DOM Webkit
HTML Safari
CSS Safari
www.webkit.org

HTML
Adobe AIR 1.0
Adobe AIR JavaScript ,
HTML, JavaScript. JavaScript
AIR HTMLLoader. HTML HTMLLoader HTML-, ,
, NativeWindow. SWF- HTMLLoader,
Sprite, ,
. Adobe ActionScript 3.0
HTML- AIR 1078 ActionScript 3.0 Adobe Flash Platform.
Flex AIR HTMLLoader mx:HTML. mx:HTML
UIComponent, Flex.
JavaScript mx:HTML .

JavaScript AIR
Adobe AIR 1.0
, JavaScript AIR.
, AIR . (
HTMLLoader.)

23.11.2012.

1033

ACTIONSCRIPT 3.0
HTML

AIR

NativeWindow

HTMLLoader
window

JavaScript
window

document

body

head

htmlLoader

nativeWindow

runtime
h1

div

table

JavaScript Document Window. JavaScript AIR


runtime, nativeWindow htmlLoader. ActionScript JavaScript
window HTMLLoader, Window JavaScript. ,
ActionScript, JavaScript , AIR JavaScript.

runtime API- AIR AIR


( ). API- AIR
runtime ( ). , File
:
var file = new window.runtime.filesystem.File();

. AIR SDK JavaScript AIRAliases.js,


AIR. window.runtime.package.Class
air.Class. , File new
air.File().
NativeWindow . HTML-
window.nativeWindow - NativeWindow.
HTMLLoader ,
. HTML- window.htmlLoader
HTMLLoader.

23.11.2012.

1034

ACTIONSCRIPT 3.0
HTML

. htmlLoader, nativeWindow runtime ,


,
. , .
( ,
.) , , ,
runtime parent.runtime).


Adobe AIR 1.0
AIR , .
, ,
. API-
AIR HTML JavaScript,
. JavaScript
load .

AIR sandboxRoot
documentRoot. sandboxRoot ,

.
, -.
,
API- AIR
. ,
,
. ,
, .
parentSandboxBridge
childSandboxBridge window. . HTML
Adobe AIR 1164 frame iframe HTML 1044.


Adobe AIR 1.0
AIR Adobe Acrobat. PDF-
Acrobat Adobe Reader 8.1 ( ). HTMLLoader
PDF-. SWF-
HTML,
.
WebKit AIR.


HTML Adobe AIR 1164
HTML 1036

23.11.2012.

1035

ACTIONSCRIPT 3.0
HTML

frame iframe HTML 1044


Window JavaScript 1042
XMLHttpRequest 1038
PDF- AIR 592

AIR WebKit
Adobe AIR 1.0
Adobe AIR WebKit , Safari. AIR ,
. , WebKit , W3C
HTML, CSS JavaScript.
AIR WebKit.
HTML, CSS JavaScript .
www.webkit.org developer.apple.com. - W3C. Mozilla
HTML, CSS DOM (, WebKit Mozilla
).

JavaScript AIR
Flash Player 9 , Adobe AIR 1.0
AIR JavaScript.
, AIR. ,
JavaScript -,
, AIR . .
JavaScript 1055.

HTML
Adobe AIR 1.0
AIR .
,
,
Adobe Flash. , AIR
.
, AIR, .
1122.
API- AIR HTML JavaScript,
.
JavaScript
.
, . ( ,
, , .)

23.11.2012.

1036

ACTIONSCRIPT 3.0
HTML

, ,
. ,
(
URL- app:). , ,

,
, . , ,
, .

, , . ,
, ,
, .
, frame iframe
HTML.

AIR, .

, .
, ,
, . ,
.
. , ,
,
.

eval() JavaScript
Adobe AIR 1.0
eval()
. , JSON
, , ,
.
1167 eval().


Adobe AIR 1.0

. load
.


Adobe AIR 1.0
HTML- script
JavaScript .
,
.

23.11.2012.

1037

ACTIONSCRIPT 3.0
HTML

XMLHttpRequest
Adobe AIR 1.0
AIR XMLHttpRequest (XHR),
. .
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http:/www.example.com/file.data", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
//do something with data...
}
}
xmlhttp.send(null);

, AIR ,
, . XHR, JSON-,
, . XHR
, , .
XHR
, . XHR
.
AIR XMLHttpRequest
.

. allowCrossDomainXHR frame iframe, AIR,
true:
<iframe id="mashup"
src="http://www.example.com/map.html"
allowCrossDomainXHR="true"
</iframe>

. AIR URLStream.
XMLHttpRequest
, , ,
URL- XHR. ,
iframe,
example.com:
<iframe id="mashup"
src="http://www.example.com/map.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://www.example.com/"
allowCrossDomainXHR="true"
</iframe>

sandboxRoot URL- www.example.com,


, .
, : XMLHttpRequest.

23.11.2012.

1038

ACTIONSCRIPT 3.0
HTML

, sandboxRoot
URL-, . , .
, www.example.com ,
, (iframe), .
<iframe id="mashup"
src="http://www.example.com/map.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://www.example.com/air/"
allowCrossDomainXHR="true"
</iframe>

air.
.
frame iframe HTML 1044 HTML Adobe AIR 1164.

ookies
Adobe AIR 1.0
AIR (
http: https:) cookies ( document.cookie).
,
EncryptedLocalStore, SharedObject FileStream.

Clipboard
Adobe AIR 1.0
API- Clipboard WebKit copy, cut paste. ,
, clipboardData.
clipboardData.

clearData(mimeType)

. mimeType MIME- .

getData(mimeType)

.
paste. mimeType MIME- .

setData(mimeType,
)

. mimeType MIME- .

JavaScript
.
Clipboard AIR. ,
:
var clipping = air.Clipboard.generalClipboard.getData("text/plain",
air.ClipboardTransferMode.ORIGINAL_ONLY);

MIME- :

23.11.2012.

1039

ACTIONSCRIPT 3.0
HTML

MIME

text/plain;

HTML

text/html;

URL-

text/uri-list;

image/x-vnd.adobe.air.bitmap;

application/x-vnd.adobe.air.file-list.

.
.
, .
.
641 Pasteboard JavaScript ( Apple).

Adobe AIR 1.0


HTML- DOM: dragstart, drag,
dragend, dragenter, dragover, dragleave drop. , ,
dataTransfer. dataTransfer
, , clipboardData,
clipboard. , drop:
function onDrop(dragEvent){
return dragEvent.dataTransfer.getData("text/plain",
air.ClipboardTransferMode.ORIGINAL_ONLY);
}

dataTransfer.

clearData(mimeType)

. mimeType MIME-
.

getData(mimeType)

.
drop. mimeType MIME- .

setData(mimeType,
)

. mimeType MIME- .

types

, MIME- ,
dataTransfer.

effectsAllowed

, , .
effectsAllowed dragstart.

dropEffect

,
. dropEffect dragEnter.
, , ,
. dropEffect , effectsAllowed.
copy move, , , link.
.

23.11.2012.

1040

ACTIONSCRIPT 3.0
HTML

AIR .
AIR 654 JavaScript (
Apple).

innerHTML outerHTML
Adobe AIR 1.0
AIR innerHTML outerHTML
. load
load innerHTML outerHTML .
innerHTML outerHTML
. , innerHTML
outerHTML, , . ,
, .
<script> . . HTML
Adobe AIR 1164.

Document.write() Document.writeln()
Adobe AIR 1.0
write() writeln() ,
load. ,
. ,
-, document.write() writeln()
, .

Document.designMode
Adobe AIR 1.0
, document.designMode
on. , , .
on designMode true contentEditable body.
contentEditable HTML-
. . contentEditable
HTML 1047.

unload ( body frameset)


Adobe AIR 1.0
frameset body ( . . )
unload ( ). exiting
NativeApplication ( ).
closing NativeWindow ( ). ,
JavaScript, , (Goodbye. ):

23.11.2012.

1041

ACTIONSCRIPT 3.0
HTML

var app = air.NativeApplication.nativeApplication;


app.addEventListener(air.Event.EXITING, closeHandler);
function closeHandler(event)
{
alert("Goodbye.");
}

unload, ,
.
. , Adobe AIR.

Window JavaScript
Adobe AIR 1.0
Window JavaScript.
AIR JavaScript Window
AIR, . ,
- ,
.
Window.runtime runtime
. API AIR Flash Player ( Flex). ,
AIR:
var preferencesFile = new window.runtime.flash.filesystem.File();

AIRAliases.js, AIR SDK, ,


. , AIRAliases.js File
:
var preferencesFile = new air.File();

window.runtime
, . . .
. AIRAliases.js 1061.
Window.nativeWindow nativeWindow

. : , ,
., : , .
, :
window.nativeWindow.close();

. NativeWindow
Window JavaScript. , .
window.nativeWindow
, . . .
Window.htmlLoader htmlLoader AIR HTMLLoader HTML-

. HTML. , htmlLoader.paintsDefaultBackground ,
( ):
window.htmlLoader.paintsDefaultBackground = false;

23.11.2012.

1042

ACTIONSCRIPT 3.0
HTML

. HTMLLoader window, JavaScript Window


HTML-. JavaScript
HTMLLoader.
window.htmlLoader
, . . .
Window.parentSandboxBridge Window.childSandboxBridge parentSandboxBridge
childSandboxBridge .

.
1073.
Window.setTimeout() Window.setInterval() AIR

setTimeout() setInterval() . ,
setTimeout() setInterval(), .
. .
setTimeout() setInterval() 1058.
Window.open() open() ,

, ,
(, ). ,
( , , ,
). . JavaScript
window.open() 1170.

air.NativeApplication
Adobe AIR 1.0
NativeApplication ,
( ) .
NativeApplication ,
NativeApplication.nativeApplication.
JavaScript :
var app = window.runtime.flash.desktop.NativeApplication.nativeApplication;

, AIRAliases.js, :
var app = air.NativeApplication.nativeApplication;

NativeApplication
. NativeApplication .
AIR 951.

URL- JavaScript
Adobe AIR 1.0
, URL- JavaScript (, href="javascript:alert('Test')"),
. .

23.11.2012.

1043

ACTIONSCRIPT 3.0
HTML

HTML AIR
Adobe AIR 1.0
AIR WebKit HTML, :
frame iframe HTML 1044
HTML 1046

frame iframe HTML


Adobe AIR 1.0
AIR frame iframe
.
sandboxRoot sandboxRoot

src ( ). ,
. ,
, .
. sandboxRoot URL- ,
, (
, : , XMLHttpRequest
).
documentRoot documentRoot , URL, , sandboxRoot.

URL- src , , URL,


sandboxRoot, documentRoot. ,
:
<iframe src="http://www.example.com/air/child.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://www.example.com/air/"/>
child.html sandbox .

URL- child.html sandbox. ,


www.example.com/air , AIR
app:/sandbox/.
allowCrossDomainXHR XMLHttpRequest
,
allowCrossDomainXHR="allowCrossDomainXHR".
. API XHR
. .
- , ,
. API XHR
, ,
.
, .

23.11.2012.

1044

ACTIONSCRIPT 3.0
HTML

. allowCrossDomainXHR frame iframe,


API XHR ( , 0
f n). , allowCrossDomainXHR deny, API XHR .
, .
ondominitialize dominitialize .

AIR. ,
- .
dominitialize ,
, ,
dominitialize.
, ,
.
.
, iframe AIR.
child.html
.
<iframe src="http://localhost/air/child.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://localhost/air/"/>

child.html
XMLHttpRequest www.example.com:
<iframe src="http://www.example.com/air/child.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://www.example.com/air/"/>

child.html
XMLHttpRequest .
<iframe src="http://www.example.com/air/child.html"
documentRoot="app:/sandbox/"
sandboxRoot="http://www.example.com/air/"
allowCrossDomainXHR="allowCrossDomainXHR"/>

child.html
.
<iframe

src="file:///templates/child.html"
documentRoot="app:/sandbox/"
sandboxRoot="app-storage:/templates/"/>

child.html
dominitialize, .

23.11.2012.

1045

ACTIONSCRIPT 3.0
HTML

<html>
<head>
<script>
var bridgeInterface = {};
bridgeInterface.testProperty = "Bridge engaged";
function engageBridge(){
document.getElementById("sandbox").parentSandboxBridge = bridgeInterface;
}
</script>
</head>
<body>
<iframe id="sandbox"
src="http://www.example.com/air/child.html"
documentRoot="app:/"
sandboxRoot="http://www.example.com/air/"
ondominitialize="engageBridge()"/>
</body>
</html>

child.html ,
:
<html>
<head>
<script>
document.write(window.parentSandboxBridge.testProperty);
</script>
</head>
<body></body>
</html>

.
1073 HTML Adobe AIR
1164.

HTML
Adobe AIR 1.0
DOM AIR WebKit ,
DOM. ,
.

oncontextmenu

oncopy

oncut

ondominitialize

DOM ,
,
DOM .

23.11.2012.

1046

ACTIONSCRIPT 3.0
HTML

ondrag

ondragend

ondragenter

,
.

ondragleave

,
.

ondragover

,
.

ondragstart

ondrop

,
.

onerror

, .

oninput

, form .

onpaste

, .

onscroll

,
.

onselectstart

, .

contentEditable HTML
Adobe AIR 1.0
contentEditable HTML-.
. HTML- ,
, p.
<html>
<head/>
<body contentEditable="true">
<h1>de Finibus Bonorum et Malorum</h1>
<p contentEditable="false">Sed ut perspiciatis unde omnis iste natus error.</p>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis.</p>
</body>
</html>

. document.designMode on,
, contentEditable .
designMode off, , contentEditable
true, - . .
Document.designMode 1041.

Data: URL-
Adobe AIR 2
AIR URL- data: :

img
23.11.2012.

1047

ACTIONSCRIPT 3.0
HTML

input type="image"
CSS, (, background-image)
URL- Data
CSS HTML , base64. URL-
data: :
<html>
<head>
<style>
body {
backgroundimage:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAMAAABHPGVmAAAAGXRFWHRTb2Z
0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRF%2F6cA%2F%2F%2F%2Fgxp3lwAAAAJ0Uk5T%2FwDltzBKAAA
BF0lEQVR42uzZQQ7CMAxE0e%2F7X5oNCyRocWzPiJbMBZ6qpIljE%2BnwklgKG7kwUjc2IkIaxkY0CPdEsCCasws6ShX
BgmBBmEagpXQQLAgWBAuSY2gaKaWPYEGwIEwg0FRmECwIFoQeQjJlhJWUEFazjFDJCkI5WYRWMgjtfEGYyQnCXD4jTCd
m1zmngFpBFznwVNi5RPSbwbWnpYr%2BBHi%2FtCTfgPLEPL7jBctAKBRptXJ8M%2BprIuZKu%2BUKcg4YK1PLz7kx4bS
qHyPaT4d%2B28OCJJiRBo4FCQsSA0bziT3XubMgYUG6fc5fatmGBQkL0hoJ1IaZMiQsSFiQ8vRscTjlQOI2iHZwtpHuf
%2BJAYiOiJSkj8Z%2FIQ4ABANvXGLd3%2BZMrAAAAAElFTkSuQmCC');
background-repeat:repeat;
}
</style>
</head>
<body>
</body>
</html>

URL- data: , .
, .
.

CSS AIR
Adobe AIR 1.0
WebKit CSS.
: -webkit. ,
WebKit.
Webkit CSS CSS . CSS Safari.

WebKit AIR
Adobe AIR 1.0
AIR , WebKit Safari 4.

window.postMessage (AIR
API- )

CSS
Web Open Font Format (WOFF) SVG.
- HTML

23.11.2012.

1048

ACTIONSCRIPT 3.0
HTML


(AIR API- PrintJob)

SVG
WAI-ARIA
- (AIR API- )
worker Web
API- WebKit SQL (AIR API-)
API- WebKit (AIR API-
)

API- WebKit
WebKit (AIR )
WML (Wireless Markup Language, )
API- JavaScript, HTML,
CSS, AIR:
Window JavaScript:
applicationCache();

console;
openDatabase();
postMessage();
document.print();
HTML:
audio;

video.
HTML:
aria-*

draggable
formnovalidate
list
novalidate
onbeforeload
onhashchange
onorientationchange
onpagehide
onpageshow
onpopstate

23.11.2012.

1049

ACTIONSCRIPT 3.0
HTML

ontouchstart
ontouchmove
ontouchend
ontouchcancel
onwebkitbeginfullscreen
onwebkitendfullscreen
pattern
required
sandbox
JavaScript:
beforeload

hashchange
orientationchange
pagehide
pageshow
popstate
touchstart
touchmove
touchend
touchcancel
webkitbeginfullscreen
webkitendfullscreen
CSS:
background-clip

background-origin ( -webkit-background-origin)
background-repeat-x
background-repeat-y
background-size ( -webkit-background-size)
border-bottom-left-radius
border-bottom-right-radius
border-radius
border-top-left-radius
border-top-right-radius
text-rendering
-webkit-animation-play-state
-webkit-background-clip

23.11.2012.

1050

ACTIONSCRIPT 3.0
HTML

-webkit-color-correction
-webkit-font-smoothing
CSS:
appearance:

media-volume-slider-container
media-volume-slider
media-volume-sliderthumb
outer-spin-button
border-box (background-clip background-origin)
contain (background-size)
content-box (background-clip background-origin)
cover (background-size)
list:
afar
amharic
amharic-abegede
cjk-earthly-branch
cjk-heavenly-stem
ethiopic
ethiopic-abegede
ethiopic-abegede-am-et
ethiopic-abegede-gez
ethiopic-abegede-ti-er
ethiopic-abegede-ti-et
ethiopic-halehame-aa-er
ethiopic-halehame-aa-et
ethiopic-halehame-am-et
ethiopic-halehame-gez
ethiopic-halehame-om-et
ethiopic-halehame-sid-et
ethiopic-halehame-so-et
ethiopic-halehame-ti-er
ethiopic-halehame-ti-et
ethiopic-halehame-tig
hangul
hangul-consonant

23.11.2012.

1051

ACTIONSCRIPT 3.0
HTML

lower-norwegian
oromo
sidama
somali
tigre
tigrinya-er
tigrinya-er-abegede
tigrinya-et
tigrinya-et-abegede
upper-greek
upper-norwegian
-wap-marquee ( )

23.11.2012.

1052

1053

59. HTML
JavaScript AIR
Adobe AIR 1.0
Adobe AIR
HTML JavaScript. ,
AIR HTML- SWF- HTML JavaScript
HTMLLoader ( mx:HTML Flex).

HTMLLoader
Adobe AIR 1.0
HTMLLoader Adobe AIR , HTML-
AIR. SWF- HTMLLoader
, HTMLLoader.createRootWindow()
HTML, HTMLLoader. HTMLLoader JavaScript
window.htmlLoader HTML-.

HTML- URL
Adobe AIR 1.0
URL HTMLLoader ( HTMLLoader
Stage HTML ):
import flash.html.HTMLLoader;
var html:HTMLLoader = new HTMLLoader;
html.width = 400;
html.height = 600;
var urlReq:URLRequest = new URLRequest("http://www.adobe.com/");
html.load(urlReq);

width height HTMLLoader 0.


HTMLLoader . HTMLLoader
. , .
AIR HTML 1097.
. Flex - UIComponent
Container. HTMLLoader
Container, Flex mx:HTML
- UIComponent, HTMLLoader
UIComponent. HTMLLoader
UIComponent, UIComponent Flex.

23.11.2012.

ACTIONSCRIPT 3.0
HTML JavaScript AIR

HTML- TextField,
. TextField Adobe Flash HTML-, -
. ( HTMLLoader Adobe AIR
Flash Player.)

HTML-
Adobe AIR 1.0
loadString() HTMLLoader HTML- HTMLLoader:
var html:HTMLLoader = new HTMLLoader();
var htmlStr:String = "<html><body>Hello <b>world</b>.</body></html>";
html.loadString(htmlStr);

, loadString(),
, .

( ).
XMLHttpRequest.
window.location "about:blank".
window.runtime (
).
Adobe AIR 1.5 HTMLLoader placeLoadStringContentInApplicationSandbox.
HTMLLoader true, ,
loadString(), . (
false.) , loadString(),
window.runtime AIR.
true, ,
loadString(). HTML
, true.
true , ,
.
, SDK AIR 1.0 AIR 1.1, ,
loadString(), .

HTML AIR
Adobe AIR 1.0
, AIR, API- AIR.
. ,
(, http://example.com)
( ).
- , eval() ( API-)
, ,
, . Ajax
eval() API.

23.11.2012.

1054

ACTIONSCRIPT 3.0
HTML JavaScript AIR

AIR
, .

(. 1122).
, ,
, API- AIR.
,
.
, ,
( ).
-. ,
eval() (
API- AIR).
API- AIR
. .
1073.
,
, JavaScript:
Adobe AIR JavaScript .
,
JavaScript 1055.
. HTML Adobe AIR 1164.

JavaScript
Adobe AIR 1.0
,
, JavaScript:
Adobe AIR JavaScript .
.

JavaScript
Adobe AIR 1.0
, ,
, load
load. JavaScript
JavaScript:

eval();
setTimeout() setInterval();
.
, JavaScript ,
JavaScript :

23.11.2012.

1055

ACTIONSCRIPT 3.0
HTML JavaScript AIR

javascript:URL
, onevent innerHTML outerHTML
JavaScript
document.write() document.writeln()
XMLHttpRequest load load

. . .

1167.
Ajax, ,
Adobe http://www.adobe.com/go/airappsandboxframeworks_ru.
, ,
JavaScript .



Adobe AIR 1.0
, JavaScript,
. ,
,
1074.
API- AIR, ,
1075.

eval()
Flash Player 9 , Adobe AIR 1.0
eval()
load load. eval()
. ,
eval().


Adobe AIR 1.0
:
eval("obj." + propName + " = " + val);

:
obj[propName] = val;

23.11.2012.

1056

ACTIONSCRIPT 3.0
HTML JavaScript AIR


Adobe AIR 1.0
:
function compile(var1, var2){
eval("var fn = function(){ this."+var1+"(var2) }");
return fn;
}

:
function compile(var1, var2){
var self = this;
return function(){ self[var1](var2) };
}

Adobe AIR 1.0


JavaScript, :
var CustomClass =
{
Utils:
{
Parser: function(){ alert('constructor') }
},
Data:
{
}
};
var constructorClassName = "CustomClass.Utils.Parser";

eval():
var myObj;
eval('myObj=new ' + constructorClassName +'()')

eval(),
:

23.11.2012.

1057

ACTIONSCRIPT 3.0
HTML JavaScript AIR

function getter(str)
{
var obj = window;
var names = str.split('.');
for(var i=0;i<names.length;i++){
if(typeof obj[names[i]]=='undefined'){
var undefstring = names[0];
for(var j=1;j<=i;j++)
undefstring+="."+names[j];
throw new Error(undefstring+" is undefined");
}
obj = obj[names[i]];
}
return obj;
}

:
try{
var Parser = getter(constructorClassName);
var a = new Parser();
}catch(e){
alert(e);
}

setTimeout() setInterval()
Adobe AIR 1.0
, , . ,
:
setTimeout("alert('Timeout')", 100);

:
setTimeout(function(){alert('Timeout')}, 100);

, , this
:
this.appTimer = setInterval("obj.customFunction();", 100);

:
var _self = this;
this.appTimer = setInterval(function(){obj.customFunction.apply(_self);}, 100);


Adobe AIR 1.0
new Function(param, body) .
load.

23.11.2012.

1058

ACTIONSCRIPT 3.0
HTML JavaScript AIR

javascript:URL
Adobe AIR 1.0
, URL- javascript:,
. JavaScript .
javascript: URL, :
<a href="javascript:code()">Click Me</a>

:
<a href="#" onclick="code()">Click Me</a>

, onevent
innerHTML outerHTML
Adobe AIR 1.0
innerHTML outerHTML DOM
, , onclick onmouseover, .
. id
addEventListener().
, , :
<div id="container"></div>

:
document.getElementById('container').innerHTML =
'<a href="#" onclick="code()">Click Me.</a>';

:
document.getElementById('container').innerHTML = '<a href="#" id="smith">Click Me.</a>';
document.getElementById('smith').addEventListener("click", function() { code(); });

JavaScript

Adobe AIR 1.0


.
. ,
, .
, . .
1074.

23.11.2012.

1059

ACTIONSCRIPT 3.0
HTML JavaScript AIR

document.write() document.writeln()
Adobe AIR 1.0
document.write() document.writeln() load
. .
( body) , DOM.

XMLHttpRequest load
load
Adobe AIR 1.0
XMLHttpRequest, load
load, . XMLHttpRequest
, , load.
load XMLHttpRequest .


Adobe AIR 1.0
(, innerHTML
document.createElement()) .

API- AIR JavaScript


Adobe AIR 1.0
Webkit, HTML JavaScript
. AIR,
:


SQL




, API- AIR File, flash.filesystem.
File JavaScript :
var myFile = new window.runtime.flash.filesystem.File();

23.11.2012.

1060

ACTIONSCRIPT 3.0
HTML JavaScript AIR

runtime JavaScript, HTML-


AIR. JavaScript
. flash runtime flash-.
, flash.filesystem runtime flash.filesystem (
File). ActionScript.
. runtime window ,
frame iframe. ,
, runtime .
JavaScript
(, window.runtime.flash.desktop.NativeApplication),
AIR SDK AIRAliases.js,
(, air.NativeApplication).
API- AIR . API Flash Player, ,
API- Adobe AIR HTML-. ActionScript
SWF- ( Flash Player). JavaScript ActionScript . ( ,
ECMAScript.)
JavaScript ( HTML-), ActionScript ( SWF-).
. JavaScript Dictionary, XML XMLList,
ActionScript.

AIRAliases.js
Adobe AIR 1.0
, :

window.runtime.flash.desktop.NativeApplication

window.runtime.flash.desktop.ClipboardManager

window.runtime.flash.filesystem.FileStream

window.runtime.flash.data.SQLDatabase

AIR SDK AIRAliases.js, ,


. ,
:

air.NativeApplication

air.Clipboard

air.FileStream

air.SQLDatabase

AIRAliases.js.
. API- Adobe AIR HTML-.
, AIRAliases.js
: window.runtime.trace(),
window.runtime.flash.net.navigateToURL() window.runtime.flash.net.sendToURL(),
air.trace(), air.navigateToURL() air.sendToURL().

23.11.2012.

1061

1062

ACTIONSCRIPT 3.0
HTML JavaScript AIR

AIRAliases.js, HTML- script:


<script src="AIRAliases.js"></script>

src.
. JavaScript ,
AIRAliases.js HTML-, .

URL- AIR
Adobe AIR 1.0
HTML-, AIR,
URL- src img, frame, iframe script, href link
, URL-.
URL

file

, .

file:///c:/AIR Test/test.txt

app

,
.

app:/images

app-storage

app-storage:/settings/prefs.xml
,
. AIR
,
,
.

http

HTTP-.

http://www.adobe.com

https

HTTPS-.

https://secure.example.com

. URI 873.
API- AIR, File, Loader, URLStream Sound,
URLRequest, URL. URLRequest ,
URL-. ,
URLRequest, Adobe:
var urlReq = new air.URLRequest("http://www.adobe.com/");

URLRequest . HTTP 871.

23.11.2012.

ACTIONSCRIPT 3.0
HTML JavaScript AIR

ActionScript
JavaScript
Adobe AIR 1.0
JavaScript HTML-, HTMLLoader, ,
, ActionScript window.runtime,
window.htmlLoader window.nativeWindow HTML-. , ActionScript,
JavaScript, JavaScript.

JavaScript ActionScript
Adobe AIR 1.0
, , HTML:
var html:HTMLLoader = new HTMLLoader();
var foo:String = "Hello from container SWF."
function helloFromJS(message:String):void {
trace("JavaScript says:", message);
}
var urlReq:URLRequest = new URLRequest("test.html");
html.addEventListener(Event.COMPLETE, loaded);
html.load(urlReq);
function loaded(e:Event):void{
html.window.foo = foo;
html.window.helloFromJS = helloFromJS;
}

HTML- ( test.html), HTMLLoader ,


foo helloFromJS(), SWF-:
<html>
<script>
function alertFoo() {
alert(foo);
}
</script>
<body>
<button onClick="alertFoo()">
What is foo?
</button>
<p><button onClick="helloFromJS('Hi.')">
Call helloFromJS() function.
</button></p>
</body>
</html>

JavaScript
htmlDOMInitialize ,
. complete, ,
load, .

23.11.2012.

1063

ACTIONSCRIPT 3.0
HTML JavaScript AIR

JavaScript
Adobe AIR 1.0
ActionScript JavaScript, HTML-
, .
JavaScript runtimeApplicationDomain HTMLLoader.
, runtimeApplicationDomain
ApplicationDomain.currentDomain, :
html.runtimeApplicationDomain = ApplicationDomain.currentDomain;

runtimeApplicationDomain JavaScript
. JavaScript
window.runtime new:
var customClassObject = new window.runtime.CustomClass();

HTML- , . HTML , ,
. ,
ApplicationDomain.currentDomain .


Adobe AIR 1.0
JavaScript ,
, SWF- JavaScript,
, .
, .
: JavaScript
HTML-, .
AIR . .
HTML- 1102.

DOM JavaScript ActionScript


Adobe AIR 1.0
HTMLLoader complete, (DOM)
HTML . ( div
p ) JavaScript. complete load (
) JavaScript. complete , DOM, ,
. complete ,
DOM HTML.
, HTML-:

23.11.2012.

1064

ACTIONSCRIPT 3.0
HTML JavaScript AIR

<html>
<script>
foo = 333;
function test() {
return "OK.";
}
</script>
<body>
<p id="p1">Hi.</p>
</body>
</html>

HTML- JavaScript foo JavaScript test(). ,


window . , window.document
P ( ID p1), getElementById().
( HTMLLoader complete)
ActionScript, :
var html:HTMLLoader = new HTMLLoader();
html.width = 300;
html.height = 300;
html.addEventListener(Event.COMPLETE, completeHandler);
var xhtml:XML =
<html>
<script>
foo = 333;
function test() {
return "OK.";
}
</script>
<body>
<p id="p1">Hi.</p>
</body>
</html>;
html.loadString(xhtml.toString());
function completeHandler(e:Event):void {
trace(html.window.foo); // 333
trace(html.window.document.getElementById("p1").innerHTML); // Hi.
trace(html.window.test()); // OK.
}

HTML- innerHTML. ,
html.window.document.getElementById("p1").innerHTML
HTML- p1.
HTML- ActionScript. ,
p1 JavaScript foo - HTMLLoader:
html.window.document.getElementById("p1").innerHTML = "Goodbye";
html.window.foo = 66;

23.11.2012.

1065

ACTIONSCRIPT 3.0
HTML JavaScript AIR

SWF- HTML
Adobe AIR 1.0
AIR SWF- HTML- , .
SWF- object, embed .
. - object,
embed SWF- HTML-.
AIR. object W3C , AIR.
object embed
HTML- .
NativeWindow, HTML SWF, , AIR
SWF, (wmode), ,
window. SWF HTML
wmode opaque transparent. wmode
window, , .
, HTML object SWF- HTML.
wmode opaque, ,
NativeWindow. SWF- ,
URL-, AIR. (,
SWF-, , AIR
.)
<object type="application/x-shockwave-flash" width="100%" height="100%">
<param name="movie" value="app:/SWFFile.swf"></param>
<param name="wmode" value="opaque"></param>
</object>

. object
SWF-, urlString.
ID, elementID:

23.11.2012.

1066

ACTIONSCRIPT 3.0
HTML JavaScript AIR

<script>
function showSWF(urlString, elementID){
var displayContainer = document.getElementById(elementID);
var flash = createSWFObject(urlString, 'opaque', 650, 650);
displayContainer.appendChild(flash);
}
function createSWFObject(urlString, wmodeString, width, height){
var SWFObject = document.createElement("object");
SWFObject.setAttribute("type","application/x-shockwave-flash");
SWFObject.setAttribute("width","100%");
SWFObject.setAttribute("height","100%");
var movieParam = document.createElement("param");
movieParam.setAttribute("name","movie");
movieParam.setAttribute("value",urlString);
SWFObject.appendChild(movieParam);
var wmodeParam = document.createElement("param");
wmodeParam.setAttribute("name","wmode");
wmodeParam.setAttribute("value",wmodeString);
SWFObject.appendChild(wmodeParam);
return SWFObject;
}
</script>

SWF HTMLLoader,
alpha , 1.0. , AIR 1.5.2,
SWF wmode.
. SWF , , SWF , HTML-
. SWF
.
, SWF,
HTML-:

23.11.2012.

1067

ACTIONSCRIPT 3.0
HTML JavaScript AIR

var imageLoader;
function showSWF(urlString, elementID){
var displayContainer = document.getElementById(elementID);
imageLoader = createSWFObject(urlString,650,650);
displayContainer.appendChild(imageLoader);
}
function createSWFObject(urlString, width, height){
var SWFObject = document.createElement("object");
SWFObject.setAttribute("type","application/x-shockwave-flash");
SWFObject.setAttribute("width","100%");
SWFObject.setAttribute("height","100%");
var movieParam = document.createElement("param");
movieParam.setAttribute("name","movie");
movieParam.setAttribute("value",urlString);
SWFObject.appendChild(movieParam);
var flashVars = document.createElement("param");
flashVars.setAttribute("name","FlashVars");
//Load the asset inside the SWF content.
flashVars.setAttribute("value","imgPath=air.jpg");
SWFObject.appendChild(flashVars);
return SWFObject;
}
function loadImage()
{
showSWF("ImageLoader.swf", "imageSpot");
}

ActionScript , HTML-,
:

23.11.2012.

1068

ACTIONSCRIPT 3.0
HTML JavaScript AIR

package
{
import
import
import
import
import
import

flash.display.Sprite;
flash.display.LoaderInfo;
flash.display.StageScaleMode;
flash.display.StageAlign;
flash.display.Loader;
flash.net.URLRequest;

public class ImageLoader extends Sprite


{
public function ImageLoader()
{
var flashvars = LoaderInfo(this.loaderInfo).parameters;
if(flashvars.imgPath){
var imageLoader = new Loader();
var image = new URLRequest(flashvars.imgPath);
imageLoader.load(image);
addChild(imageLoader);
imageLoader.x = 0;
imageLoader.y = 0;
stage.scaleMode=StageScaleMode.NO_SCALE;
stage.align=StageAlign.TOP_LEFT;
}
}
}
}

ActionScript HTML
Adobe AIR 1.0
AIR HTML-, ActionScript
SWF-. , myClasses.swf,
lib , HTML- :
<script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script>

. ,
type="application/x-shockwave-flash".
SWF- SWF- Adobe Flash 10 AIR 1.5,
XML
AIR 1.5.
lib myClasses.swf AIR.
runtime Window JavaScript:
var libraryObject = new window.runtime.LibraryClass();

23.11.2012.

1069

ACTIONSCRIPT 3.0
HTML JavaScript AIR

SWF- , . ,
LibraryClass utilities,
:
var libraryObject = new window.runtime.utilities.LibraryClass();

. SWF- ActionScript HTML- AIR


acompc. acompc Flex SDK
Flex SDK.

DOM JavaScript HTML


ActionScript
Adobe AIR 1.0
HTML- ActionScript SWF-,
<script>, JavaScript, window document, ,
ActionScript. , ,
JavaScript ( , ).
, HTML-:
<html>
<script src="ASLibrary.swf" type="application/x-shockwave-flash"></script>
<script>
num = 254;
function getStatus() {
return "OK.";
}
function runASFunction(window){
var obj = new runtime.ASClass();
obj.accessDOM(window);
}
</script>
<body onload="runASFunction">
<p id="p1">Body text.</p>
</body>
</html>

HTML- JavaScript num JavaScript getStatus().


window . , window.document
P ( ID p1).
ActionScript ASLibrary.swf, ASClass. ASClass
accessDOM(), JavaScript. accessDOM()
JavaScript Window. Window
, , DOM,
:
public class ASClass{
public function accessDOM(window:*):void {
trace(window.num); // 254
trace(window.document.getElementById("p1").innerHTML); // Body text..
trace(window.getStatus()); // OK.
}
}

23.11.2012.

1070

ACTIONSCRIPT 3.0
HTML JavaScript AIR

, HTML- ActionScript.
, p1 JavaScript foo
:
public function modifyDOM(window:*):void {
window.document.getElementById("p1").innerHTML = "Bye";
window.foo = 66;

Date RegExp
Adobe AIR 1.0
JavaScript ActionScript Date RegExp,
. Date RegExp
,
.
, ActionScript JavaScript Date jsDate ActionScript Date:
var asDate:Date = new Date(jsDate.getMilliseconds());

ActionScript JavaScript RegExp jsRegExp RegExp


ActionScript:
var flags:String = "";
if (jsRegExp.dotAll) flags += "s";
if (jsRegExp.extended) flags += "x";
if (jsRegExp.global) flags += "g";
if (jsRegExp.ignoreCase) flags += "i";
if (jsRegExp.multiline) flags += "m";
var asRegExp:RegExp = new RegExp(jsRegExp.source, flags);

HTML ActionScript
Adobe AIR 1.0
HTMLLoader complete CSS-
.
, HTML-:

23.11.2012.

1071

ACTIONSCRIPT 3.0
HTML JavaScript AIR

<html>
<style>
.style1A { font-family:Arial; font-size:12px }
.style1B { font-family:Arial; font-size:24px }
</style>
<style>
.style2 { font-family:Arial; font-size:12px }
</style>
<body>
<p class="style1A">
Style 1A
</p>
<p class="style1B">
Style 1B
</p>
<p class="style2">
Style 2
</p>
</body>
</html>

HTMLLoader , CSS-
cssRules window.document.styleSheets, :
var html:HTMLLoader = new HTMLLoader( );
var urlReq:URLRequest = new URLRequest("test.html");
html.load(urlReq);
html.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var styleSheet0:Object = html.window.document.styleSheets[0];
styleSheet0.cssRules[0].style.fontSize = "32px";
styleSheet0.cssRules[1].style.color = "#FF0000";
var styleSheet1:Object = html.window.document.styleSheets[1];
styleSheet1.cssRules[0].style.color = "blue";
styleSheet1.cssRules[0].style.font-family = "Monaco";
}

CSS- , HTML-
:

, HTMLLoader complete,
.

23.11.2012.

1072

ACTIONSCRIPT 3.0
HTML JavaScript AIR

Adobe AIR 1.0


.

.

AIR JavaScript
Adobe AIR 1.0
AIR ,
.
. ,
,
. AIR
.

. ,
, , . ,
example.com
, example.com.
,
.
,
.
JavaScript ,
.

.
, ,
API- AIR,
AIR ,
.


.
, ,
, ( ).
, XMLHttpRequest
().

23.11.2012.

1073

ACTIONSCRIPT 3.0
HTML JavaScript AIR

. frame iframe HTML 1044,


HTML Adobe AIR 1164 XMLHttpRequest 1038.



Adobe AIR 1.0

, ,
, , frame
iframe. ,
,
http://localhost/
.
AIR frame sandboxRoot documentRoot, ,
, ,
. , URL- sandboxRoot,
documentRoot. , ,
, URL- sandboxRoot.
sandboxRoot URL- ,
. URL- file:, http: https:.
URL-
.
documentRoot , .
URL- file:, app: app-storage:.
, sandbox,
www.example.com:
<iframe
src="http://www.example.com/local/ui.html"
sandboxRoot="http://www.example.com/local/"
documentRoot="app:/sandbox/">
</iframe>

ui.html javascript sandbox :


<script src="http://www.example.com/local/ui.js"></script>

script,
:
<script src="http://www.example.com/remote/remote.js"></script>

URL sandboxRoot URL- .


www.example.com/local/ (
) , AIR .
, :
, XMLHttpRequest .

23.11.2012.

1074

ACTIONSCRIPT 3.0
HTML JavaScript AIR


Adobe AIR 1.0
,

,
. childSandboxBridge parentSandboxBridge
window .


Adobe AIR 1.0
childSandboxBridge
. childSandbox
.
. , ,
, :
var interface = {};
interface.calculatePrice = function(){
return ".45 cents";
}
interface.storeID = "abc"
window.childSandboxBridge = interface;

, id child,

childSandboxBridge:
var childInterface = document.getElementById("child").contentWindow.childSandboxBridge;
air.trace(childInterface.calculatePrice()); //traces ".45 cents"
air.trace(childInterface.storeID)); //traces "abc"


Adobe AIR 1.0
parentSandboxBridge
. parentSandbox
.
. ,
, , :
var interface = {};
interface.save = function(text){
var saveFile = air.File("app-storage:/save.txt");
//write text to file
}
document.getElementById("child").contentWindow.parentSandboxBridge = interface;

save.txt,
.
:

23.11.2012.

1075

ACTIONSCRIPT 3.0
HTML JavaScript AIR

var textToSave = "A string.";


window.parentSandboxBridge.save(textToSave);


. ,
.
,
.



Adobe AIR 1.0
,
, . window, frame iframe
dominitialize DOM , DOM. dominitialize
,
.
,
dominitialize, :
<html>
<head>
<script>
var bridgeInterface = {};
bridgeInterface.testProperty = "Bridge engaged";
function engageBridge(){
document.getElementById("sandbox").contentWindow.parentSandboxBridge = bridgeInterface;
}
</script>
</head>
<body>
<iframe id="sandbox"
src="http://www.example.com/air/child.html"
documentRoot="app:/"
sandboxRoot="http://www.example.com/air/"
ondominitialize="engageBridge()"/>
</body>
</html>

child.html ,
:
<html>
<head>
<script>
document.write(window.parentSandboxBridge.testProperty);
</script>
</head>
<body></body>
</html>

23.11.2012.

1076

ACTIONSCRIPT 3.0
HTML JavaScript AIR

dominitialize , ,
window, window.open():
var childWindow = window.open();
childWindow.addEventListener("dominitialize", engageBridge());
childWindow.document.location = "http://www.example.com/air/child.html";


. , child.html
. -
,
, ,
.
createRootWindow() HTMLLoader,
, createRootWindow().
,
, .
, .
, .

23.11.2012.

1077

1078

60.
HTML- AIR
Adobe AIR 1.0
HTMLLoader HTML Adobe AIR.
, Sprite,
ActionScript 3.0. , ,
HTML, .
HTMLHost HTMLLoader.
HTMLLoader HTMLHost . , HTML
,
, . HTMLHost
, .
HTMLHost HTML, AIR.
HTMLHost HTMLLoader, htmlHost
HTMLHost, defaultBehavior,
true.
. Adobe Flex Framework HTMLLoader mx:HTML.
Flex HTML.

HTMLLoader
Adobe AIR 1.0
HTMLLoader Sprite Adobe Flash Player. ,
, , .
: , , .
.
SWF PDF, HTML, .
HTML HTMLLoader, HTML.
, , ,
.


Adobe AIR 1.0
HTMLLoader
, , .
HTMLLoader HTML.
:

23.11.2012.

ACTIONSCRIPT 3.0
HTML- AIR

x, y

width, height

visible

HTML width height HTMLLoader 0.


, HTML. HTML
HTMLLoader HTML CSS .
HTMLLoader .
HTMLLoader ( width, 0)
width height HTMLLoader contentWidth
contentHeight. ,
HTML CSS.
- , HTMLLoader.
. HTMLLoader scaleX scaleY ,
.

HTMLLoader
Adobe AIR 1.0
paintsDefaultBackground HTMLLoader, true,
HTMLLoader. paintsDefaultBackground
false, . ,
HTMLLoader, HTML.
HTML (
style="background-color:gray", ), HTML
. opaqueBackground
HTMLLoader paintsDefaultBackground false, ,
opaqueBackground, .
. PNG
HTML . HTML .

HTMLLoader
Adobe AIR 1.0
HTMLLoader 1.0.
HTMLLoader HTMLLoader
. HTMLLoader,
, scaleMode Stage
StageScaleMode.NO_SCALE.

23.11.2012.

1079

ACTIONSCRIPT 3.0
HTML- AIR

SWF PDF HTML


Adobe AIR 1.0
SWF PDF, HTMLLoader, :

HTMLLoader 1.0.
alpha HTMLLoader , 1.0.
HTMLLoader.
.
, PDF .
SWF, HTML, wmode
opaque transparent. wmode
window, SWF
wmode.
. AIR 1.5.2 HTML SWF ,
wmode .
HTMLLoader . SWF HTML 1066 PDF- AIR
592.


Adobe AIR 1.0
HTMLLoader , .
, HTMLLoader ,
. ,
,
.
.
:

alpha

HTML

filters

HTML

graphics

, ,
HTML, .
paintsDefaultBackground false,
.

opaqueBackground

. paintsDefaultBackground
false, .

23.11.2012.

1080

ACTIONSCRIPT 3.0
HTML- AIR

rotation

HTMLLoader
. SWF PDF, HTML,
.

scaleX, scaleY


1. SWF PDF,
HTML, .

transform

HTML. HTML
. SWF PDF,
HTML, ,
, .

filters HTML:
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("http://www.adobe.com/");
html.load(urlReq);
html.width = 800;
html.height = 600;
var blur:BlurFilter = new BlurFilter(8);
var filters:Array = [blur];
html.filters = filters;

HTML
Adobe AIR 1.0
HTMLLoader ,
HTML:

contentHeight

HTML .

contentWidth

HTML .

scrollH

HTML HTMLLoader.

scrollV

HTML HTMLLoader.

scrollV , HTML
:

23.11.2012.

1081

ACTIONSCRIPT 3.0
HTML- AIR

var html:HTMLLoader = new HTMLLoader();


html.addEventListener(Event.HTML_BOUNDS_CHANGE, scrollHTML);
const SIZE:Number = 600;
html.width = SIZE;
html.height = SIZE;
var urlReq:URLRequest = new URLRequest("http://www.adobe.com");
html.load(urlReq);
this.addChild(html);
function scrollHTML(event:Event):void
{
html.scrollV = html.contentHeight - SIZE;
}

HTMLLoader .
ActionScript Flex. Flex HTML
HTML.
HTMLLoader.createRootWindow() , HTMLLoader
(. HTML 1094).

HTML
Adobe AIR 1.0
HTMLLoader .
window.history HTML. HTMLLoader
HTML:

historyLength

, .

historyPosition

.
, .

getHistoryAt()

URLRequest, .

historyBack()

, .

historyForward()

, .

historyGo()

.
, . 0
. .

HTMLHistoryItem. HTMLHistoryItem
:

23.11.2012.

1082

ACTIONSCRIPT 3.0
HTML- AIR

isPost

true, HTML POST.

originalUrl

URL- HTML .

title

HTML.

url

URL- HTML.


HTML
Adobe AIR 1.0
HTMLLoader userAgent,
HTMLLoader. userAgent HTMLLoader
load(). HTMLLoader, userAgent
URLRequest, load(), .
, HTMLLoader
, URLRequestDefaults.userAgent.
URLRequestDefaults URLRequest,
URLRequest, load() HTMLLoader. userAgent
HTMLLoader URLRequestDefaults.userAgent.
userAgent HTMLLoader,
URLRequestDefaults.userAgent, , AIR
. (, Mac OS Windows),
, :

"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko)


AdobeAIR/1.0"

"Mozilla/5.0 (Windows; U; en) AppleWebKit/420+ (KHTML, like Gecko) AdobeAIR/1.0"


HTML
Adobe AIR 1.0
HTML meta,
:
meta http-equiv="content-type" content="text/html" charset="ISO-8859-1";

, ,
textEncodingOverride HTMLLoader:

23.11.2012.

1083

ACTIONSCRIPT 3.0
HTML- AIR

var html:HTMLLoader = new HTMLLoader();


html.textEncodingOverride = "ISO-8859-1";

, HTML ,
HTMLLoader textEncodingFallback HTMLLoader:
var html:HTMLLoader = new HTMLLoader();
html.textEncodingFallback = "ISO-8859-1";

textEncodingOverride HTML.
textEncodingOverride HTML
textEncodingFallback.
textEncodingOverride textEncodingFallback
HTML.

,
,
HTML
Adobe AIR 1.0
JavaScript API- ,
HTML. AIR API-
HTMLHost.

HTMLHost
Adobe AIR 1.0
, , HTMLLoader ,
, HTML ,
. , , window.moveTo()
HTMLLoader ,
, HTMLLoader, - .
HTMLHost AIR JavaScript:

window.status

window.document.title

window.location

window.blur()

window.close()

window.focus()

window.moveBy()

window.moveTo()

window.open()

23.11.2012.

1084

ACTIONSCRIPT 3.0
HTML- AIR

window.resizeBy()

window.resizeTo()

HTMLLoader new HTMLLoader()


JavaScript . HTMLHost API- JavaScript
.
HTMLHost. HTMLHost, ,
defaultBehaviors true HTMLHost:
var defaultHost:HTMLHost = new HTMLHost(true);

HTML AIR createRootWindow() HTMLLoader


HTMLHost, , .
HTMLHost htmlHost
HTMLLoader null .
. AIR HTMLHost ,
AIR HTML, , JavaScript window.open() .

: HTMLHost
Adobe AIR 1.0
, HTMLLoader
HTMLHost:
Flex:
1 , HTMLHost ().
2 ,

. , , CustomHost,
window.open() window.document.title. window.open()
HTML , window.document.title (
<title> HTML) .

23.11.2012.

1085

ACTIONSCRIPT 3.0
HTML- AIR

package
{
import
import
import
import

flash.html.*;
flash.display.StageScaleMode;
flash.display.NativeWindow;
flash.display.NativeWindowInitOptions;

public class CustomHost extends HTMLHost


{
import flash.html.*;
override public function
createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader
{
var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
var bounds:Rectangle = new Rectangle(windowCreateOptions.x,
windowCreateOptions.y,
windowCreateOptions.width,
windowCreateOptions.height);
var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions,
windowCreateOptions.scrollBarsVisible, bounds);
htmlControl.htmlHost = new HTMLHostImplementation();
if(windowCreateOptions.fullscreen){
htmlControl.stage.displayState =
StageDisplayState.FULL_SCREEN_INTERACTIVE;
}
return htmlControl;
}
override public function updateTitle(title:String):void
{
htmlLoader.stage.nativeWindow.title = title;
}
}
}

3 , HTMLLoader ( HTMLHost),

. htmlHost HTMLLoader. Flex


CustomHost, :

23.11.2012.

1086

ACTIONSCRIPT 3.0
HTML- AIR

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
applicationComplete="init()">
<mx:Script>
<![CDATA[
import flash.html.HTMLLoader;
import CustomHost;
private function init():void
{
var html:HTMLLoader = new HTMLLoader();
html.width = container.width;
html.height = container.height;
var urlReq:URLRequest = new URLRequest("Test.html");
html.htmlHost = new CustomHost();
html.load(urlReq);
container.addChild(html);
}
]]>
</mx:Script>
<mx:UIComponent id="container" width="100%" height="100%"/>
</mx:WindowedApplication>

HTML :
<html>
<head>
<title>Test</title>
</head>
<script>
function openWindow()
{
window.runtime.trace("in");
document.title = "foo"
window.open('Test.html');
window.runtime.trace("out");
}
</script>
<body>
<a href="#" onclick="openWindow()">window.open('Test.html')</a>
</body>
</html>

Flash Professional.
1 Flash AIR. CustomHostExample
CustomHostExample.fla.
2 ActionScript CustomHost.as, , HTMLHost

(). ,
. , ,
CustomHost, window.open()
window.document.title. window.open() HTML ,
window.document.title ( <title> HTML)
.

23.11.2012.

1087

ACTIONSCRIPT 3.0
HTML- AIR

package
{
import
import
import
import
import
import
import
import
import
import

flash.display.StageScaleMode;
flash.display.NativeWindow;
flash.display.NativeWindowInitOptions;
flash.events.Event;
flash.events.NativeWindowBoundsEvent;
flash.geom.Rectangle;
flash.html.HTMLLoader;
flash.html.HTMLHost;
flash.html.HTMLWindowCreateOptions;
flash.text.TextField;

public class CustomHost extends HTMLHost


{
public var statusField:TextField;
public function CustomHost(defaultBehaviors:Boolean=true)
{
super(defaultBehaviors);
}
override public function windowClose():void
{
htmlLoader.stage.nativeWindow.close();
}
override public function createWindow(
windowCreateOptions:HTMLWindowCreateOptions ):HTMLLoader
{
var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
var bounds:Rectangle = new Rectangle(windowCreateOptions.x,
windowCreateOptions.y,
windowCreateOptions.width,
windowCreateOptions.height);
var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions,
windowCreateOptions.scrollBarsVisible, bounds);
htmlControl.htmlHost = new HTMLHostImplementation();
if(windowCreateOptions.fullscreen){
htmlControl.stage.displayState =
StageDisplayState.FULL_SCREEN_INTERACTIVE;
}
return htmlControl;
}
override public function updateLocation(locationURL:String):void
{
trace(locationURL);
}
override public function set windowRect(value:Rectangle):void
{
htmlLoader.stage.nativeWindow.bounds = value;

23.11.2012.

1088

ACTIONSCRIPT 3.0
HTML- AIR

}
override public function updateStatus(status:String):void
{
statusField.text = status;
trace(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;
}
}
}

3 ActionScript CustomHostExample.as,

. HTMLLoader host
CustomHost, :

23.11.2012.

1089

ACTIONSCRIPT 3.0
HTML- AIR

package
{
import
import
import
import

flash.display.Sprite;
flash.html.HTMLLoader;
flash.net.URLRequest;
flash.text.TextField;

public class CustomHostExample extends Sprite


{
function CustomHostExample():void
{
var html:HTMLLoader = new HTMLLoader();
html.width = 550;
html.height = 380;
var host:CustomHost = new CustomHost();
html.htmlHost = host;
var urlReq:URLRequest = new URLRequest("Test.html");
html.load(urlReq);
addChild(html);
var statusTxt:TextField = new TextField();
statusTxt.y = 380;
statusTxt.height = 20;
statusTxt.width = 550;
statusTxt.background = true;
statusTxt.backgroundColor = 0xEEEEEEEE;
addChild(statusTxt);
host.statusField = statusTxt;
}
}
}

HTML
:

23.11.2012.

1090

ACTIONSCRIPT 3.0
HTML- AIR

<html>
<head>
<title>Test</title>
<script>
function openWindow()
{
document.title = "Test"
window.open('Test.html');
}
</script>
</head>
<body bgColor="#EEEEEE">
<a href="#" onclick="window.open('Test.html')">window.open('Test.html')</a>
<br/><a href="#" onclick="window.document.location='http://www.adobe.com'">
window.document.location = 'http://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>

window.location
Adobe AIR 1.0
locationChange() URL- HTML.
locationChange() , JavaScript
window.location. URL-:
override public function updateLocation(locationURL:String):void
{
htmlLoader.load(new URLRequest(locationURL));
}

. htmlLoader HTMLHost
HTMLLoader.

JavaScript window.moveBy(),
window.moveTo(), window.resizeTo(), window.resizeBy()
Adobe AIR 1.0
set windowRect() HTML. set
windowRect() , JavaScript window.moveBy(),
window.moveTo(), window.resizeTo() window.resizeBy().
:
override public function set windowRect(value:Rectangle):void
{
htmlLoader.stage.nativeWindow.bounds = value;
}

23.11.2012.

1091

ACTIONSCRIPT 3.0
HTML- AIR

JavaScript window.open()
Adobe AIR 1.0
createWindow() JavaScript window.open().
createWindow() HTMLLoader.
, HTMLLoader , .
createWindow()
HTMLLoader.createRootWindow() , HTMLLoader.
NativeWindow HTMLLoader .
override public function createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader{
var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
var bounds:Rectangle = new Rectangle(windowCreateOptions.x, windowCreateOptions.y,
windowCreateOptions.width, windowCreateOptions.height);
var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions,
windowCreateOptions.scrollBarsVisible, bounds);
htmlControl.htmlHost = new HTMLHostImplementation();
if(windowCreateOptions.fullscreen){
htmlControl.stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
}
return htmlControl;
}

. HTMLHost ,
window.open().
htmlHost null , .
, createWindow()
HTMLWindowCreateOptions. HTMLWindowCreateOptions , ,
features window.open():

HTMLWindowCreateOptions


features
JavaScript
window.open()

fullscreen

fullscreen

height

height

locationBarVisible

location

menuBarVisible

menubar

resizeable

resizable

scrollBarsVisible

scrollbars

statusBarVisible

status

toolBarVisible

toolbar

width

width

left screenX

top screenY

23.11.2012.

1092

ACTIONSCRIPT 3.0
HTML- AIR

HTMLLoader , feature.
, , ,
.
window.open() JavaScript .
createWindow() HTMLLoader .

JavaScript window.close()
Adobe AIR 1.0
windowClose() JavaScript window.close().
window.close():
override public function windowClose():void
{
htmlLoader.stage.nativeWindow.close();
}

JavaScript window.close() . ,
, HTMLLoader , (,
) , :
override public function windowClose():void
{
htmlLoader.parent.removeChild(htmlLoader);
}

window.status
Adobe AIR 1.0
updateStatus() JavaScript window.status.
:
override public function updateStatus(status:String):void
{
trace(status);
}

updateStatus().
HTMLLoader .

window.document.title
Adobe AIR 1.0
updateTitle() JavaScript
window.document.title.
Sample:
override public function updateTitle(title:String):void
{
htmlLoader.stage.nativeWindow.title = title + " - Sample";
}

23.11.2012.

1093

ACTIONSCRIPT 3.0
HTML- AIR

document.title HTML,
updateTitle().
document.title ,
HTMLLoader. , .

JavaScript window.blur()
window.focus()
Adobe AIR 1.0
windowBlur() windowFocus() JavaScript
window.blur() window.focus(), :
override public function windowBlur():void
{
htmlLoader.alpha = 0.5;
}
override public function windowFocus():void
{
htmlLoader.alpha = 1.0;
NativeApplication.nativeApplication.activate(htmlLoader.stage.nativeWindow);
}

. AIR API- .

HTML
Adobe AIR 1.0
HTMLLoader , HTMLLoader.createRootWindow(),
( NativeWindow), HTMLLoader,
.
, :

visible

, , (true) (false).

windowInitOptions

NativeWindowInitOptions. NativeWindowInitOptions
NativeWindow, : ,
, ,
( , ), .

scrollBarsVisible

(true) (false).

bounds

Rectangle, .

, HTMLLoader.createRootWindow()
HTMLLoader :
var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
var bounds:Rectangle = new Rectangle(10, 10, 600, 400);
var html2:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions, true, bounds);
var urlReq2:URLRequest = new URLRequest("http://www.example.com");
html2.load(urlReq2);
html2.stage.nativeWindow.activate();

23.11.2012.

1094

ACTIONSCRIPT 3.0
HTML- AIR

. , createRootWindow() JavaScript,
HTML. JavaScript Window opener parent, ,
null. createRootWindow()
HTMLHost createWindow() createRootWindow() opener parent
HTML.

HTMLLoader
Adobe AIR 1.0
HTMLLoader . ,
, HTMLLoader (,
HTML ).
HTMLHost normal
JavaScript window.open(). HTMLLoader,
HTMLHost:
package
{
import flash.html.HTMLLoader;
public class MyHTMLHost extends HTMLHost
{
public function MyHTMLHost()
{
super(false);
}
override public function createWindow(opts:HTMLWindowCreateOptions):void
{
var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
var bounds:Rectangle = new Rectangle(opts.x, opts.y, opts.width, opts.height);
var html:HTMLLoader = HTMLLoader.createRootWindow(true,
initOptions,
opts.scrollBarsVisible,
bounds);
html.stage.nativeWindow.orderToFront();
return html
}
}

HTMLLoader, MyHTMLHost
htmlHost:

23.11.2012.

1095

ACTIONSCRIPT 3.0
HTML- AIR

package
{
import flash.html.HTMLLoader;
import MyHTMLHost;
import HTMLLoader;
public class MyHTML extends HTMLLoader
{
public function MyHTML()
{
super();
htmlHost = new MyHTMLHost();
}
}
}

HTMLHost HTMLLoader.createRootWindow(),
, . ,
, HTML 1084.

23.11.2012.

1096

1097

61. AIR
HTML
Adobe AIR 1.0

. Adobe AIR , .
, DOM 3-
, ,
.

HTMLLoader
Adobe AIR 1.0
HTMLLoader Adobe ActionScript 3.0:

htmlDOMInitialize

HTML-, -
DOM.

complete

DOM HTML ,
onload HTML-.

htmlBoundsChanged

contentWidth
contentHeight .

locationChange

location HTMLLoader.

locationChanging

HTMLLoader
, JavaScript .
locationChanging load(),
loadString(), reload(), historyGo(), historyForward()
historyBack().
preventDefault()
.
, locationChanging
, HTMLLoader .

scroll

HTML.
scroll (
#) window.scrollTo().
scroll.

uncaughtScriptException

HTMLLoader JavaScript,
JavaScript.

ActionScript JavaScript (, onClick).


. DOM ActionScript 1098.

23.11.2012.

ACTIONSCRIPT 3.0
AIR HTML

DOM ActionScript
Adobe AIR 1.0
ActionScript JavaScript. ,
HTML-:
<html>
<body>
<a href="#" id="testLink">Click me.</a>
</html>

ActionScript
. , clickHandler() HTML-
onclick testLink:
var html:HTMLLoader = new HTMLLoader( );
var urlReq:URLRequest = new URLRequest("test.html");
html.load(urlReq);
html.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
html.window.document.getElementById("testLink").onclick = clickHandler;
}
function clickHandler( event:Object ):void {
trace("Event of type: " + event.type );
}

flash.events.Event Event.
Object .
addEventListener().
, completeHandler() :
function completeHandler(event:Event):void {
var testLink:Object = html.window.document.getElementById("testLink");
testLink.addEventListener("click", clickHandler);
}

- DOM, ,
HTMLLoader complete,
. HTML- , DOM HTML
, . HTMLLoader
complete, .

JavaScript
Adobe AIR 1.0
HTML-:

23.11.2012.

1098

ACTIONSCRIPT 3.0
AIR HTML

<html>
<head>
<script>
function throwError() {
var x = 400 * melbaToast;
}
</script>
</head>
<body>
<a href="#" onclick="throwError()">Click me.</a>
</html>

JavaScript throwError(), melbaToast:


var x = 400 * melbaToast;

JavaScript , JavaScript
try/catch, HTMLLoader, ,
HTMLUncaughtScriptExceptionEvent. ,
:
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("test.html");
html.load(urlReq);
html.width = container.width;
html.height = container.height;
container.addChild(html);
html.addEventListener(HTMLUncaughtScriptExceptionEvent.UNCAUGHT_SCRIPT_EXCEPTION,
htmlErrorHandler);
function htmlErrorHandler(event:HTMLUncaughtJavaScriptExceptionEvent):void
{
event.preventDefault();
trace("exceptionValue:", event.exceptionValue)
for (var i:int = 0; i < event.stackTrace.length; i++)
{
trace("sourceURL:", event.stackTrace[i].sourceURL);
trace("line:", event.stackTrace[i].line);
trace("function:", event.stackTrace[i].functionName);
}
}

JavaScript window.htmlLoader:

23.11.2012.

1099

ACTIONSCRIPT 3.0
AIR HTML

<html>
<head>
<script language="javascript" type="text/javascript" src="AIRAliases.js"></script>
<script>
function throwError() {
var x = 400 * melbaToast;
}
function htmlErrorHandler(event) {
event.preventDefault();
var message = "exceptionValue:" + event.exceptionValue + "\n";
for (var i = 0; i < event.stackTrace.length; i++){
message += "sourceURL:" + event.stackTrace[i].sourceURL +"\n";
message += "line:" + event.stackTrace[i].line +"\n";
message += "function:" + event.stackTrace[i].functionName + "\n";
}
alert(message);
}
window.htmlLoader.addEventListener("uncaughtScriptException", htmlErrorHandler);
</script>
</head>
<body>
<a href="#" onclick="throwError()">Click me.</a>
</html>

htmlErrorHandler() (. .
JavaScript AIR)
. exceptionValue HTMLUncaughtScriptExceptionEvent.
stackTrace:
exceptionValue: ReferenceError: Can't find variable: melbaToast
sourceURL: app:/test.html
line: 5
function: throwError
sourceURL: app:/test.html
line: 10
function: onclick


JavaScript
Adobe AIR 1.0
addEventListener().
addEventListener() ,
, . ,
closing, ,
:
window.nativeWindow.addEventListener(air.NativeWindow.CLOSING, handleWindowClosing);

23.11.2012.

1100

ACTIONSCRIPT 3.0
AIR HTML


Adobe AIR 1.0
, HTML-,
. moveHandler() move (
NativeWindowBoundsEvent) .
<html>
<script src="AIRAliases.js" />
<script>
function init() {
writeValues();
window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.MOVE,
moveHandler);
}
function writeValues() {
document.getElementById("xText").value = window.nativeWindow.x;
document.getElementById("yText").value = window.nativeWindow.y;
}
function moveHandler(event) {
air.trace(event.type); // move
writeValues();
}
</script>
<body onload="init()" />
<table>
<tr>
<td>Window X:</td>
<td><textarea id="xText"></textarea></td>
</tr>
<tr>
<td>Window Y:</td>
<td><textarea id="yText"></textarea></td>
</tr>
</table>
</body>
</html>

, textarea X Y
:
, moveHandler() .
. type
, move.


Adobe AIR 1.0
removeEventListener()
. .
eventName listener addEventListener().

23.11.2012.

1101

ACTIONSCRIPT 3.0
AIR HTML

HTML-
Adobe AIR 1.0
HTML- -
, ,
. ,
: JavaScript HTML-,
.
, JavaScript HTML-,
. ( HTMLLoader)
unload window.
, JavaScript uncaughtScriptException:
window.onunload = cleanup;
window.htmlLoader.addEventListener('uncaughtScriptException', uncaughtScriptException);
function cleanup()
{
window.htmlLoader.removeEventListener('uncaughtScriptException',
uncaughtScriptExceptionHandler);
}

HTML-, cleanup
closing NativeWindow (window.nativeWindow). ,
JavaScript uncaughtScriptException:
window.nativeWindow.addEventListener(air.Event.CLOSING, cleanup);
function cleanup()
{
window.htmlLoader.removeEventListener('uncaughtScriptException',
uncaughtScriptExceptionHandler);
}

,
( ). , JavaScript HTML
createRootWindow() HTMLLoader
complete. complete
removeEventListener():
var html = runtime.flash.html.HTMLLoader.createRootWindow(true);
html.addEventListener('complete', htmlCompleteListener);
function htmlCompleteListener()
{
html.removeEventListener(complete, arguments.callee)
// handler code..
}
html.load(new runtime.flash.net.URLRequest("second.html"));


, .


Adobe AIR 1.0
hasEventListener() , .

23.11.2012.

1102

1103

62. HTML

Adobe AIR 2.5


StageWebView HTML-
Adobe AIR HTMLLoader
. StageWebView.isSupported, ,
. .
StageWebView
HTML- . ,
.
URL, HTML.

StageWebView
StageWebView .
, .
StageWebView .
StageWebView .
StageWebView, stage StageWebView,
, . viewPort .
viewPort x y -8192 8191.
8191. ,
.
StageWebView, stage viewPort HTML:
var webView:StageWebView = new StageWebView();
webView.viewPort = new Rectangle( 0, 0, this.stage.stageWidth, this .stage.stageHeight);
webView.stage = this.stage;
var htmlString:String = "<!DOCTYPE HTML>" +
"<html><body>" +
"<p>King Philip could order five good steaks.</p>" +
"</body></html>";
webView.loadString( htmlString );

StageWebView, stage null.


dispose(). dispose() ,
, .

23.11.2012.

1104

ACTIONSCRIPT 3.0
HTML-

StageWebView : loadURL() loadString().


loadURL() URL. URI,
, : data:, file:, http:, https:, javascript:.
app: app-storage: . AIR URL.
loadString() , HTML-.
, , :

: about:blank
iOS: htmlString
Android: URI htmlString
URI .
URI

Local XMLHttpRequest

Remote XMLHttpRequest

data:

file:

http:, https:

about: (loadString()
method)

. displayState FULL_SCREEN,
,
StageWebView. iOS Android StageWebView ,
displayState FULL_SCREEN.
StageWebView - Adobe.
package {
import flash.display.MovieClip;
import flash.media.StageWebView;
import flash.geom.Rectangle;
public class StageWebViewExample extends MovieClip{
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.adobe.com" );
}
}
}

Android Android INTERNET,


.

23.11.2012.

ACTIONSCRIPT 3.0
HTML-

Android 3.0
manifestAdditions Android AIR
StageWebView. . Flash Player
StageWebView.

JavaScript URI
JavaScript URI , HTML,
StageWebView. , JavaScript URI,
-. StageWebView
JavaScript:
package {
import flash.display.*;
import flash.geom.Rectangle;
import flash.media.StageWebView;
public class WebView extends Sprite
{
public var webView:StageWebView = new StageWebView();
public function WebView()
{
var htmlString:String = "<!DOCTYPE HTML>" +
"<html><script type=text/javascript>" +
"function callURI(){" +
"alert(\"You clicked me!!\");"+
"}</script><body>" +
"<p><a href=javascript:callURI()>Click Me</a></p>" +
"</body></html>";
webView.stage = this.stage;
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight );
webView.loadString( htmlString );
}
}
}


(Sean Voisen): StageWebView


HTML, StageWebView
locationChanging. preventDefault() ,
. StageWebView
locationChange. StageWebView complete.
locationChanging HTML.
locationChange complete .
iOS locationChanging locationChange,
loadURL() loadString(). locationChange

23.11.2012.

1105

ACTIONSCRIPT 3.0
HTML-

,
.
package {
import
import
import
import
import
import

flash.display.MovieClip;
flash.media.StageWebView;
flash.events.LocationChangeEvent;
flash.geom.Rectangle;
flash.net.navigateToURL;
flash.net.URLRequest;

public class StageWebViewNavEvents extends MovieClip{


var webView:StageWebView = new StageWebView();
public function StageWebViewNavEvents() {
webView.stage = this.stage;
webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight );
webView.addEventListener( LocationChangeEvent.LOCATION_CHANGING, onLocationChanging );
webView.loadURL( "http://www.adobe.com" );
}
private function onLocationChanging( event:LocationChangeEvent ):void
{
event.preventDefault();
navigateToURL( new URLRequest( event.location ) );
}
}
}

, StageWebView,
.
.
.

23.11.2012.

1106

ACTIONSCRIPT 3.0
HTML-

package {
import
import
import
import
import

flash.display.MovieClip;
flash.media.StageWebView;
flash.geom.Rectangle;
flash.events.KeyboardEvent;
flash.ui.Keyboard;

public class StageWebViewExample extends MovieClip{


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.adobe.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();
}
}
}
}

StageWebView , ,
.
StageWebView , focusIn.
, .
StageWebView , focusOut. StageWebView
,
- . direction
,
. ,
StageWebView.

23.11.2012.

1107

ACTIONSCRIPT 3.0
HTML-

iOS . StageWebView focusIn focusOut


FocusEvent, none.
StageWebView, focusIn.
StageWebView, focusOut.
StageWebView Flash:
package {
import
import
import
import
import
import
import
import
import
import

flash.display.MovieClip;
flash.media.StageWebView;
flash.geom.Rectangle;
flash.events.KeyboardEvent;
flash.ui.Keyboard;
flash.text.TextField;
flash.text.TextFieldType;
flash.events.FocusEvent;
flash.display.FocusDirection;
flash.events.LocationChangeEvent;

public class StageWebViewFocusEvents extends MovieClip{


var webView:StageWebView = new StageWebView();
var topControl:TextField = new TextField();
var bottomControl:TextField = new TextField();
public function StageWebViewFocusEvents()
{
trace("Starting");
topControl.type = TextFieldType.INPUT;
addChild( topControl );
topControl.height = 60;
topControl.width = stage.stageWidth;
topControl.background = true;
topControl.text = "One control on top.";
topControl.addEventListener( FocusEvent.FOCUS_IN, flashFocusIn );
topControl.addEventListener( FocusEvent.FOCUS_OUT, flashFocusOut );
webView.stage = this.stage;
webView.viewPort = new Rectangle( 0, 60, stage.stageWidth, stage.stageHeight
- 120 );
webView.addEventListener( FocusEvent.FOCUS_IN, webFocusIn );
webView.addEventListener(FocusEvent.FOCUS_OUT, webFocusOut );
webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING,
function( event:LocationChangeEvent ):void
{
event.preventDefault();
} );
webView.loadString("<form action='#'><input/><input/><input/></form>");
webView.assignFocus();
bottomControl.type = TextFieldType.INPUT;
addChild( bottomControl );
bottomControl.y = stage.stageHeight - 60;
bottomControl.height = 60;
bottomControl.width = stage.stageWidth;
bottomControl.background = true;
bottomControl.text = "One control on the bottom.";
bottomControl.addEventListener( FocusEvent.FOCUS_IN, flashFocusIn );

23.11.2012.

1108

ACTIONSCRIPT 3.0
HTML-

bottomControl.addEventListener( FocusEvent.FOCUS_OUT, flashFocusOut );}


private function webFocusIn( event:FocusEvent ):void
{
trace("Web focus in");
}
private function webFocusOut( event:FocusEvent ):void
{
trace("Web focus out: " + event.direction);
if( event.direction == FocusDirection.TOP )
{
stage.focus = topControl;
}
else
{
stage.focus = bottomControl;
}
}
private function flashFocusIn( event:FocusEvent ):void
{
trace("Flash focus in");
var textfield:TextField = event.target as TextField;
textfield.backgroundColor = 0xff5566;
}
private function flashFocusOut( event:FocusEvent ):void
{
trace("Flash focus out");
var textfield:TextField = event.target as TextField;
textfield.backgroundColor = 0xffffff;
}
}
}


StageWebView .
StageWebView. ,
StageWebView. StageWebView.
StageWebView .
StageWebView
drawViewPortToBitmapData. StageWebView,
null. - , ,
. : Google Facebook.
-
.

23.11.2012.

1109

ACTIONSCRIPT 3.0
HTML-

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 stagewebview 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);
}
}
}

23.11.2012.

1110

1111

63.
worker
Flash Player 11.4 , Adobe AIR 13.4
worker ActionScript , , ,
.
API- ActionScript Flash Player 11.4
AIR 3.4 . AIR
.

worker
Flash Player 11.4 , Adobe AIR 13.4
worker, ,
. , . ,
, , ,
, .
, ,
. ,
.
1 : enterFrame

.
2 : ,

,
3 : XML URL

. , , XML
XML.
4 : ,


5 : , ,

,
6 :

, 1-5 ,
. ,
. 30
.
,
. , XML, 3,

23.11.2012.

ACTIONSCRIPT 3.0
worker

. XML
, , .
( ) .
,
.
,
. ,
. worker ActionScript .
worker . worker
, worker .
worker :
.
.
worker ,
worker. ,
,
.
worker ,
. worker
,
. worker
, worker
. worker ,
, . Adobe
worker .

worker
Flash Player 11.4 , Adobe AIR 13.4
worker
worker. worker . -, Worker,
. -, WorkerDomain,
Worker Worker .
, WorkerDomain.
worker SWF- . worker
worker.
WorkerDomain, WorkerDomain
WorkerDomain.current.
Worker ( worker,
), Worker.current.

23.11.2012.

1112

ACTIONSCRIPT 3.0
worker

Worker SWF-
SWF worker, worker
SWF-. worker,
worker SWF-. worker, worker
SWF- ByteArray. ByteArray
createWorker() WorkerDomain worker.
SWF worker ByteArray .

SWF worker
[Embed] SWF worker SWF-
ByteArray.
[Embed(source="../swfs/BgWorker.swf", mimeType="application/octet-stream")]
private static var BgWorker_ByteClass:Class;
private function createWorker():void
{
var workerBytes:ByteArray = new BgWorker_ByteClass();
var bgWorker:Worker = WorkerDomain.current.createWorker(workerBytes);
// ... set up worker communication and start the worker
}

SWF worker SWF ByteArray BgWorker_ByteClass.


ByteArray,
SWF- worker.

SWF- worker
URLLoader SWF . SWF-
, SWF-, -, SWF, AIR.
var workerLoader:URLLoader = new URLLoader();
workerLoader.dataFormat = URLLoaderDataFormat.BINARY;
workerLoader.addEventListener(Event.COMPLETE, loadComplete);
workerLoader.load(new URLRequest("BgWorker.swf"));
private function loadComplete(event:Event):void
{
// create the background worker
var workerBytes:ByteArray = event.target.data as ByteArray;
var bgWorker:Worker = WorkerDomain.current.createWorker(workerBytes);
// ... set up worker communication and start the worker
}

URLLoader SWF-, SWF data


URLLoader (event.target.data ).

SWF SWF worker


SWF- SWF, SWF worker.
loaderInfo.bytes SWF.

23.11.2012.

1113

ACTIONSCRIPT 3.0
worker

// The primordial worker's main class constructor


public function PrimordialWorkerClass()
{
init();
}
private function init():void
{
var swfBytes:ByteArray = this.loaderInfo.bytes;
// Check to see if this is the primordial worker or the background worker
if (Worker.current.isPrimordial)
{
// create a background worker
var bgWorker:Worker = WorkerDomain.current.createWorker(swfBytes);
// ... set up worker communication and start the worker
}
else // entry point for the background worker
{
// set up communication between workers using getSharedProperty()
// ... (not shown)
// start the background work
}
}

, if, SWF-
, . ,
worker , isPrimordial Worker, .

worker
worker start()
Worker. start() . , worker,
workerState Worker. ,
Worker , ,
. workerState , state Worker
WorkerState.RUNNING. worker
. workerState
start().
// listen for worker state changes to know when the worker is running
bgWorker.addEventListener(Event.WORKER_STATE, workerStateHandler);
// set up communication between workers using
// setSharedProperty(), createMessageChannel(), etc.
// ... (not shown)
bgWorker.start();
private function workerStateHandler(event:Event):void
{
if (bgWorker.state == WorkerState.RUNNING)
{
// The worker is running.
// Send it a message or wait for a response.
}
}

23.11.2012.

1114

1115

ACTIONSCRIPT 3.0
worker

worker
worker
listWorkers() WorkerDomain. worker,
state WorkerState.RUNNING, worker.
worker , .
worker , terminate() Worker,
worker .

worker
Flash Player 11.4 , Adobe AIR 13.4
worker , ,
. worker, ,
.
worker .
, ,
, .
.
- .
. worker
, , ,
. worker
, ,
. :

worker
?


worker

, ,

MessageChannel

, ,

ByteArray


worker
. worker .
, .
worker , setSharedProperty() Worker
( ).
// code running in the parent worker
bgWorker.setSharedProperty("sharedPropertyName", someObject);

23.11.2012.

ACTIONSCRIPT 3.0
worker

, getSharedProperty()
Worker, .
// code running in the background worker
receivedProperty = Worker.current.getSharedProperty("sharedPropertyName");

, worker . ,
worker setSharedProperty() .
, worker, getSharedProperty()
.
, setSharedProperty(), .
getSharedProperty(), ,
setSharedProperty(), , .
1118.

worker , worker.
setSharedProperty() Worker, worker.
worker start() Worker,
worker. ,
start(), worker.

MessageChannel
worker.
MessageChannel
. () ,
MessageChannel channelMessage. - worker
. - worker
.
worker: .
MessageChannel, createMessageChannel() - Worker,
- worker.
// In the sending worker swf
var sendChannel:MessageChannel;
sendChannel = Worker.current.createMessageChannel(receivingWorker);

worker MessageChannel.
MessageChannel setSharedProperty().
receivingWorker.setSharedProperty("incomingChannel", sendChannel);

- worker channelMessage
MessageChannel. , - worker
.
// In the receiving worker swf
var incomingChannel:MessageChannel;
incomingChannel = Worker.current.getSharedProperty("incomingChannel");
incomingChannel.addEventListener(Event.CHANNEL_MESSAGE, handleIncomingMessage);

, - worker send() MessageChannel.

23.11.2012.

1116

ACTIONSCRIPT 3.0
worker

// In the sending worker swf


sendChannel.send("This is a message");

- worker MessageChannel channelMessage.


- worker , receive() .
private function handleIncomingMessage(event:Event):void
{
var message:String = incomingChannel.receive() as String;
}

, , , ,
send(). , ,
- worker, ,
1118.

ByteArray
worker , ,
. . ,
, ,
. ,
, .
1118.
ByteArray . ByteArray
setSharedProperty() Worker send() MessageChannel
ByteArray,
. ByteArray , shareable
true.
ByteArray worker , ByteArray,
, ByteArray worker.
worker ,
, .
worker , worker
.
.
, .
ByteArray :

atomicCompareAndSwapIntAt();
atomicCompareAndSwapLength().
, flash.concurrent ,
:

Mutex;
Condition.

23.11.2012.

1117

ACTIONSCRIPT 3.0
worker


Worker.setSharedProperty() MessageChannel.send()
- worker AMF.
.

, - worker
getSharedProperty(), AMF. ,
. , worker,
worker.

, AMF, ,
worker Worker.setSharedProperty() MessageChannel.send().

,
flash.net.registerClassAlias()
[RemoteClass]. worker .
, ,
worker:

Worker;
MessageChannel;
( ByteArray, shareable true);
Mutex;
Condition.
Worker.setSharedProperty()
MessageChannel.send(), worker . ,
worker, worker. ,
worker ,
- worker.
.


, worker,
worker API, SWF-, :

,
worker worker,
SQLite.
worker,
worker . , ,
worker ,
. .
Mutex Condition
flash.concurrent, .

23.11.2012.

1118

ACTIONSCRIPT 3.0
worker

, SQLite
.
worker SQLite .
worker SQLConnection,
. .
.
SQL AIR 767
flash.concurrent

23.11.2012.

1119

1120

64.
Flash Player 9 , Adobe AIR 1.0
Adobe, , -
. Adobe Flash Player Adobe AIR
, , . SWF-,
ActionScript 3.0 Flash Player 9.0.124.0
, SWF, HTML JavaScript, AIR 1.0
, .
.
, API-.
Flash Player . Flash Player
Developer Center www.adobe.com/go/devnet_security_ru.

Flash
Flash Player 9 , Adobe AIR 1.0
, Flash Player AIR,
SWF-, HTML, .
-, www.example.com,
. ,
. ( .
1122.)
, ActionScript SWF- SWF-, , ,
. ,
SWF- , ActionScript 3.0.
,
, .
,
ActionScript 3.0, , ActionScript.
LocalConnection. ,
SWF- ActionScript 3.0, .
, Security.allowDomain() SWF-.
. 1144.
, .

, , .

.

23.11.2012.

ACTIONSCRIPT 3.0

Flash Player AIR


:

http://example.com

http://www.example.com

http://store.example.com

https://www.example.com

http://192.0.34.166

, http://example.com, IP-,
http://192.0.34.166, .
, SWF-
:

Security.allowDomain() (. ()
1135);

URL- (. - ( )
1131).
Flash Player AIR
. ,
, , , , SWF HTML . ,
-.

, Loader, Sound NetStream;


MXML Flex; HTML AIR.


Bitmap, BitmapData.draw() BitmapData.drawWithQuality(), Sound.id3
SoundMixer.computeSpectrum(). drawWithQuality Flash Player 11.3 AIR 3.3
.

(, XML) , URLStream, URLLoader, FileReference, Socket XMLSocket. AIR


, FileStream XMLHttpRequest.
Flash Player
. , ,
.
, (SWF-, , mp3- )
, ,
, .
.

SWF- ( ,
) , .
. .
1123.

23.11.2012.

1121

ACTIONSCRIPT 3.0

RTMP (Real-Time Messaging Protocol) .


. , RTMP
1144.
, - ,
, , SWF-
, SWF- URL-
. .
1148.
XML-,
URLLoader.
URL- .
. URLLoader URLStream
1151.
. ,
AIR.


Flash Player 9 , Adobe AIR 1.0
, , ,
, -, AIR.
Flash Player AIR
, , , , ,
, .
, ,
.
Flash Player . Flash Player
Developer Center www.adobe.com/go/devnet_security_ru.


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR , ( SWF),
. , , example.com foo.org
.
, . SWF-
- , ,
URL- Security.allowDomain(). .
- ( ) 1131
() 1135.
SWF- .

23.11.2012.

1122

ACTIONSCRIPT 3.0

Flash Player . Flash Player


Developer Center www.adobe.com/go/devnet_security_ru.


Flash Player 9 , Adobe AIR 1.0
, file:
UNC (Universal Naming Convention ). SWF-
.

:
Flash Player AIR .
(,
URLLoader), .
.

: SWF-
, , (.
SWF- 1126).
.
SWF-, ,
. . SWF-

, URL Security.allowDomain(). ,
URL- <allowaccess-from domain="*"/> Security.allowDomain("*"). .
- ( ) 1131
() 1135.

: SWF-,
( ).
()
SWF-
(. 1128
1129). SWF-,
, SWF ( ).

AIR:
, AIR. ,
AIR
. ,
AIR, .
AIR
.

,
.
,
Flash Player, , .

23.11.2012.

1123

ACTIONSCRIPT 3.0

HTML- SWF, , ExternalInterface, , (HTML SWF)


. ,
Flash Player.
SWF-
SWF- . SWF-
SWF-
.

AIR
Adobe AIR 1.0
Adobe AIR ,
Flash Player. ,
AIR, .
, , ,
Flash Player.
, AIR,
. URL
app:/ (. URI 873).
.
, AIR,
.
AIR
. AIR
. ,
, ,
. ; HTML-
, SWF- .
API-
AIR, . ,
air.NativeApplication.nativeApplication.applicationDescriptor,
,
. API-
FileStream, .
API- ActionScript,
, AIR c ActionScript 3.0
Adobe Flash Platform. API-
SecurityError.
HTML ( HTMLLoader) JavaScript API- AIR (
window.runtime air AIRAliases.js)
. HTML
window.runtime,
API- Flash Player.

23.11.2012.

1124

ACTIONSCRIPT 3.0

, AIR,
.

HTML
API-,
. ( )
, (, ).
eval(). .

1167.

img HTML TextField


ActionScript SWF,
.


asfunction HTML ActionScript 2.0.

SWF
, Flash Player 9 3.
Flash Player Adobe
SWF ( ).

JavaScript AIR
Adobe AIR 1.0

JavaScript eval()
.
JavaScript, AIR.
:

JavaScript ,
, window.runtime,
API- AIR.

,
, XMLHttpRequest ,
, . ,
, , allowCrossdomainXHR . .
1167.

JavaScript window.open(). .
JavaScript window.open() 1170.

HTML remote ()
CSS, frame, iframe img ( URL-).

HTML ,

CSS, frame, iframe img
( URL-).

23.11.2012.

1125

ACTIONSCRIPT 3.0

.
1167.

SWF
Flash Player 9 , Adobe AIR 1.0
SWF-
, , .
Global Flash Player Trust
User Flash Player Trust. .
1128 1129.
.
1123.
Adobe Flash Professional
SWF-
,
.

Adobe Flex
SWF-
, usenetwork Adobe Flex. .
Adobe Flex 3.

Security.sandboxType
Flash Player 9 , Adobe AIR 1.0
SWF- Security.sandboxType,
, ,
Flash Player AIR SWF-. Security ,
Security.sandboxType, .

Security.REMOTE: SWF-

Security.LOCAL_WITH_FILE: SWF- ,

. SWF-
, .

Security.LOCAL_WITH_NETWORK: SWF- ,

, . SWF-
, .

23.11.2012.

1126

ACTIONSCRIPT 3.0

Security.LOCAL_TRUSTED: SWF- ,
Flash Player. SWF-

.

Security.APPLICATION: SWF- AIR ( AIR)


. AIR
. ,
AIR,
AIR. AIR
.


Flash Player 9 , Adobe AIR 1.0
Flash Player ,
, SWF-, URL- .
, .
( )
. .
Flash Player ,
.

( )

, , ,
.
AIR ,
AIR.

23.11.2012.

1127

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
( ,
) Flash Player,
. , ,
.
.
:

mms.cfg
Global Flash Player Trust

mms.cfg
Flash Player 9 , Adobe AIR 1.0
mms.cfg ,
. Flash Player
. mms.cfg ,
,
, , .
SWF-
Capabilities.avHardwareDisable Capabilities.localFileReadDisable.
, mms.cfg, ActionScript.
,
, mms.cfg .
mms.cfg . ,
, mms.cfg.
Adobe , ,
mms.cfg.
mms.cfg :

Windows: \Macromed\Flash\mms.cfg
(, C:\WINDOWS\system32\Macromed\Flash\mms.cfg)

Mac: /Macromedia/mms.cfg
(, /Library/Application Support/Macromedia/mms.cfg)
mms.cfg . Flash Player Administration
Guide www.adobe.com/go/flash_player_admin_ru.

23.11.2012.

1128

ACTIONSCRIPT 3.0

Global Flash Player Trust


Flash Player 9 , Adobe AIR 1.0
SWF-
. SWF-
. SWF-
, .
Global Flash Player Trust, :

Windows: \Macromed\Flash\FlashPlayerTrust
(, C:\WINDOWS\system32\Macromed\Flash\FlashPlayerTrust)

Mac: /Macromedia/FlashPlayerTrust
(, /Library/Application Support/Macromedia/FlashPlayerTrust)
FlashPlayerTrust ,
, . SWF-, HTML-
. #. ,
Flash Player, ,
.
# Trust files in the following directories:
C:\Documents and Settings\All Users\Documents\SampleApp

SMB. , , .
.
,
, .cfg.
SWF- ,
Global Flash Player Trust,
.
. mms.cfg, Global Flash Player Trust
, .
Global Flash Player Trust
, .
Flash Player Trust (.
1129).


Flash Player 9
Flash Player
: , User Flash Player
Trust.

23.11.2012.

1129

ACTIONSCRIPT 3.0


Flash Player 9

.
, .
, SWF- ,
, ,
Flash Player.
,
, , , ,
, . AIR
.
. , mms.cfg (.
1128), .
. www.adobe.com/go/settingsmanager_ru.

User Flash Player Trust


Flash Player 9 , Adobe AIR 1.0

SWF-. SWF-
. SWF-
, . User
Player Trust, , Flash
( ):

Windows: \Macromedia\Flash Player\#Security\FlashPlayerTrust


(, C:\Documents and Settings\JohnD\Application Data\Macromedia\Flash
Player\#Security\FlashPlayerTrust Windows XP C:\Users\JohnD\AppData\Roaming\Macromedia\Flash
Player\#Security\FlashPlayerTrust Windows Vista)
Windows Application Data . ,
, > ,
.
.

Mac: /Macromedia/Flash Player/#Security/FlashPlayerTrust


(, /Users/JohnD/Library/Preferences/Macromedia/Flash Player/#Security/FlashPlayerTrust)
, ,
.
, User Flash Player Trust
.

23.11.2012.

1130

ACTIONSCRIPT 3.0

SWF- ,
User Flash Player Trust,
. User
Flash Player Trust ,
().
Global Flash Player Trust,
(.
1128).

- ( )
Flash Player 9 , Adobe AIR 1.0
- SWF- ,
. XML-, .
, :

, ;
XML ;
SWF-
;

XML-.
ActionScript :
. ActionScript, Loader, Sound, URLLoader URLStream,
URL-. Socket
XMLSocket , ,
.
Flash Player ,
: URL- .

URL-.
, SWF-,
.

,
TCP- Socket XMLSocket.
Flash Player ,
. ,
HTTP-, SWF-
HTTP. , ,
SWF- . ,
.

SWF-, Flash Player 10. (
Flash Player ,
Flash Player.) .
Flash Player 9 Flash Player Developer Center
www.adobe.com/go/devnet_security_ru.

23.11.2012.

1131

ACTIONSCRIPT 3.0

, AIR,
URL . AIR,
, .


Flash Player 9 , Adobe AIR 1.0
Flash Player ( AIR,
AIR) URL crossdomain.xml
, 843.
. ( Flash Player
, . ,
, .)
, . ,
.
URL master-only ( ), /crossdomain.xml
.
all (), .
. Flash Player 9
URL- all (),
. ,
(/crossdomain.xml) Flash Player 10,
,
, . ,
, . Flash Player 9 Flash
Player Developer Center www.adobe.com/go/devnet_security_ru.
SWF- .
Security.loadPolicyFile(). , ,
, loadPolicyFile()
, . loadPolicyFile() ,
, . Flash Player

. , Security.loadPolicyFile()
.
, Flash Player .
, Flash Player , .
loadPolicyFile() - ; Flash Player ,
. ,
, loadPolicyFile().
Security.loadPolicyFile() (),
, .
loadPolicyFile() Flash Player,
, .
, .
Flash Player
, .

23.11.2012.

1132

ACTIONSCRIPT 3.0

, URL-.
.
1151.

URL-
Flash Player 9 , Adobe AIR 1.0
URL- , ,
. . ,
, .
, . , ,
https://www.adobe.com:8080/crossdomain.xml,
www.adobe.com HTTPS 8080.

URL-
Flash Player 9 , Adobe AIR 1.0
<cross-domain-policy>, , ,
<allow-access-from>, . <allow-access-from>
domain, IP-, ,
( ). :

, IP-;
, .
.
, . , xyz.com
*.xyz.com. IP-.
URL-, SWF-
*.example.com, www.friendOfExample.com 192.0.34.166.
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*.example.com" />
<allow-access-from domain="www.friendOfExample.com" />
<allow-access-from domain="192.0.34.166" />
</cross-domain-policy>

IP-, SWF-, IP-


IP- (, http://65.57.83.12/flashmovie.swf).
SWF- . Flash Player
DNS.
, .
<?xml version="1.0"?>
<!-- http://www.foo.com/crossdomain.xml -->
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

23.11.2012.

1133

ACTIONSCRIPT 3.0

<allow-access-from> secure,
true. HTTPS- SWF-
( HTTPS) HTTPS-,
false.
secure false , HTTPS.
, false
. Adobe secure false.
HTTPS-, SWF- HTTP-,
Adobe SWF- HTTPS-.
HTTPS. ,
SWF- -, secure="false" <allow-access-from>,
.
<allow-access-from domain="www.example.com" secure="false" />

allow-http-request-headers-from.
, ,
, . <allow-access-from>
, allow-http-request-headers-from
.
SOAPAction .
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="SOAPAction"/>
</cross-domain-policy>

allow-http-request-headers-from ,
. ,
, .


Flash Player 9 , Adobe AIR 1.0
.
Flash Player , .

. ,
. , .

Loader.load(), checkPolicyFile context,


LoaderContext.

<img>,
checkPolicyFile <img> "true", .
<img checkPolicyFile = "true" src = "example.jpg">

Sound.load(), checkPolicyFile context,


SoundLoaderContext.

NetStream, checkPolicyFile NetStream.

23.11.2012.

1134

ACTIONSCRIPT 3.0

, Flash Player ,
. ,
<allow-access-from> . ,
Security.loadPolicyFile(), , .

()
Flash Player 9 , Adobe AIR 1.0
API- ActionScript
Security.allowDomain(), SWF- .
SWF- SWF- www.example.com.
Security.allowDomain("www.example.com")

SWF- (.
1144);

(. 1147);
(. 1147);
Stage (.
1146).
Security.allowDomain() SWF-
SWF-, Security.allowDomain().
. 1144.
IP- Security.allowDomain(),
IP-. , URL
IP-, . ,
www.example.com IP- 192.0.34.166,
Security.allowDomain("192.0.34.166") www.example.com.
, "*"
Security.allowDomain(). "*"
SWF-, .
ActionScript API- :
Security.allowInsecureDomain(). , Security.allowDomain(),
SWF-, HTTPS-,
SWF-, , . ,
, (HTTPS),
, (, HTTP),
.
: Security.allowInsecureDomain() ,
HTTPS, SWF-, HTTP,
, HTTP- ,
SWF- , HTTPS-.
. , AIR,
allowDomain() allowInsecureDomain() Security.

23.11.2012.

1135

ACTIONSCRIPT 3.0

, , Security.loadPolicyFile(),
Flash Player .
. - ( )
1131.

API-

Flash Player 9 , Adobe AIR 1.0


API- .
.
. SWF-
, allowNetworking.


Flash Player 9 , Adobe AIR 1.0
Flash Player Adobe AIR, , HTTP-
. HTTP- ,
, HTTP.
API-, URL-.
API-, ,
Socket.connect() XMLSocket.connect(), Security.loadPolicyFile(),
.
, .
API- ActionScript 3.0, :
FileReference.download(),FileReference.upload(), Loader.load(), Loader.loadBytes(),
navigateToURL(), NetConnection.call(), NetConnection.connect(), NetStream.play(),
Security.loadPolicyFile(), sendToURL(), Sound.load(), URLLoader.load(), URLStream.load()

, ,
<img> SWF- HTML- <object>
<embed>.
, <img>
SWF- HTML- <object> <embed>.
:
HTTP: 20 (ftp data), 21 (ftp control)

23.11.2012.

1136

ACTIONSCRIPT 3.0

HTTP FTP: 1 (tcpmux), 7 (echo), 9 (discard), 11 (systat), 13 (daytime), 15 (netstat), 17 (qotd), 19 (chargen),
22 (ssh), 23 (telnet), 25 (smtp), 37 (time), 42 (name), 43 (nicname), 53 (domain), 77 (priv-rjs), 79 (finger),
87 (ttylink), 95 (supdup), 101 (hostriame), 102 (iso-tsap), 103 (gppitnp), 104 (acr-nema), 109 (pop2), 110 (pop3),
111 (sunrpc), 113 (auth), 115 (sftp), 117 (uucp-path), 119 (nntp), 123 (ntp), 135 (loc-srv / epmap), 139 (netbios),
143 (imap2), 179 (bgp), 389 (ldap), 465 (smtp+ssl), 512 (print / exec), 513 (login), 514 (shell), 515 (printer),
526 (tempo), 530 (courier), 531 (chat), 532 (netnews), 540 (uucp), 556 (remotefs), 563 (nntp+ssl), 587 (smtp),
601 (syslog), 636 (ldap+ssl), 993 (ldap+ssl), 995 (pop3+ssl), 2049 (nfs), 4045 (lockd), 6000 (x11)

allowNetworking
Flash Player 9 , Adobe AIR 1.0
SWF-
allowNetworking <object> <embed> HTML, SWF-.
allowNetworking:

"all" ( ): SWF- API- ;

"internal": SWF- API-

, , API ;

"none": SWF- API-


, , API-
SWF-, .

allowNetworking , SWF-
HTML- . "internal" "none"
, SWF- ,
HTML-, ,
HTML-. SWF-
HTML-, allowNetworking
, .
API- SecurityError.
allowNetworking <object> <embed> HTML, SWF-, .
<object classic="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
Code
base="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,124,
0"
width="600" height="400" ID="test" align="middle">
<param name="allowNetworking" value="none" />
<param name="movie" value="test.swf" />
<param name="bgcolor" value="#333333" />
<embed src="test.swf" allowNetworking="none" bgcolor="#333333"
width="600" height="400"
name="test" align="middle" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

23.11.2012.

1137

ACTIONSCRIPT 3.0

HTML- SWF.
, allowNetworking. HTML-,
Adobe Flash Professional Adobe Flash Builder, AC_FL_RunContent()
SWF-. allowNetworking , .
AC_FL_RunContent( ... "allowNetworking", "none", ...)

API- , allowNetworking "internal":


navigateToURL(), fscommand(), ExternalInterface.call()

allowNetworking "none", API-


:
sendToURL(), FileReference.download(), FileReference.upload(), Loader.load(),
LocalConnection.connect(), LocalConnection.send(), NetConnection.connect(), NetStream.play(),
Security.loadPolicyFile(), SharedObject.getLocal(), SharedObject.getRemote(), Socket.connect(),
Sound.load(), URLLoader.load(), URLStream.load(), XMLSocket.connect()

allowNetworking SWF- API , ,


(. 1122).
allowNetworking "none",
<img> htmlText TextField ( SecurityError).
allowNetworking "none", ,
Flash Professional ( ActionScript), .


Flash Player 9 , Adobe AIR 1.0
Flash Player 9.0.27.0 ,
, .
, displayState Stage
StageDisplayState.FULL_SCREEN. .
179.
SWF-, ,
, .
, <object> <embed> HTML-,
SWF-, allowFullScreen "true" (
"false"), .

23.11.2012.

1138

ACTIONSCRIPT 3.0

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,
18,0"
width="600" height="400" id="test" align="middle">
<param name="allowFullScreen" value="true" />
<param name="movie" value="test.swf" />
<param name="bgcolor" value="#333333" />
<embed src="test.swf" allowFullScreen="true" bgcolor="#333333"
width="600" height="400"
name="test" align="middle" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

HTML- SWF.
, allowFullScreen. HTML-,
Flash Professional Flash Builder, AC_FL_RunContent()
SWF-, allowFullScreen,
.
AC_FL_RunContent( ... "allowFullScreen", "true", ...)

ActionScript, ,
. Flash Player .
, ,
, . ,
.
, ,
. Flash Player 9 ,
, Escape.
. Flash Player 10
, , , .
- .
-. ,
( ).
displayState Stage
, , Stage (
SWF-). . 1146.
SWF-, ,
FullScreenDisable = 1 mms.cfg. .
1128.
SWF- , HTML-.

23.11.2012.

1139

ACTIONSCRIPT 3.0

Flash Player 11.3 , Adobe AIR 1.0


Flash Player 11.3
, , ,
. ,
displayState Stage StageDisplayState.FULL_SCREEN_INTERACTIVE.
. 179.
SWF-, ,
, .
, <object> <embed> HTML-,
SWF-, allowFullScreenInteractive "true" (
"false"), .
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,
18,0"
width="600" height="400" id="test" align="middle">
<param name="allowFullScreenInteractive" value="true" />
<param name="movie" value="test.swf" />
<param name="bgcolor" value="#333333" />
<embed src="test.swf" allowFullScreen="true" bgcolor="#333333"
width="600" height="400"
name="test" align="middle" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

HTML- SWF.
, allowFullScreenInteractive. HTML-,
Flash Professional Flash Builder, AC_FL_RunContent()
SWF-,
allowFullScreenInteractive, .
AC_FL_RunContent( ... "allowFullScreenInteractive", "true", ...)

ActionScript, ,
. Flash Player
.
,
. ,
. ,
, .
SWF-,
, FullScreenInteractiveDisable = 1 mms.cfg.
. 1128.
SWF- ,
HTML-.

23.11.2012.

1140

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR , :

SWF-;
;
Sound

HTML- ( AIR);
JavaScript ( AIR).

SWF- Loader
Flash Player 9 , Adobe AIR 1.0
SWF- (JPG, GIF PNG) Loader. SWF-,
,
SWF- . SWF-
SWF-, .

SWF-,
. SWF-
(, ), SWF-,
.
, SWF- ( ,
SWF- Loader) Loader,
(, Loader)
, , .
import flash.display.*;
import flash.net.URLRequest;
var rect:Shape = new Shape();
rect.graphics.beginFill(0xFFFFFF);
rect.graphics.drawRect(0, 0, 100, 100);
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);

23.11.2012.

1141

ACTIONSCRIPT 3.0

load() Loader context,


LoaderContext. LoaderContext ,
.

checkPolicyFile: ( SWF-).

, , ,
Loader. true, Loader
URL- (. - (
) 1131). Loader, ActionScript SWF Loader . ,
Loader.content Bitmap,
, BitmapData.draw() BitmapData.drawWithQuality()
. drawWithQuality
Flash Player 11.3 AIR 3.3 .

securityDomain: SWF- ( ).

SWF- , ,
Loader. securityDomain : null (
) SecurityDomain.currentDomain. SecurityDomain.currentDomain,
SWF-
SWF-, ,
SWF-. , SWF-
URL-, SWF-.
, ,
, .
,
, SWF-
Security.allowDomain(). ,
SWF-
.

applicationDomain: SWF-,

ActionScript 3.0 ( SWF-, ActionScript 1.0 2.0).


, , ,
, SWF- (
). ,
, , SWF-
, :
,
securityDomain. , SWF-
, applicationDomain . .
158.
. 216.
Loader contentLoaderInfo,
LoaderInfo. , LoaderInfo
SWF- . SWF, LoaderInfo DisplayObject.loaderInfo.
LoaderInfo , , URL-
, . .
215.

23.11.2012.

1142

ACTIONSCRIPT 3.0

-
Flash Player 9 , Adobe AIR 1.0
,
,
Sound.load(), NetConnection.connect() NetStream.play().

AIR
. ,
AIR
.
.
.
1148.

SWF- <img>

Flash Player 9 , Adobe AIR 1.0
SWF- <img>,
.
<img src = 'filename.jpg' id = 'instanceName' >


getImageReference() TextField, .
var loadedObject:DisplayObject = myTextField.getImageReference('instanceName');

, SWF- , ,
.
<img> ,
URL-.
, checkPolicyFile <img>, .
<img src = 'filename.jpg' checkPolicyFile = 'true' id = 'instanceName' >

SWF- <img> ,
, Security.allowDomain().
<img> (
Bitmap, SWF-), Loader,
TextField, Loader ,
Loader ActionScript. getImageReference()
Loader. Loader ,
, .
,
content Loader.
, URL-, SWF-,
allowDomain().

23.11.2012.

1143

ACTIONSCRIPT 3.0

Adobe AIR
<img>
. , ,
, allowDomain() Security.

, RTMP
Flash Player 9 , Adobe AIR 1.0
Flash Media Server RTMP (Real-Time Media Protocol) ,
. connect()
NetConnection, URL- RTMP . Flash Media Server
, .
. Flash Media Server
www.adobe.com/go/learn_fms_docs_ru.
BitmapData.draw(), BitmapData.drawWithQuality()
SoundMixer.computeSpectrum()

RTMP, . Client.videoSampleAccess
Client.audioSampleAccess ActionScript
Flash Media Server. .
ActionScript. ( drawWithQuality Flash Player 11.3 AIR 3.3 .)


Flash Player 9 , Adobe AIR 1.0
SWF-, ActionScript 3.0, HTML-, AIR,
(, URL- SWF- http://www.example.com/swfA.swf,
http://www.example.com/swfB.swf), ,
, , , .
.
, http://siteA.com/swfA.swf http://siteB.com/swfB.swf,
Flash Player AIR swfA.swf , swfB.swf,
. SWF- SWF-
Security.allowDomain(). Security.allowDomain("siteA.com"), swfB.swf
SWF- siteA.com.
SWF- AVM1 SWF-
AVM2. SWF- AVM1 ActionScript 1.0 ActionScript 2.0.
(AVM1 AVM2 ActionScript Virtual Machine ( ActionScript).
, AVM1 AVM2
LocalConnection.

23.11.2012.

1144

1145

ACTIONSCRIPT 3.0


. , ,
( SWF-),
( SWF-). siteA.swf
siteB.swf, siteA.swf , siteB.swf ,
.
siteA.com / swfA.swf
SWF

var url:String = "http://siteB.com/swfB.swf";


var req:URLRequest = new URLRequest(url);
myLoader.load(req);

myLoader.content.eggCount = 3;
myLoader.content.DisplayEggs();

Security.allowDomain("siteA.com");

var eggCount:Number;
function DisplayEggs() { ... };
siteB.com / swfB.swf

SWF

, Security.allowDomain(),
. siteA.swf siteB.swf,
siteB.swf siteA.swf, siteA.swf
Security.allowDomain(), SWF- siteB.com.
, Security.allowDomain() SWF.
Flash Player SWF-
SWF-, HTML-. HTML- SWF-
ExternalInterface.addCallback().
HTML- SWF- , SWF-
Security.allowDomain(), , SWF-,
. .
() 1135.
, Flash Player
SWF- HTML-. .
URL- 1155.

23.11.2012.

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
Stage ,
.
Stage , SWF-.
Stage SWF-,
, .

align

addChild()

displayState

addChildAt()

frameRate

addEventListener()

height

dispatchEvent()

mouseChildren

hasEventListener()

numChildren

setChildIndex()

quality

willTrigger()

scaleMode
showDefaultContextMenu
stageFocusRect
stageHeight
stageWidth
tabChildren
textSnapshot
width

SWF-
, SWF-, ,
Security.allowDomain(),
. . ()
1135.
frameRate . frameRate SWF-.
, ,
( ,
Security.allowDomain()).
removeChildAt() swapChildrenAt()
Stage, . ,
, ,
, Security.allowDomain().

23.11.2012.

1146

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
SWF- , ,
. SWF- , SWF-
, SWF-
SWF- Security.allowDomain(). .
() 1135.
Bitmap, Loader,
URL, SWF-,
Bitmap (. - ( )
1131).
LoaderInfo, ( Loader), ,
Loader: childAllowsParent,
parentAllowsChild sameDomain.


Flash Player 9 , Adobe AIR 1.0
, ,
, , .
(.
134). ,

.
, ,
,
. , .
1 SWF-, ,
Security.allowDomain(), SWF-,
.

2 SWF-, ,
Security.allowDomain(), SWF-,

.
LoaderInfo, ( Loader), ,
Loader: childAllowsParent
parentAllowsChild.
, , .

23.11.2012.

1147

ACTIONSCRIPT 3.0

Flash Player 9 , Adobe AIR 1.0


BitmapData.draw(),
BitmapData.drawWithQuality() SoundMixer.computeSpectrum().
,
, .

:

, ,
, Security.allowDomain()
.

URL- , .
SWF-,
BitmapData.draw(), BitmapData.drawWithQuality() SoundMixer.computeSpectrum()
. drawWithQuality Flash Player 11.3
AIR 3.3 .
, .


Flash Player 9 , Adobe AIR 1.0
draw() drawWithQuality() (Flash Player 11.3; AIR 3.3) BitmapData
BitmapData.
MovieClip, Bitmap .
BitmapData, .

,
( Sprite MovieClip) ,
, draw, SWF-,
Security.allowDomain().

,
, , draw,
URL-, .
, SecurityError.
load() Loader context,
LoaderContext. checkPolicyFile LoaderContext
true, Flash Player URL- ,
. , SWF, Bitmap; .
checkPolicyFile , <img>
. . SWF-
<img> 1143.

23.11.2012.

1148

ACTIONSCRIPT 3.0


Flash Player 9 , Adobe AIR 1.0
API- ActionScript 3.0, ,
.

SoundMixer.computeSpectrum(): ,
, .
.

SoundMixer.stopAll(): ,

, .
.

id3 Sound SWF-,


, .
.
: .

, ,
id3 SoundMixer.computeSpectrum().

, , ,
, SoundMixer.stopAll().
load() Sound context,
SoundLoaderContext. checkPolicyFile SoundLoaderContext
true, URL- ,
. , ,
id Sound; . ,
checkPolicyFile, SoundMixer.computeSpectrum()
.
SoundMixer.areSoundsInaccessible() ,
SoundMixer.stopAll() ,
.
SoundMixer.stopAll() ,
, stopAll().
, SWF-,
Security.allowDomain() SWF-, stopAll().
, ,
SoundMixer.areSoundsInaccessible().
computeSpectrum() ,
, , ,
. SecurityError.
, SWF-,
Security.allowDomain() SWF-.
, SWF- (, mp3- ),
URL- .
. () 1135
- ( ) 1131.

23.11.2012.

1149

ACTIONSCRIPT 3.0

RTMP, .
Client.audioSampleAccess ActionScript
Flash Media Server. .
ActionScript.


Flash Player 9 , Adobe AIR 1.0
BitmapData.draw() BitmapData.drawWithQuality()
. ( drawWithQuality Flash Player 11.3 AIR 3.3
.)
:

, RTMP Flash Media Server


, FLV- F4V-
draw RTMP,
. Client.videoSampleAccess
ActionScript Flash Media Server.
. ActionScript.
draw, source ,
, , FLV-,
FLV- ,
SWF-. , checkPolicyFile
NetStream true.


Flash Player 9 , Adobe AIR 1.0
Flash Player AIR .
,
, .
, , .
(.
- ( ) 1131).
. , AIR,
(
), ,
. AIR,
, .
AIR
.

23.11.2012.

1150

ACTIONSCRIPT 3.0

URLLoader URLStream
Flash Player 9 , Adobe AIR 1.0
, XML . load()
URLLoader URLStream , URL-.
load() , ,
, URL-
. ,
.


Flash Player 9 , Adobe AIR 1.0
843.
URL, .
Flash Player 6,
. - ,
HTTP- 80 , -.
Flash Player 9 , Flash Player 10 .
Flash Player 10 .
URL-, ,
, . master-only
( ) all ().
, , Flash
Player , .
XML- ,
, SWF-. ,
:

843 ( );
, ;
.
Flash Player 843 ,
. , SWF-
Security.loadPolicyFile().
, URL-,
, .
1024, ;
1024 ,
1024 . to-ports
<allow-access-from>. ,
.
.

23.11.2012.

1151

ACTIONSCRIPT 3.0

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<!-- Policy file for xmlsocket://socks.mysite.com -->
<cross-domain-policy>
<allow-access-from domain="*" to-ports="507" />
<allow-access-from domain="*.example.com" to-ports="507,516" />
<allow-access-from domain="*.example.org" to-ports="516-523" />
<allow-access-from domain="adobe.com" to-ports="507,516-523" />
<allow-access-from domain="192.0.34.166" to-ports="*" />
</cross-domain-policy>

843 ,
, Socket.connect() XMLSocket.connect().
Flash Player 843. ,
, .
, Flash Player allow-access-from
. ,
.
,
Security.loadPolicyFile() "xmlsocket", .
Security.loadPolicyFile("xmlsocket://server.com:2525");

Security.loadPolicyFile() Socket.connect()
XMLSocket.connect(). Flash Player ,
. ,
, ,
loadPolicyFile() , .
- , ,
: .
, .
Flash Player ,
:
<policy-file-request/>

, . Flash Player
, .
,
. . ,
Flash Player , ,
.


Flash Player 9 , Adobe AIR 1.0
,
TLS SSL , .
HTTPS.

23.11.2012.

1152

ACTIONSCRIPT 3.0

, AIR 2 ,
TCP. SecureSocket ,
TLS 1 SSL 4.


Flash Player 9 , Adobe AIR 1.0
, .
. SWF-
, ,

AIR. .
1123.
URL- flash.net.sendToURL().
URL-. , Loader.load()
Sound.load() , URLLoader.load() URLStream.load().


Flash Player 9 , Adobe AIR 1.0
FileReference.upload() .
FileReference.upload(), FileReference.browse()
FileReferenceList.browse().
, FileReference.browse() FileReferenceList.browse(),
.
Flash Player 10 .
AIR.
FileReference.download() ,
.
. , Flash-,
(
ActiveX),
( ) . Flash Player
, .
, SWF-
.
SWF-
. SWF- ,
, SWF-.

23.11.2012.

1153

ACTIONSCRIPT 3.0

SWF-,

Flash Player 9 , Adobe AIR 1.0
SWF-, context load() Loader.
LoaderContext. securityDomain
LoaderContext Security.currentDomain, Flash Player
URL- SWF-.
SWF-, SWF-
. ,
SWF-.
SWF- SWF-,
, : SWF-
Security.allowDomain(), SWF-.
Security.allowDomain() SWF-,
SWF- init,
contentLoaderInfo Loader. ,
SWF- Security.allowDomain()
. SWF-
SWF- Loader.contentLoaderInfo.applicationDomain.getDefinition()
Loader.contentLoaderInfo.applicationDomain.getQualifiedDefinitionNames() (Flash Player 11.3 AIR 3.3
).


Flash Player 9 , Adobe AIR 1.0
Flash Player 6 , ,
SWF-.
, .
SWF- , www.example.com,
(www) , . Flash Player 6 www.example.com
store.example.com example.com .
www.example.co.uk, store.example.co.uk example.co.uk .
, , SWF-
, example1.co.uk example2.co.uk .
Flash Player 7
SWF-. , SWF- www.example.com
www.example.com, SWF- store.example.com
store.example.com.

23.11.2012.

1154

ACTIONSCRIPT 3.0

SWF- ActionScript 3.0 Security.exactSettings true


( ), Flash Player
. false, Flash Player , Flash Player 6.
exactSettings ,
, Flash Player,
.
SWF- 6 ,
SWF-, ActionScript 3.0,
Security.exactSettings false,
SharedObject.getLocal().

LocalConnection
Flash Player 9 , Adobe AIR 1.0
LocalConnection Flash Player AIR.
LocalConnection Flash Player AIR,
,
. , SWF-, , SWF-, ,
AIR LocalConnection.
LocalConnection . Flash Player
LocalConnection ,
. , ,
LocalConnection.allowDomain().
, LocalConnection.allowDomain(),
, IP- *.
allowDomain() , ActionScript 1.0 2.0.
allowDomain() . ActionScript 3.0
allowDomain() LocalConnection.
allowDomain() , Security.allowDomain().
SWF- domain LocalConnection
.

URL-
Flash Player 9 , Adobe AIR 1.0
URL- ( HTTP-, mailto: .
.) API-.

flash.system.fscommand();
ExternalInterface.call();
flash.net.navigateToURL().

23.11.2012.

1155

ACTIONSCRIPT 3.0

, , ,
- ( )
AIR.
,
.
, , API- , , AllowScriptAccess,
. flash.net.navigateToURL()
, , SWF-.
. navigateToURL()
1157.
AllowScriptAccess HTML-, SWF-,
URL- SWF-. PARAM
EMBED. AllowScriptAccess , SWF- HTML-
, .
AllowScriptAccess : "always", "sameDomain"
"never".

AllowScriptAccess "always", SWF- HTML, , .

AllowScriptAccess "sameDomain", SWF- HTML, , .


AllowScriptAccess .
AllowScriptAccess, SWF-
HTML- .

AllowScriptAccess "never", SWF-


HTML-. , Adobe Flash CS4 Professional.
, SWF-
. SWF-,
Adobe ,
.
AllowScriptAccess HTML-,
URL- .
<object id='MyMovie.swf' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
codebase='http://download.adobe.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'
height='100%' width='100%'>
<param name='AllowScriptAccess' value='always'/>
<param name='src' value=''MyMovie.swf'/>
<embed name='MyMovie.swf' pluginspage='http://www.adobe.com/go/getflashplayer'
src='MyMovie.swf' height='100%' width='100%' AllowScriptAccess='never'/>
</object>

23.11.2012.

1156

ACTIONSCRIPT 3.0

navigateToURL()
Flash Player 9 , Adobe AIR 1.0
allowScriptAccess,
navigateToURL() target. target
HTML-, URL-.
, ,
navigateToURL() .
, navigateToURL("javascript: alert('Hello from Flash
Player.')"), .

SWF- , .
HTML-, SWF-,
allowScriptAccess, .

, SWF-, .
, ,
, .
(, HTTP, HTTPS mailto:),
:

target "_top" "_parent"


SWF- -, ,
SWF- allowScriptAccess,
"always".


Flash Player 9 , Adobe AIR 1.0
URL . c
ActionScript 3.0 Adobe Flash Platform:

flash.system.fscommand();
call() ExternalInterface;
flash.net.navigateToURL().


Flash Player 9 , Adobe AIR 1.0
Flash Player ,
ActionScript, SWF-
, RTMP-. ,
Flash Player, .
,
, .

23.11.2012.

1157

ACTIONSCRIPT 3.0

, SWF-,
SharedObject. :
SWF- ,
URL-. .
753.
SWF- localPath SharedObject.getLocal()
SharedObject.getRemote(), ,
URL-. SWF- SWF-
URL-. '/' localPath,
, .
Flash
Player . 100
.
. .
1128 1129.
, true secure
SharedObject.getLocal() SharedObject.getRemote(). secure,
.

true, Flash Player


.
SWF-,
HTTPS, SharedObject.getLocal() secure,
true.

false, Flash Player


, SWF-,
( HTTPS).
SWF- URL- ( HTTPS),
true secure SharedObject.getLocal()
SharedObject.getRemote() SecurityError.
URL- SWF-.
, SWF- URL-:
. SWF-
LoaderContext.securityDomain SecurityDomain.currentDomain.
SWF- -URL-, SWF-,
URL-. , SWF-
Loader.loadBytes(). SWF- ,
URL- SWF-, .
-URL SWF-
LoaderInfo.url. -URL ,
. localPath , -URL
.
.
SWF-, -,
URL- SWF- , .
,
.

23.11.2012.

1158

ACTIONSCRIPT 3.0

, SWF-, ,
HTML-. , SWF- ,
. SWF-
SharedObject.getLocal()
SharedObject.getRemote() null. .
www.adobe.com/products/flashplayer/articles/thirdpartylso.

, ,

Flash Player 9 , Adobe AIR 1.0


SWF-
Camera.get() Microphone.get(), Flash Player
,
.
mms.cfg, (.
1128
1129). , Camera.get()
Microphone.get() null. Capabilities.avHardwareDisable
, (true) (false) .
System.setClipboard() SWF-
. . getClipboard() ,
,
.
, Flash Player,
, . , Flash Player,
.

AIR
Adobe AIR 1.0

AIR
Adobe AIR 1.0
AIR ,
. AIR, ,
, , ,
. ,
, ,
AIR.

23.11.2012.

1159

ACTIONSCRIPT 3.0

Adobe AIR Adobe Flash Player,


, .
,
, .
AIR - ( SWF),
(JavaScript, HTML), .
AIR, ,
. ,
, .


Adobe AIR 1.0
AIR AIR, air,
,
. , Windows EXE, Android
APK.
Adobe AIR AIR AIR
. ,
.
. ,
AIR, .
, AIR ,
, .
, .


Adobe AIR 1.0
AIR, AIR,
, SWF-
Flash Player.
:

Mac OS: /Library/Frameworks/


Windows: C:\Program
Linux: /opt/Adobe

Files\Common Files\Adobe AIR

AIR/

Mac OS
. Windows Linux
.
. iOS AIR . AIR
.

23.11.2012.

1160

ACTIONSCRIPT 3.0

:
( -) . AIR,
, AIR
(
AIR Adobe).

( )
Adobe AIR 1.0
,
Adobe AIR, .
SWF-, .
SWF- , SWF- .
,
.


Adobe AIR 1.0

AIR. AIR
(, HTML- -). AIR
.


Adobe AIR 1.0
AIR AIR.
AIR ,
:

,
AIR -.

, .

AIR
, ( ).

AIR. AIR
, .
,
, .
AIR, .

23.11.2012.

1161

1162

ACTIONSCRIPT 3.0


Adobe AIR 1.0
:
1 .

.
2 , ,

Mac OS: ~/Applications/


Windows XP : C:\Program

Files\

Windows Vista: ~/Apps/


Linux: /opt/
installFolder ,
.

AIR
Adobe AIR 1.0
AIR , AIR,
. :

Windows: , , AIR.
exe AIR.

Linux: , , AIR.
AIR .

Mac OS: app AIR.


Finder.
app AIR.
AIR:

Windows: .exe , (,
).

Linux: .bin , (Applications),


.

Mac OS: .app , .


,
. , , ,
, .

23.11.2012.

1163

ACTIONSCRIPT 3.0

AIR
Adobe AIR 1.0
AIR
; app-storage:/
. , app-storage:/ ,
, :

Mac OS: AIR:


AIR 3.2 : <appData>/<appId>/Local

Store/, <appData>
, : /Users/<user>/Library/Preferences

AIR 3.3 : <path>/Library/Application

Support/<appID>/Local Store,

<path> /Users/<user>/Library/Containers/<bundle-id>/Data ( )
/Users/<user> ( )

Windows:

<appData>\<appId>\Local Store\ ,

<appData> CSIDL_APPDATA, , C:\Documents and


Settings\<user>\Application Data

Linux: <appData>/<appID>/Local

Store/, <appData> /home/<user>/.appdata


air.File.applicationStorageDirectory.
resolvePath() File. .
701.

Adobe AIR
Adobe AIR 1.0
AIR, ,
.
.

AIR
Adobe AIR 1.0

, , . API AIR , : Updater.update()
AIR.
AIR , .
,
.
Updater ,
AIR. , ,
, .
. , versionNumber
.

23.11.2012.

ACTIONSCRIPT 3.0

AIR
Adobe AIR 1.0
AIR . ,
. AIR
, AIR .

Windows
Adobe AIR 1.0
Windows ( )
AIR . Windows
: HKLM\Software\Policies\Adobe\AIR. :

AppInstallDisabled

, AIR . ,
0, 1.

UntrustedAppInstallDisabled

, AIR (
) . , 0, 1.

UpdateDisabled

, ,
. , 0, 1.

HTML Adobe AIR


Adobe AIR 1.0
HTML- AIR,
HTML
HTML- SWF-.

HTML JavaScript. ,
JavaScript, HTML JavaScript SWF.

.
,

.
AIR SDK HTML-.
HTMLLoader JavaScript API- AIR.

23.11.2012.

1164

ACTIONSCRIPT 3.0

StageWebView HTML,
AIR. , StageWebView,
,
AIR. StageWebView
HTML- AIR, Webkit,
HTMLLoader. StageWebView HTML,
. ,
StageWebView
, -.
TextField HTML. JavaScript ,
.
. JavaScript 1055.

HTML
Adobe AIR 1.0
HTML AIR.
.
HTML AIR , HTML
, HTML .
AIR, -,
.
.
. (
, .
cookie, , ,
.)
HTML AIR
, AIR HTML
. load AIR ,
eval(), . ,
. HTML-
, ,
. (

JavaScript, eval().) ,
JavaScript , .

1167.
HTML AIR , , ,
AIR ,
.
,
.

23.11.2012.

1165

ACTIONSCRIPT 3.0


Adobe AIR 1.0
AIR sandboxRoot documentRoot HTML frame iframe.
, :

sandboxRoot

URL- ,
.
URL- file:, http: https:.

documentRoot

URL-, .
URL- file:, app: app-storage:.

,
,
www.example.com:
<iframe
src="ui.html"
sandboxRoot="http://www.example.com/local/"
documentRoot="app:/sandbox/">
</iframe>



Adobe AIR 1.0
AIR childSandboxBridge parentSandboxBridge window
.
. :
childSandboxBridge childSandboxBridge
.
childSandbox .
. , ,
, ,
:
var interface = {};
interface.calculatePrice = function(){
return .45 + 1.20;
}
interface.storeID = "abc"
window.childSandboxBridge = interface;

, id
"child", ,
childSandboxBridge :
var childInterface = document.getElementById("child").childSandboxBridge;
air.trace(childInterface.calculatePrice()); //traces "1.65"
air.trace(childInterface.storeID)); //traces "abc"

23.11.2012.

1166

ACTIONSCRIPT 3.0

parentSandboxBridge parentSandboxBridge
.
parentSandbox .
.
, , ,
, save:
var interface = {};
interface.save = function(text){
var saveFile = air.File("app-storage:/save.txt");
//write text to file
}
document.getElementById("child").parentSandboxBridge = interface;

save.txt.
. ,
.
:
var textToSave = "A string.";
window.parentSandboxBridge.save(textToSave);

parentSandboxBridge,
SecurityError.
childSandboxBridge, SecurityError.



Adobe AIR 1.0
, HTML Adobe AIR 1164,

HTML JavaScript. .
API-
Adobe AIR JavaScript
.
. JavaScript 1055.
JavaScript eval()
Adobe AIR 1.0
HTML
API-,
( onload body
onload). ( )
, (,
).
,
innerHTML DOM, (JavaScript),
. DOM .

23.11.2012.

1167

ACTIONSCRIPT 3.0

JavaScript eval().
onload
eval() . eval()
:

. :
eval("null");
eval("3 + .14");
eval("'foo'");

. :
{ prop1: val1, prop2: val2 }

/ . :
{ get prop1() { ... }, set prop1(v) { ... } }

, :
[ val1, val2, val3 ]

, , . :
a.b.c

.
.
.
.
, onload
onload,
.
, ,
:
eval("alert(44)");
eval("myFunction(44)");
eval("NativeApplication.applicationID");

, , , , eval(),
, .
, ,
. , .
, .
:

eval().
innerHTML DOM ,
.

innerHTML DOM
( src).

src script JavaScript,


.

23.11.2012.

1168

ACTIONSCRIPT 3.0

URL- javascript ( href="javascript:alert('Test')").


setInterval() setTimout() , (
) ( ), (
setTimeout('x = 4', 1000)).

document.write() document.writeln().

.
eval() JSON.
JavaScript JSON.
JSON ( ).
Ajax JavaScript ,
, . ,
, ,
, .
. JavaScript AIR 1125
1177.
Ajax, ,
Adobe http://www.adobe.com/products/air/develop/ajax/features/.

JavaScript eval()
.
API- AIR (
)
Adobe AIR 1.0
JavaScript ,
, window.runtime, API AIR. ,
, , TypeError:
try {
window.runtime.flash.system.NativeApplication.nativeApplication.exit();
}
catch (e)
{
alert(e);
}

TypeError ( ),
window.runtime,
.
,
, .
.
1177.

23.11.2012.

1169

ACTIONSCRIPT 3.0

XMLHttpRequest
Adobe AIR 1.0
HTML
XMLHttpRequest
HTML onLoad.
HTML ,
, JavaScript XMLHttpRequest
, , . frame iframe
allowcrosscomainxhr. null
JavaScript XMLHttpRequest
, , :
<iframe id="UI"
src="http://example.com/ui.html"
sandboxRoot="http://example.com/"
allowcrossDomainxhr="true"
documentRoot="app:/">
</iframe>

.
1171.
CSS, frame, iframe img (
)
Adobe AIR 1.0
HTML ()
CSS, frame, iframe img ( URL).
HTML ,

CSS, frame, iframe img
(
).
JavaScript window.open()
Adobe AIR 1.0
, JavaScript window.open(),
,
() , .
.
JavaScript
window.open() , .

, , ,
(, ). ,
window.open() (,
setTimeout()).

23.11.2012.

1170

ACTIONSCRIPT 3.0

HTML remote ()
window.open() .
window.open()
.
,

(. 1122)
window.open() .
window.open()
remote.

Adobe AIR 1.0
,
, JavaScript: Adobe
AIR JavaScript .
. JavaScript 1055.

HTML-

Adobe AIR 1.0


loadString() HTMLLoader HTML- .
, HTML-, ,
. HTML-,
loadString(),
AIR.
placeLoadStringContentInApplicationSandbox HTMLLoader true,
HTML-, loadString(),
. . HTML-
1054.


Adobe AIR 1.0
AIR . ,
,
, .

23.11.2012.

1171

ACTIONSCRIPT 3.0

AIR
Adobe AIR 1.0
, .
AIR
application (, )
:


Security.allowDomain().
.


LoaderContext.securityDomain LoaderContext.applicationDomain .
, AIR ,
AIR, .
,
.
remote .
, ,
.

parentSandboxBridge
.

childSandboxBridge
.
, ,
, . . , ,
, ,
. , ,
.
parentSandboxBridge,
SecurityError. ,
childSandboxBridge, SecurityError.

(SWF)
Adobe AIR 1.0
, AIR SWF-
, SWF- , .
StoreAPI , .
StoreAPI parentSandboxBridge LoaderInfo Loader,
SWF.
AIR:

23.11.2012.

1172

ACTIONSCRIPT 3.0

<?xml version="1.0" encoding="utf-8"?>


<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
title="Music Store" creationComplete="initApp()">
<mx:Script>
import flash.display.Loader;
import flash.net.URLRequest;
private var child:Loader;
private var isSale:Boolean = false;
private function initApp():void {
var request:URLRequest =
new URLRequest("http://[www.yourdomain.com]/PriceQuoter.swf")
child = new Loader();
child.contentLoaderInfo.parentSandboxBridge = new StoreAPI(this);
child.load(request);
container.addChild(child);
}
public function getRegularAlbumPrice():String {
return "$11.99";
}
public function getSaleAlbumPrice():String {
return "$9.99";
}
public function getAlbumPrice():String {
if(isSale) {
return getSaleAlbumPrice();
}
else {
return getRegularAlbumPrice();
}
}
</mx:Script>
<mx:UIComponent id="container" />
</mx:WindowedApplication>

StoreAPI ,
getSaleAlbumPrice(). StoreAPI:

23.11.2012.

1173

ACTIONSCRIPT 3.0

public class StoreAPI


{
private static var musicStore:Object;
public function StoreAPI(musicStore:Object)
{
this.musicStore = musicStore;
}
public function getRegularAlbumPrice():String {
return musicStore.getRegularAlbumPrice();
}
public function getSaleAlbumPrice():String {
return "Not available";
}
public function getAlbumPrice():String {
return musicStore.getRegularAlbumPrice();
}
}

SWF- PriceQuoter, ,
:
package
{
import flash.display.Sprite;
import flash.system.Security;
import flash.text.*;
public class PriceQuoter extends Sprite
{
private var storeRequester:Object;
public function PriceQuoter() {
trace("Initializing child SWF");
trace("Child sandbox: " + Security.sandboxType);
storeRequester = loaderInfo.parentSandboxBridge;
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
addChild(tf);
tf.appendText("Store price of album is: " + storeRequester.getAlbumPrice());
tf.appendText("\n");
tf.appendText("Sale price of album is: " + storeRequester.getSaleAlbumPrice());
}
}
}

23.11.2012.

1174

ACTIONSCRIPT 3.0

(HTML)
Adobe AIR 1.0
HTML parentSandboxBridge childSandboxBridge
JavaScript . HTML .
1075.

API-
Adobe AIR 1.0
API-
, .
, , , (,
). , , readFile(path:String) (
) .
API- readApplicationSetting(),
. ,
, .



1073
AIR 1124


Adobe AIR 1.0
, -,
. - ,
-. , SWF-,
Flash Player ,
, . cookie
,
. AIR
, ,
.
.
,
.
1178.
AIR ,
URL-:

23.11.2012.

1175

1176

ACTIONSCRIPT 3.0

URL-

app:/

, . , ,
,
.

app-storage:/

, , .
, , ,
.

file:///

, . ,
, ,
, .

. AIR , URL- app:. ,



.
, AIR
.
app-storage:/ , .
, app-storage:/ , :

Mac OS: <appData>/<appId>/Local

Store/, <appData>
. , /Users/<user>/Library/Preferences

Windows: <appData>\<appId>\Local

Store\,

<appData> CSIDL_APPDATA. , C:\Documents and


Settings\<userName>\Application Data

Linux: <appData>/<appID>/Local

Store/, <appData> /home/<user>/.appdata


,
1178.


Adobe AIR 1.0
, ,
,
, .
AIR, .

Security.allowDomain()
Adobe AIR 1.0
AIR
, ,
Flash Player . ,
Adobe Flash , SWF-,
local-trusted, System.allowDomain(), SWF,

23.11.2012.

ACTIONSCRIPT 3.0

. application
AIR, , ,
.
,
Security.allowDomain().


Adobe AIR 1.0
AIR, ,
. ,
, ,
, .
,
.
, ,
, ,
.

. , AIR API-
, SWF-,
. ,
-,
SWF- .
.
, AIR ,
.
,
.
,
.
.
1171.

SWF
Adobe AIR 1.0
Loader.loadBytes() SWF .
, ,
.
, SWF API AIR.

23.11.2012.

1177

ACTIONSCRIPT 3.0

loadBytes() SWF. ,
loadBytes()
. ,
SWF .
loadBytes() AIR SWF;
. AIR loaderContext loadBytes()
allowLoadBytesCodeExecution, true,
loadBytes() SWF.
:
var loader:Loader = new Loader();
var loaderContext:LoaderContext = new LoaderContext();
loaderContext.allowLoadBytesCodeExecution = true;
loader.loadBytes(bytes, loaderContext);

loadBytes() SWF
allowLoadBytesCodeExecution LoaderContext false ( ), Loader
SecurityError.
. Adobe AIR API- .
,
allowLoadBytesCodeExecution LoaderContext.


Adobe AIR 1.0
AIR -, ,
. ,
AIR, . AIR
, - .
.

Adobe AIR 1.0


, ,
. ,
, , app-storage:/.
,
.
:

AIR ( ) .
AIR ( ),
.

.
URL app:/ SecurityError.

23.11.2012.

1178

ACTIONSCRIPT 3.0

API- AIR,
. Loader.loadBytes()
JavaScript eval().


Adobe AIR 1.0
AIR
.
.
, .
. :

.
URL-,
.

,
Adobe AIR 1.0

. :

,
. ,
, EncryptedLocalStore. .
763.

,
HTTPS TLS (Transport Layer Security).

.
. , , ,
, .


Adobe AIR 1.0
, .
,
. ,
. ,
, . .
, .
. ,
. ,
, , .
,
.

23.11.2012.

1179

ACTIONSCRIPT 3.0


Adobe AIR 1.0
AIR .
,
. AIR ,
, , .
,
. ,
, .
adt SDK, Flash, Flash Builder ,
adt . ,
.
.

Android
Adobe AIR 2.5
Android, , AIR
. AIR ,
, ,
.
AIR Android Android,
Android. AIR .
Android .




Android
Android .
, AIR ,
. ,
Android
.
AIR Android.
. , AIR,
:
ACCESS_COARSE_LOCATION ,
WIFI , Geolocation.
ACCESS_FINE_LOCATION: GPS Geolocation.
ACCESS_NETWORK_STATE ACCESS_WIFI_STATE:

NetworkInfo.
CAMERA: .

23.11.2012.

1180

ACTIONSCRIPT 3.0

INTERNET: . .
READ_PHONE_STATE: AIR .
RECORD_AUDIO: .
WAKE_LOCK DISABLE_KEYGUARD

SystemIdleMode.
WRITE_EXTERNAL_STORAGE: .


, Android, . AIR
Android Android APK,
Android, AIR. Android AIR
, .

Android , ,
.

, Android , 25
.

Android .
, ,
.

, ,
,
(AIR ).

Android Linux.
Linux, ,
. ,
. , (
SD-) , SD-
.
AIR cookie, .

, Android
, .

.
,
. deactivate, NativeApplication,
.
.

23.11.2012.

1181

ACTIONSCRIPT 3.0


Android:

Android
AIR Android ,
, SQL.
,
.
, . ,
,
, Android.
EncryptedLocalStore ,
Android. Android
,
. ,
, .
. ,
, . , ,
, .

iOS
iOS AIR . AIR
, ,
, .
AIR iOS iOS,
iOS. AIR . ,
iOS AIR. AIR
, .

, iOS, .
AIR iOS IPA,
iOS, AIR. iOS AIR ,
.

iOS , , Apple.
, .

iOS , Apple, .

iOS,
, .
.

23.11.2012.

1182

ACTIONSCRIPT 3.0

,
. deactivate, NativeApplication,
.
.

23.11.2012.

1183

1184

65.
ActionScript
ActionScript 3.0 ,
. - ,
.
Flash Professional Flash Builder
ActionScript 3.0 . ActionScript 3.0 Flash Professional
1186 ActionScript 3.0 Flash Builder 1187.
trace , .
ActionScript 3.0 ,
Flash Player 10.1 . . ActionScript
3.0 1188.
Flash Professional Flash Builder.
,
, .
. Flash - Adobe Developer Connection.


ActionScript 3.0:

( ActionScript 3.0)
( ActionScript 3.0)
, ( ZIP-
www.adobe.com/go/learn_programmingAS3samples_flash_ru)

:
var x:int = 5;
trace(x); // 5

, .
, .

ActionScript.
:

23.11.2012.

ACTIONSCRIPT 3.0
ActionScript

package {
public class Example1 {
public function Example1():void {
var x:int = 5;
trace(x); //5
}
}
}

, .
,
ActionScript 3.0 ,
ActionScript ,
. , :

ActionScript;
.FLA Flash Professional;
MXML Flash Builder;
, , ,
().
ZIP-.
, ZIP-
ZIP- Flash Professional CS5 Flex 4 (
www.adobe.com/go/learn_programmingAS3samples_flash_ru) :

AlarmClock ( : 151)
AlgorithmicVisualGenerator ( API :
249)

ASCIIArt ( : ASCII- 20)


CapabilitiesExplorer ( : 936)
CustomErrors ( : CustomErrors 75)
DisplayObjectTransformer ( :
234)

FilterWorkbench ( : Filter Workbench 314)


GlobalStockTicker (. ,
1024)

IntrovertIM_HTML ( API: ActionScript JavaScript -


910)

NewsLayout ( TextField: 418)


PlayList ( : PlayList 50)
PodcastPlayer ( : Podcast Player 500)
ProjectionDragger (: 385)
ReorderByZ ( Matrix3D 390)
RSSViewer ( XML ActionScript: RSS 122)
23.11.2012.

1185

ACTIONSCRIPT 3.0
ActionScript

RuntimeAssetsExplorer ( : RuntimeAssetsExplorer 356)


SimpleClock ( : 6)
SpinningMoon ( : 274)
SpriteArranger ( : SpriteArranger 219)
TelnetSocket ( TCP: Telnet 858)
VideoJukebox ( : Video Jukebox 542)
WikiEditor ( : Wiki 98)
WordSearch ( : WordSearch 620)

Flash Developer Center Flex Developer Center.

ActionScript 3.0 Flash


Professional
( ),
Flash Professional.
Flash Professional
Flash Professional, .
1 > .
2 Flash .

Flash.
3 .
4 .
5 > . .
6 , > .

Flash Professional
Flash Professional, .
1 > .
2 ActionScript .

.
3 .

, MovieClip:
import flash.display.MovieClip;
public class Example1 extends MovieClip{
//...
}

23.11.2012.

1186

ACTIONSCRIPT 3.0
ActionScript

, , ,
import.
4 > . , ,

(, ContextMenuExample.as).
. ,
flashx.textLayout.container.ContainerController, (package
flashx.textLayout.container.examples {). ,
(flashx/textLayout/container/examples) (
ActionScript package { ), .
5 > .
6 Flash (ActionScript 3.0)

. Flash.
7 ,

ActionScript (,
ContextMenuExample).
8 > . FLA- , ,

(, ContextMenuExample.as).
9 , > .

Flash Professional
ZIP-.
Flash Professional, .
1 .
2 Flash Professional > .
3 , . FLA

.
4 , > .

ActionScript 3.0 Flash Builder


( ),
Flash Builder.
Flash Builder
Flash Builder, .
1 Flex ( > > Flex)

MXML Flex ( > >


MXML). (, ContextMenuExample).
2 MXML <mx:Script>.
3 <mx:Script> </mx:Script>. MXML.
4 ,

MXML (, > ContextMenuExample).

23.11.2012.

1187

ACTIONSCRIPT 3.0
ActionScript

Flash Builder
Flash Builder, .
1 > > ActionScript.
2 (, ContextMenuExample) .

(
). , ActionScript.
3 ActionScript. ,

, ActionScript .
. ,
flashx.textLayout.container.ContainerController, (package
flashx.textLayout.container.examples {). ,
(flashx/textLayout/container/examples) (
ActionScript package { ), .
4 ,

ActionScript (, > ContextMenuExample).


Flash Builder
ZIP-.
Flash Builder, .
1 . (,

ContextMenuExample).
2 Flash Builder > > Flex.

, .
(, ContextMenuExample). (
). , .
3 , .
4 .

MXML . , .
5 ,

MXML (, > ContextMenuExample).

ActionScript 3.0

ActionScript 3.0 , Flash


Player 10.1. , , , .
, .
trace Flash
Professional Flash Builder .

23.11.2012.

1188

ACTIONSCRIPT 3.0
ActionScript

,
-. ,
.
1 SWF-, ActionScript 3.0 Flash

Professional 1186 ActionScript 3.0 Flash Builder 1187.


Flash Professional SWF- > . Flash Builder
SWF- , Flash Builder.
2 SWF- .

.
3 URL file:// SWF-.

file:://applications/myExample.swf.
- ,
.
1 SWF- HTML-. SWF-,

ActionScript 3.0 Flash Professional 1186 ActionScript 3.0


Flash Builder 1187. Flash Professional >
SWF-. , Flash HTML
. >
, : HTML SWF. Flash Builder ,
Flash Builder SWF- HTML-.
2 SWF- HTML- -.
3 URL http:// HTML-.

, http://www.myWebServer/examples/myExample.html.
.

,
.
. SWF-
. , 176 x 208 .
ActionScript 3.0
ActionScript 3.0.
.
,
. Adobe
ActionScript,
.
trace

trace . , TextField.
trace text .
, .

23.11.2012.

1189

ACTIONSCRIPT 3.0
ActionScript

function createTracingTextField(x:Number, y:Number,


width:Number, height:Number):TextField {
var tracingTF:TextField = new TextField();
tracingTF.x = x;
tracingTF.y = y;
tracingTF.width = width;
tracingTF.height = height;
// A border lets you more easily see the area the text field covers.
tracingTF.border = true;
// Left justifying means that the right side of the text field is automatically
// resized if a line of text is wider than the width of the text field.
// The bottom is also automatically resized if the number of lines of text
// exceed the length of the text field.
tracingTF.autoSize = TextFieldAutoSize.LEFT;
// Use a text size that works well on the device.
var myFormat:TextFormat = new TextFormat();
myFormat.size = 18;
tracingTF.defaultTextFormat = myFormat;
addChild(tracingTF);
return tracingTF;
}

, .
:
var traceField:TextField = createTracingTextField(10, 10, 150, 150);
// Use the newline character "\n" to force the text to the next line.
traceField.appendText("data to trace\n");
traceField.appendText("more data to trace\n");
// Use the following line to clear the text field.
traceField.appendText("");

appendText() .
( String ).
. , toString():
var albumYear:int = 1999;
traceField.appendText("albumYear = ");
traceField.appendText(albumYear.toString());


.
. ,
TextField myTextField,
.
// Use a text size that works well on the device.
var myFormat:TextFormat = new TextFormat();
myFormat.size = 18;
myTextField.defaultTextFormat = myFormat

23.11.2012.

1190

ACTIONSCRIPT 3.0
ActionScript



, SWF-.
, ,
. . KeyboardEvent
604.
,
. ,
ActionScript 3.0 .
.
. ,
.
. Adobe
ActionScript, .
.
192.

. , ,
. ,
, .
. , ,
, , Enter .
.
. 598.

. , ,
.
, ,
. Flash Player 10.1
. SWF-, Flash Player 10.1
.
.

, . ,
, . ,
API : 249
.
API- .
.
.
Flash Platform.

23.11.2012.

1191

ACTIONSCRIPT 3.0
ActionScript



.
,
, .
.
Flash Platform.

23.11.2012.

1192

1193

66. SQL

Adobe AIR SQL, SQL,
SQL,
SQLite.
. .
. AIR
( ).
SQL, SQL Adobe
Air. SQL.
SQL, Adobe AIR.
SQL-92. , -,
SQL,
SQL. SQL,
AIR, SQL-92
SQL.
SQL
, ,
.


: SQL .
: .

::= .

| .
[] .
.

() ( , )
, , ,
.

+ , , ,
.

* , , ,
0 .


*
, 0 .

23.11.2012.

ACTIONSCRIPT 3.0
SQL

. .
, .
() ,
.

, .

SQL
SQL SQL Adobe AIR.
, ,
. :

SQL
(SELECT, INSERT, UPDATE DELETE)
( CREATE, ALTER DROP , ,
)


(, )


SQL
SQL

SQL

SQL.
SQL, , .

, SQL ,
. SQL ,
SQL. ,
,
. . COLLATE.
(, , , . .)

SQL.
. SQL . ,
, SQL
, .


SQL.
, , .
: SELECT, INSERT, UPDATE DELETE.

23.11.2012.

1194

ACTIONSCRIPT 3.0
SQL

SELECT
SELECT . SELECT
0 , .
,
SELECT FROM.
sql-statement

::=

result
result-column
table-list
table

::=
::=
::=
::=

join-op
join-args
compound-op
sort-expr-list
sort-order
collation-name

::=
::=
::=
::=
::=
::=

SELECT [ALL | DISTINCT] result


[FROM table-list]
[WHERE expr]
[GROUP BY expr-list]
[HAVING expr]
[compound-op select-statement]*
[ORDER BY sort-expr-list]
[LIMIT integer [( OFFSET | , ) integer]]
result-column [, result-column]*
* | table-name . * | expr [[AS] string]
table [ join-op table join-args ]*
table-name [AS alias] |
( select ) [AS alias]
, | [NATURAL] [LEFT | RIGHT | FULL] [OUTER | INNER | CROSS] JOIN
[ON expr] [USING ( id-list )]
UNION | UNION ALL | INTERSECT | EXCEPT
expr [sort-order] [, expr [sort-order]]*
[COLLATE collation-name] [ASC | DESC]
BINARY | NOCASE

.
*, .
.*, .
DISTINCT , .
NULL . ,
ALL.
, FROM.
,
. ,
JOIN. LEFT OUTER
JOIN. ON join-args .
FROM. FROM
. ,
.
WHERE , .
WHERE .
WHERE , WHERE
.
GROUP BY
. GROUP BY , .
GROUP BY ,
SELECT.

23.11.2012.

1195

ACTIONSCRIPT 3.0
SQL

HAVING WHERE , ,
. HAVING ,
GROUP BY. HAVING ,
. HAVING SELECT.
WHERE, HAVING .
ORDER BY . sort-expr-list,
ORDER BY, ,
. SELECT,
SELECT ( compound-op)
. sort
sort-order,
COLLATE , , / ASC
DESC, ( ). sort-order
, ( ).
COLLATE . COLLATE.
LIMIT , .
LIMIT , . OFFSET
LIMIT , .
SELECT LIMIT SELECT,
. , LIMIT
OFFSET, , .
OFFSET , , .
:
SQL.
SELECT SELECT,
UNION, UNION ALL, INTERSECT EXCEPT.
SELECT, SELECT,
. ORDER BY,
SELECT ( LIMIT, ).
UNION UNION ALL
SELECT . , UNION
, UNION ALL .
INTERSECT ,
SELECT. EXCEPT SELECT
SELECT. SELECT,
.
. .
AIR 2.5, SQL CAST BLOB
ActionScript ByteArray. ,
, AMF, ByteArray:
stmt.text = "SELECT CAST(data AS ByteArray) AS data FROM pictures;";
stmt.execute();
var result:SQLResult = stmt.getResult();
var bytes:ByteArray = result.data[0].data;

INSERT
INSERT .

23.11.2012.

1196

ACTIONSCRIPT 3.0
SQL

sql-statement ::= INSERT [OR conflict-algorithm] INTO [database-name.] table-name [(columnlist)] VALUES (value-list) |
INSERT [OR conflict-algorithm] INTO [database-name.] table-name [(columnlist)] select-statement
REPLACE INTO [database-name.] table-name [(column-list)] VALUES (value-list) |
REPLACE INTO [database-name.] table-name [(column-list)] select-statement

( VALUES) .
column-list , .
column-list , .
, , ,
, NULL, .
INSERT SELECT. column-list
, , SELECT,
; ,
column-list. SELECT .
SELECT . SELECT .
SELECT.
conflict-algorithm
, .
.
1205.
REPLACE INTO INSERT [OR
conflict-algorithm] REPLACE ( INSERT OR REPLACE...).
REPLACE INTO INSERT [OR
conflict-algorithm] REPLACE ( INSERT OR REPLACE...).
UPDATE
update .
sql-statement
[WHERE expr]

::=

UPDATE [database-name.] table-name SET column1=value1, column2=value2,...

UPDATE, ,
. SET ,
, . WHERE
, .
DELETE
.
sql-statement

::=

DELETE FROM [database-name.] table-name [WHERE expr]

DELETE FROM, ,
.
WHERE, . WHERE,
, . WHERE
. . .

23.11.2012.

1197

ACTIONSCRIPT 3.0
SQL


, ,
, , . .

:
CREATE TABLE
ALTER TABLE
DROP TABLE
:
CREATE INDEX
DROP INDEX
:
CREATE VIEWS
DROP VIEWS
:
CREATE TRIGGERS
DROP TRIGGERS
CREATE TABLE
CREATE TABLE CREATE TABLE,
, ( ) .
.
sql-statement
name

::= CREATE [TEMP | TEMPORARY] TABLE [IF NOT EXISTS] [database-name.] table-

sql-statement
statement
column-def
type
column-constraint

::=

( column-def [, column-def]* [, constraint]* )


CREATE [TEMP | TEMPORARY] TABLE [database-name.] table-name AS select-

::=
::=
::=

name [type] [[CONSTRAINT name] column-constraint]*


typename | typename ( number ) | typename ( number , number )
NOT NULL [ conflict-clause ] |
PRIMARY KEY [sort-order] [ conflict-clause ] [AUTOINCREMENT] |
UNIQUE [conflict-clause] |
CHECK ( expr ) |
DEFAULT default-value |
COLLATE collation-name
constraint
::= PRIMARY KEY ( column-list ) [conflict-clause] |
UNIQUE ( column-list ) [conflict-clause] |
CHECK ( expr )
conflict-clause
::= ON CONFLICT conflict-algorithm
conflict-algorithm ::= ROLLBACK | ABORT | FAIL | IGNORE | REPLACE
default-value
::= NULL | string | number | CURRENT_TIME | CURRENT_DATE | CURRENT_TIMESTAMP
sort-order
::= ASC | DESC
collation-name
::= BINARY | NOCASE
column-list
::= column-name [, column-name]*

23.11.2012.

1198

ACTIONSCRIPT 3.0
SQL

,
. , .

, . .
.
NOT NULL , NULL.
UNIQUE .
:
. CREATE TABLE UNIQUE,
, UNIQUE, /
UNIQUE .
CHECK , (true),
. CHECK
.
COLLATE ,
.
BINARY. COLLATE . COLLATE.
DEFAULT ,
INSERT. NULL,
.
( ): CURRENT_TIME, CURRENT_DATE CURRENT_TIMESTAMP.
NULL, , ,
INSERT . CURRENT_TIME,
CURRENT_DATE CURRENT_TIMESTAMP, / UTC.
CURRENT_TIME HH:MM:SS (::). CURRENT_DATE
YYYY-MM-DD (--). CURRENT_TIMESTAMP YYYY-MM-DD
HH:MM:SS (-- ::.)
PRIMARY KEY UNIQUE
. PRIMARY KEY
INTEGER ( , int),
. ,
. ( , SQLite
INTEGER , Adobe
AIR INTEGER, int.)
INTEGER PRIMARY KEY,
.
: ROWID, OID _ROWID_. ,
INTEGER PRIMARY KEY .
INTEGER PRIMARY KEY,
, .
INTEGER PRIMARY KEY AUTOINCREMENT.
AUTOINCREMENT
INTEGER PRIMARY KEY,
INSERT, .

23.11.2012.

1199

ACTIONSCRIPT 3.0
SQL

CREATE TABLE PRIMARY KEY.


PRIMARY KEY .
NOT NULL.
conflict-clause, ,
.
ABORT.
. INSERT UPDATE
, , CREATE
TABLE. . ON CONFLICT
1205.
, FOREIGN KEY, ,
.
CREATE TABLE TEMP TEMPORARY,
(
SQLConnection). . ,
, .
, .
database-name,
( SQLConnection attach()
). database-name TEMP,
database-name temp.
TEMP, (
SQLConnection open() openAsync()).
.
.
CREATE TABLE AS .
.
IF NOT EXISTS ,
CREATE TABLE.
DROP TABLE, ALTER TABLE
.
ALTER TABLE
ALTER TABLE
. .
sql-statement ::= ALTER TABLE [database-name.] table-name alteration
alteration
::= RENAME TO new-table-name
alteration
::= ADD [COLUMN] column-def

RENAME TO , ,
[database-name.] table-name, , new-table-name.
.
.

23.11.2012.

1200

ACTIONSCRIPT 3.0
SQL

,
. , ,
, ,
.
, ,
.
ADD [COLUMN] .
. column-def
, CREATE TABLE, .

PRIMARY KEY UNIQUE.


CURRENT_TIME, CURRENT_DATE
CURRENT_TIMESTAMP.

NOT NULL, NULL.


ALTER TABLE .
DROP TABLE
DROP TABLE , CREATE TABLE.
, table-name.
. . , , .
sql-statement

::=

DROP TABLE [IF EXISTS] [database-name.] table-name

DROP TABLE .
INSERT.
, SQLConnection.clean(). autoClean
true, .
IF EXISTS , ,
.
CREATE INDEX
CREATE INDEX CREATE INDEX,
, ON, , ,
,
.
sql-statement

::=

column-name

::=

CREATE [UNIQUE] INDEX [IF NOT EXISTS] [database-name.] index-name


ON table-name ( column-name [, column-name]* )
name [COLLATE collation-name] [ASC | DESC]

ASC DESC,
, .
.
COLLATE ,
.
, CREATE TABLE.
, BINARY. COLLATE
. COLLATE.

23.11.2012.

1201

ACTIONSCRIPT 3.0
SQL

, .
.
DROP INDEX
DROP INDEX , CREATE INDEX.
.
CREATE INDEX.
sql-statement ::= DROP INDEX [IF EXISTS] [database-name.] index-name

DROP INDEX .
INSERT.
, SQLConnection.clean(). autoClean
true, .
CREATE VIEW
CREATE VIEW SELECT.
FROM SELECT .
( )
, .
sql-statement ::= CREATE [TEMP | TEMPORARY] VIEW [IF NOT EXISTS] [database-name.] view-name AS
select-statement

CREATE VIEW TEMP TEMPORARY,


SQLConnection,
. .
[database-name], (
SQLConnection attach() ).
[database-name] TEMP, [database-name]
. TEMP,
( SQLConnection
open() openAsync()).
. DELETE, INSERT UPDATE,
(INSTEAD OF DELETE, INSTEAD OF INSERT, INSTEAD
OF UPDATE). . CREATE TRIGGER.
DROP VIEW.
DROP VIEW
DROP VIEW , CREATE VIEW.
sql-statement ::= DROP VIEW [IF EXISTS] view-name

, view-name. ,
.
CREATE TRIGGER
CREATE TRIGGER .
(trigger-action),
(database-event).

23.11.2012.

1202

ACTIONSCRIPT 3.0
SQL

sql-statement
name

sql-statement
name

::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] [database-name.] trigger[BEFORE | AFTER] database-event
ON table-name
trigger-action
::= CREATE [TEMP | TEMPORARY] TRIGGER [IF NOT EXISTS] [database-name.] trigger-

database-event

::=

trigger-action

::=

trigger-step

::=

column-list

::=

INSTEAD OF database-event
ON view-name
trigger-action
DELETE |
INSERT |
UPDATE |
UPDATE OF column-list
[FOR EACH ROW] [WHEN expr]
BEGIN
trigger-step ;
[ trigger-step ; ]*
END
update-statement |
insert-statement |
delete-statement |
select-statement
column-name [, column-name]*

, , DELETE,
INSERT UPDATE , ,
UPDATE .
, TEMP TEMPORARY.
, ,
SQLConnection. (BEFORE AFTER),
BEFORE.
FOR EACH ROW, FOR EACH ROW
. FOR EACH ROW trigger-step
, , ,
, WHEN .
WHEN, SQL, trigger-step,
, WHEN. WHEN , SQL
.
( trigger-action) (pre-change post-change)
OLD NEW.
OLD NEW , . OLD
, , , ,
. NEW ,
, , ,
. WHEN trigger-step
, , NEW.column-name
OLD.column-name, column-name , .
OLD NEW database-event, .

INSERT: NEW .
UPDATE: NEW OLD .
23.11.2012.

1203

ACTIONSCRIPT 3.0
SQL

DELETE: OLD .
(BEFORE, AFTER INSTEAD OF) , trigger-step
, . ON CONFLICT
UPDATE INSERT trigger-step. ON CONFLICT
, ,
.
, INSTEAD OF .
INSTEAD OF INSERT, INSTEAD OF DELETE INSTEAD OF UPDATE,
(INSERT, DELETE, UPDATE) .
INSERT, DELETE UPDATE
. INSTEAD OF, , ,
, .
.
INTEGER PRIMARY KEY .
BEFORE INTEGER PRIMARY KEY ,
, , . ,
PRIMARY KEY INTEGER PRIMARY KEY.
DROP TRIGGER.
.
RAISE ()
SQL RAISE() trigger-step.
:
raise-function

::=

RAISE
RAISE
RAISE
RAISE

(
(
(
(

ABORT, error-message ) |
FAIL, error-message ) |
ROLLBACK, error-message ) |
IGNORE )

,
ON CONFLICT (ABORT, FAIL ROLLBACK),
. ROLLBACK ,
SQLStatement, execute(),
(SQLErrorEvent.ERROR). SQLError error
details, error-message, RAISE().
RAISE(IGNORE), ,
, , .
. , ,
, .
. ON CONFLICT ( ).
DROP TRIGGER
DROP TRIGGER , CREATE TRIGGER.
sql-statement

::=

DROP TRIGGER [IF EXISTS] [database-name.] trigger-name

. ,
.

23.11.2012.

1204

ACTIONSCRIPT 3.0
SQL


, SQL,
, , ,
.
COLLATE
COLLATE SELECT, CREATE TABLE CREATE INDEX
, .
sql-statement
collation-name

::=
::=

COLLATE collation-name
BINARY | NOCASE

BINARY. BINARY
TEXT, ,
.
NOCASE TEXT.
NOCASE .
NULL, BLOB, INTEGER REAL.
BINARY, COLLATE
CREATE TABLE.
TEXT
.

,
, ,
, . ,
.
, BINARY.

BETWEEN...AND >= <=.


, x BETWEEN y AND z x >= y AND x <= z. ,
BETWEEN...AND .

IN =,
. , ,
x IN (y, z), x, x .
BINARY.

ORDER BY, SELECT,


, .
. , ,
ORDER BY, ,
, . ,
BINARY.
EXPLAIN
EXPLAIN SQL.
sql-statement

::=

EXPLAIN sql-statement

23.11.2012.

1205

ACTIONSCRIPT 3.0
SQL

EXPLAIN SQL,
,
, EXPLAIN. EXPLAIN
,
SQL,
.
ON CONFLICT ( )
ON CONFLICT SQL. ,
SQL.
conflict-clause
conflict-clause
conflict-algorithm

::=
::=
::=

ON CONFLICT conflict-algorithm
OR conflict-algorithm
ROLLBACK |
ABORT |
FAIL |
IGNORE |
REPLACE

ON CONFLICT, ON CONFLICT,
CREATE TABLE. INSERT UPDATE
, ON CONFLICT OR,
. , INSERT ON CONFLICT IGNORE INSERT OR IGNORE.
, .
ON CONFLICT ,
. : ROLLBACK, ABORT, FAIL, IGNORE REPLACE.
ABORT. .
ROLLBACK (ROLLBACK),

. , SQLStatement .
( , ),
, ABORT.
ABORT , ,

SQLStatement . (ROLLBACK) , ,
, . ABORT
.
FAIL SQLStatement

. , ,
. , UPDATE
100, , 99 ,
100 .
IGNORE , ,

. , .
, , .
.
REPLACE UNIQUE,
, . ,
, . .
NOT NULL, NULL ,
. , ABORT.

23.11.2012.

1206

ACTIONSCRIPT 3.0
SQL

CHECK, IGNORE.
, ,
.
, OR INSERT UPDATE,
, CREATE TABLE. CREATE TABLE
INSERT UPDATE, ABORT.
REINDEX
REINDEX .
, .
sql-statement
sql-statement

::=
::=

REINDEX collation-name
REINDEX [database-name .] ( table-name | index-name )

,
. , ,
table-name. index-name ,
.

SQL, SQL.
. , ,
.
comment

::=

single-line-comment ::=
block-comment
::=

single-line-comment |
block-comment
-- single-line
/* multiple-lines or block [*/]

.
.
.
, .
. SQL
. , ,
, SQL.
. .

SQL.
SQL.

23.11.2012.

1207

ACTIONSCRIPT 3.0
SQL

expr

::=

expr binary-op expr |


expr [NOT] like-op expr [ESCAPE expr] |
unary-op expr |
( expr ) |
column-name |
table-name.column-name |
database-name.table-name.column-name |
literal-value |
parameter |
function-name( expr-list | * ) |
expr ISNULL |
expr NOTNULL |
expr [NOT] BETWEEN expr AND expr |
expr [NOT] IN ( value-list ) |
expr [NOT] IN ( select-statement ) |
expr [NOT] IN [database-name.] table-name |
[EXISTS] ( select-statement ) |
CASE [expr] ( WHEN expr THEN expr )+ [ELSE expr] END |
CAST ( expr AS type ) |
expr COLLATE collation-name
LIKE | GLOB
see Operators
see Operators
:param-name | @param-name | ?
literal-value [, literal-value]*
literal-string | literal-number | literal-boolean | literal-blob |

like-op
::=
binary-op
::=
unary-op
::=
parameter
::=
value-list
::=
literal-value
::=
literal-null
literal-string ::= 'string value'
literal-number ::= integer | number
literal-boolean ::= true | false
literal-blob ::= X'string of hexadecimal data'
literal-null ::= NULL

,
. ,
(true false) .
( WHERE, HAVING,
ON JOIN CHECK)
. :

ISNULL
NOTNULL
IN ()
EXISTS ()
LIKE
GLOB

( , )

23.11.2012.

1208

ACTIONSCRIPT 3.0
SQL


.
. .
().
'.
, , : ''.
true () false ().
.
(BLOB) ,
x X , X'53514697465'.
NULL.

, CREATE TABLE,
: ROWID, OID _ROWID_.
( ),
. ,
CREATE TABLE .
, . ,
, , UPDATE INSERT.
SELECT * FROM .
SELECT
SELECT IN,
( ) EXISTS.
IN SELECT
. SELECT (
, UNION EXCEPT). EXISTS
SELECT TRUE,
, FALSE, . SELECT
-,
, . SELECT
, ,
.
SELECT IN, IN TRUE,
SELECT.
IN NOT, .
SELECT , IN,
SELECT. SELECT
, , , . SELECT ,
SELECT NULL.
CAST
CAST .
,
CREATE TABLE. . .

23.11.2012.

1209

ACTIONSCRIPT 3.0
SQL


SQL .

: , ,

;
;
.
, RAISE(),
, .
CREATE TRIGGER. RAISE() . CREATE TRIGGER > RAISE().
SQL, .

.
SELECT GROUP BY.
AVG(X)

COUNT(X)
COUNT(*)
MAX(X)
MIN(X)

SUM(X)
TOTAL(X)

X .
(BLOB), ,
0. AVG()
, .
X . (
*) .
.
.
.
.
, NULL.
.
, SUM() NULL, TOTAL() 0.0.
TOTAL() .
SUM() , .
, SUM(), ,
SUM() .
.

, ,
DISTINCT.
. , COUNT(DISTINCT x)
X, .

.
ABS(X)
COALESCE(X, Y, ...)

X.
. ,
NULL. .

23.11.2012.

1210

ACTIONSCRIPT 3.0
SQL

GLOB(X, Y)
IFNULL(X, Y)
HEX(X)
LAST_INSERT_ROWID(
)

LENGTH(X)
LIKE(X, Y [, Z])

LOWER(X)
LTRIM(X) LTRIM(X, Y)

MAX(X, Y, ...)

MIN(X, Y, ...)

NULLIF(X, Y)
QUOTE(X)

RANDOM(*)

RANDOMBLOB(N)

ROUND(X) ROUND(X,
Y)
RTRIM(X) RTRIM(X, Y)

SUBSTR(X, Y, Z)

TRIM(X) TRIM(X, Y)

TYPEOF(X)

UPPER(X)
ZEROBLOB(N)

X GLOB Y.
. ,
NULL. COALESCE().
BLOB.
.
( ) ,
SQLConnection.
,
SQLConnection.lastInsertRowID.
X ( ).
X LIKE Y [ESCAPE Z] SQL.
ESCAPE,
. .
X, .
, X.
Y, Y,
X.
.
, .
. , MAX()
, 2 ,
, .
.
, .
. , MIN()
, 2 ,
, .
, .
NULL.
, ,
SQL.
. .
BLOB .

.
9223372036854775808
9223372036854775807.
.
N ,
. N
. . N
, .
X Y .
Y , 0.
, X.
Y, Y,
X.
X, Y-
Z . X 1. Y
,
, .
, X.
Y, Y,
X.
X. : null, integer, real, text
blob. .
.
X, .
, N 0x00.

23.11.2012.

1211

ACTIONSCRIPT 3.0
SQL


,
. ,
, , .
DATE.
, DATE, .
DATE(T, ...)

TIME(T, ...)

DATETIME(T, ...)

JULIANDAY(T, ...)

STRFTIME(F, T, ...)

DATE() , YYYY-MM-DD (-). (T) ,


. .
.
TIME() , HH:MM:SS (::).
(T) ,
. .
.
DATETIME() , YYYY-MMDD HH:MM:SS (-- ::). (T)
, .
.
.
JULIANDAY() , ,
24 4714 , .
(T) ,
. .
.
STRFTIME() ,
, F.
:
%d
%f SS.SSS
%H 00-24
%j 001-366
%J
%m 01-12
%M 00-59
%s 1970-01-01
%S 00-59
%w 0-6 ( = 0)
%W 00-53
%Y 0000-9999
%% - %
(T) ,
. .
.


.
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS

2007-06-15
2007-06-15 07:30
2007-06-15 07:30:59
2007-06-15 07:30:59.152

23.11.2012.

1212

ACTIONSCRIPT 3.0
SQL

YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDD.DDDD

2007-06-15T07:30
2007-06-15T07:30:59
2007-06-15T07:30:59.152
07:30 ( 2000-01-01)
07:30:59 ( 2000-01-01)
07:30:59:152 ( 2000-01-01)

(UCT).
,
.

T T, . ,
, 2001-01-01.

,
. .
NNN days
NNN hours
NNN minutes
NNN.NNNN seconds
NNN months
NNN years
start of month
start of year
start of day
weekday N
localtime
utc

, .
, .
, .
,

, .
, .
.
.
.
. (0 =
, 1 = . .)
.
(UCT).

SQL , ,
, , SQL.

SQL ,
.
*
/
%
+
<< >> & |
< >=
> >=
=
==
!=
AND
OR

<> IN

.
!

NOT

COLLATE . COLLATE
. ,
.

23.11.2012.

1213

ACTIONSCRIPT 3.0
SQL

, .
= ==. != <>.
|| , .
% .
,
||, .
SQL
LIKE
LIKE .
expr
pattern

::=
::=

(column-name | expr) LIKE pattern


'[ string | % | _ ]'

LIKE , ,
. (%) .
. (_)
.
, . (.
7- .
LIKE 8- iso8859 UTF-8. ,
'a' LIKE 'A' TRUE, '' LIKE '' FALSE).
SQLConnection.caseSensitiveLike.
ESCAPE, ,
ESCAPE, , .
LIKE . ,
, , ,
.
GLOB
GLOB LIKE, Unix
. LIKE, GLOB .
IN
IN , (
).
in-expr

::=

value-list

::=

expr [NOT] IN
expr [NOT] IN
expr [NOT] IN
literal-value

( value-list ) |
( select-statement ) |
[database-name.] table-name
[, literal-value]*


SELECT. SELECT
IN . SELECT .
BETWEEN...AND
BETWEEN...AND >= <=. ,
x BETWEEN y AND z x >= y AND x <= z.
NOT

23.11.2012.

1214

ACTIONSCRIPT 3.0
SQL

NOT . GLOB, LIKE IN


NOT, ( , ,
).

,
SQLStatement.parameters.
.
?
:AAAA

@AAAA

.
( ) .
, ,
AAAA.
SQL.
.
.

SQL
SQL, Adobe AIR.
FOREIGN KEY FOREIGN KEY ,

.
FOR EACH STATEMENT ( FOR EACH

ROW). INSTEAD OF ( ).
( , ) .
ALTER TABLE RENAME TABLE ADD COLUMN ALTER TABLE.
ALTER TABLE, DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT .
., .
.
RIGHT FULL OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN .
. DELETE,
INSERT UPDATE. INSTEAD OF, ,
(DELETE, INSERT UPDATE).
.
GRANT REVOKE .

, .
GRANT REVOKE, RDBMS, .
SQL SQLite SQLite,
Adobe AIR.
SQLConnection.
SQL, (BEGIN, END, COMMIT, ROLLBACK)

SQLConnection, :
SQLConnection.begin(), SQLConnection.commit() SQLConnection.rollback().
ANALYZE SQLConnection.analyze().
ATTACH SQLConnection.attach().
COPY .

23.11.2012.

1215

ACTIONSCRIPT 3.0
SQL

CREATE VIRTUAL TABLE .


DETACH SQLConnection.detach().
PRAGMA .
VACUUM SQLConnection.compact().
. , sqlite_master
sqlite_, SQL. API-
, - .
. SQLConnection.loadSchema().
(MATCH() REGEX()) SQL.

SQLite Adobe AIR.


. Adobe AIR (
0, 1 . .).
INTEGER PRIMARY KEY

, INTEGER PRIMARY
KEY. , INTEGER (,
int), , . Adobe
AIR int ( INTEGER) INTEGER.
, int PRIMARY KEY,
. . CREATE TABLE .

SQL
SQLite , Adobe
AIR. ( , , SQL,
).
Boolean Boolean.
Date Date.
int int ( INTEGER).
Number Number ( REAL).
Object Object ,

AMF3. ( , ,
, ,
.)
String String ( TEXT).
XML XML ActionScript (E4X).
XMLList XMLList ActionScript (E4X).

SQLite, Adobe AIR.


true true,
BOOLEAN.
false false,
BOOLEAN.

23.11.2012.

1216

ACTIONSCRIPT 3.0
SQL


SQL, SQL Adobe AIR ,
.
: .
,
.

1217
1218
1220
1221
1221
1221
SELECT 1222


,
. .
NULL NULL.
INTEGER .
REAL .
TEXT ( 256 ).
BLOB (. Binary Large Object, BLOB);

, ( 256 ).
, , SQL, ,
SQL ,
SQL.
, SQL, TEXT,
, INTEGER,
, , REAL,
, , NULL,
NULL. BLOB
X'ABCD'. . .
, SQLStatement.parameters,
,
. , int INTEGER, Number
REAL, String TEXT, ByteArray BLOB.

23.11.2012.

1217

ACTIONSCRIPT 3.0
SQL


. ,
( INSERT UPDATE),
. , Date ( Date
ActionScript JavaScript) TEXT,
Date String (
toString()). ,
. SELECT,
, , ,
.
NULL, ActionScript JavaScript (null)
NULL .
NULL SELECT,
ActionScript JavaScript (null) . NULL,
, , , ,
( Number Boolean).
:

TEXT ( String)
NUMERIC
INTEGER ( int)
REAL ( Number)
Boolean
Date
XML
XMLLIST
Object
NONE
TEXT ( String)
TEXT String , NULL, TEXT BLOB.
TEXT,
.
NUMERIC
NUMERIC , NULL, REAL INTEGER.
NUMERIC,
.
INTEGER REAL (, '10.05'
REAL). , .
NULL, . ,
NUMERIC, , .
, 0, uint.
, int.
( ), Number.

23.11.2012.

1218

ACTIONSCRIPT 3.0
SQL

INTEGER ( int)
INTEGER NUMERIC,
. ( Number)
,
,
INTEGER.
.
REAL ( Number)
REAL NUMBER , NUMERIC.
.
REAL Number.
Boolean
Boolean true () false (). Boolean
, Boolean ActionScript JavaScript.
String, String true, String
false. ,
true, 0 false. (Boolean) SELECT,
Boolean.
INTEGER (0 false 1 true) Boolean .
Date
Date . Date ,
Date ActionScript JavaScript. String
Date .
, . Number,
int uint, ,
. Date, SELECT,
Date. Date
REAL,
.
XML XMLList
XML XMLList XML.
XML SQLStatement,
ActionScript XML() XMLList().
XML, .
SQL (, INSERT INTO (col1) VALUES ('Invalid XML (no closing tag)'),
, .
, XML.
Data XML XMLList TEXT NULL.
Object
Object ActionScript JavaScript,
Object, Object, Array
. Object AMF3,
BLOB.
AMF3, ,

23.11.2012.

1219

ACTIONSCRIPT 3.0
SQL

. , ActionScript, ,
.
,
flash.net.registerClassAlias() ( Flex [RemoteObject]).
, .
, ,
,
( Object) ,
.
NONE
NONE .
.

, CREATE TABLE.
( ).

CHAR, CLOB, STRI TEXT,


TEXT/String. , VARCHAR CHAR
TEXT.

BLOB ,
NONE.

XMLL, XMLList.
XML, XML.
OBJE, Object.
BOOL, Boolean.
DATE, Date.
INT ( UINT), INTEGER/int.
REAL, NUMB, FLOA DOUB,
REAL/Number.

NUMERIC.
CREATE TABLE t AS SELECT...,
, NONE.


=, <, <=, >= !=,
, IN BETWEEN.
. .
.
.

NULL
( NULL).

23.11.2012.

1220

ACTIONSCRIPT 3.0
SQL

INTEGER REAL TEXT BLOB. INTEGER


REAL INTEGER REAL .

TEXT BLOB. TEXT


.

BLOB .
BETWEEN . , a
BETWEEN b AND c a >= b AND a <= c, , a
, .
a IN (SELECT b ....) , ,
a = b. , b , a , b
a . a IN (x, y, z) a = +x OR a = +y OR a = +z.
IN ( x, y z) ,
. IN ,
. ,
.
COLLATE.
. COLLATE.


*, /, %, + -
NUMERIC. -
NUMERIC, NULL.
||
TEXT. - TEXT,
NULL. :
NULL, BLOB , TEXT.


ORDER BY
NULL. INTEGER REAL , TEXT
(BINARY NOCASE).
BLOB . .


GROUP BY
. INTEGER REAL, ,
. GROUP BY .

23.11.2012.

1221

ACTIONSCRIPT 3.0
SQL

SELECT
SELECT (UNION, INTERSECT EXCEPT) .
. ,
SELECT,
, . ,
SELECT ( -
) . SELECT
SELECT ,
.

23.11.2012.

1222

1223

67.
SQL,

SQLError ,
SQL Adobe AIR. SQLError details,
. ,
, detailID SQLError.
detailID
details. .
detailArguments
. ,
details ,
.
detailID
. - ,
detailArguments.
, SQL.
SQLError detailID
1001
1102
1003
1004

1005
1006
1007
1008
1009
1010
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011



.
.
() %s [,| %s] ,
SQL.
. SQL %d
() %d .
%s [,| %s].
.
pageSize.
%s %s %s.
%s %s .
%s %s.
%s.
Parser stack overflow. ( .)
Too many arguments on function '%s' (
%s.)
%s:
: %s
PRAGMA SQL .
Not a writable directory. ( .)
Unknown or unsupported join type: '%s %s %s' (
: %s %s %s.)
RIGHT FULL OUTER .
A NATURAL join may not have an ON or USING clause. ( NATURAL
ON USING.)
Cannot have both ON and USING clauses in the same join. (
ON, USING, .)
Cannot join using column '%s' - column not present in both tables. (
%s,
.)

23.11.2012.

ACTIONSCRIPT 3.0
SQL,

2012

2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2030
2032
2033
2034
2035
2036
2037
2043
2044
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2058
2060
2061

Only a single result allowed for a SELECT that is part of an expression. (


SELECT,
.)
No such table: '[%s.]%s' ( : [%s.]%s.)
No tables specified. ( .)
Too many columns in result set|too many columns on '%s'. (
| %s.)
%s ORDER|GROUP BY , 1 %d
ORDER BY. (
ORDER BY.)
%s ORDER BY term out of range - should be between 1 and %d. ( %s ORDER
BY 1 %d.)
%r ORDER BY term does not match any column in the result set. ( %r ORDER
BY .)
ORDER BY clause should come after '%s' not before. ( ORDER BY
%s, .)
LIMIT clause should come after '%s' not before. ( LIMIT
%s, .)
SELECT %s
.
A GROUP BY clause is required before HAVING. ( HAVING
GROUP BY.)
Aggregate functions are not allowed in the GROUP BY clause. (
GROUP BY .)
DISTINCT .
Too many terms in compound SELECT (
SELECT.)
Too many terms in ORDER|GROUP BY clause (
ORDER|GROUP BY.)
Temporary trigger may not have qualified name (
.)
Trigger '%s' already exists ( %s .)
Cannot create BEFORE|AFTER trigger on view: '%s'. (
BEFORE|AFTER : %s.)
Cannot create INSTEAD OF trigger on table: '%s'. (
INSTEAD OF : %s.)
No such trigger: '%s' ( : %s.)
Recursive triggers not supported ('%s'). (
(%s).)
No such column: %s[.%s[.%s]] ( : %s[.%s[.%s]])
VACUUM SQL.
Table '%s': indexing function returned an invalid plan. ( %s:
.)
At most %d tables in a join. ( %d .)
PRIMARY KEY.
UNIQUE.
NOT NULL NULL.
,
.
.
ANALYZE SQL.
Invalid name: '%s' ( : %s.)
ATTACH SQL.
%s %s %s
Access to '[%s.]%s.%s' is prohibited. ( [%s.]%s.%s .)
Not authorized. ( .)
No such view: '[%s.]%s' ( : [%s.]%s.)
Temporary table name must be unqualified. (
.)
Table '%s' already exists. ( %s .)

23.11.2012.

1224

ACTIONSCRIPT 3.0
SQL,

2062
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074

2075
2076
2077
2080
2081
2082

2083
2084
2085
2086

2087
2088
2089
2090
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102

There is already an index named: '%s' ( :


%s.)
Duplicate column name: '%s' ( : %s.)
Table '%s' has more than one primary key. ( %s
.)
AUTOINCREMENT INTEGER PRIMARY KEY
No such collation sequence: '%s' ( :
%s.)
Parameters are not allowed in views. (
.)
View '%s' is circularly defined. ( %s .)
Table '%s' may not be dropped. ( %s.)
Use DROP VIEW to delete view '%s' ( DROP VIEW
%s.)
Use DROP TABLE to delete table '%s' ( DROP TABLE
%s.)
Foreign key on '%s' should reference only one column of table '%s' (
%s %s.)
Number of columns in foreign key does not match the number of columns in the
referenced table. (
.)
Unknown column '%s' in foreign key definition. ( %s
.)
Table '%s' may not be indexed. ( %s.)
Views may not be indexed. ( .)
Conflicting ON CONFLICT clauses specified. (
ON CONFLICT.)
No such index: '%s' ( : %s.)
Index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped.
( , UNIQUE
PRIMARY KEY.)
BEGIN SQL .
COMMIT SQL .
ROLLBACK SQL .
Unable to open a temporary database file for storing temporary tables.
(
.)
Unable to identify the object to be reindexed. (
.)
Table '%s' may not be modified. ( %s.)
Cannot modify '%s' because it is a view. ( %s,
.)
Variable number must be between ?0 and ?%d< (
?0 ?%d<.)
Misuse of aliased aggregate '%s' (
%s.)
Ambiguous column name: '[%s.[%s.]]%s' ( :
[%s.[%s.]]%s.)
No such function: '%s' ( : %s.)
Wrong number of arguments to function '%s' ( ,
%s.)
Subqueries prohibited in CHECK constraints. ( CHECK
.)
Parameters prohibited in CHECK constraints. ( CHECK
.)
( %d)
RAISE() -
Table '%s' has %d columns but %d values were supplied ( %s
(%d) (%d).)
Database schema is locked: '%s' ( : %s.)
Statement too long. ( .)

23.11.2012.

1225

ACTIONSCRIPT 3.0
SQL,

2103
2104
2105
2106
2108

2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2300
2301
2302

2303
2304
2305
2306
2307
2309
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2501
2508
2510
2511

/

Too many attached databases - max %d (
. %d.)
Cannot ATTACH database within transaction. (
ATTACH .)
Database '%s' is already in use. ( %s .)
Attached databases must use the same text encoding as main database.
( ,
.)
.
Unable to open database. ( .)
Cannot DETACH database within transaction. (
DETACH .)
Cannot detach database: '%s' ( : %s)
Database '%s' is locked. ( %s .)
.
[|] "%s"[,"%s"] [|] .
Malformed database schema. ( .)
Unsupported file format. ( .)
Unrecognized token: '%s' ( : %s.)
Could not convert text value to numeric value. (
.)
Could not convert string value to date. (
.)
Could not convert floating point value to integer without loss of data. (

.)
Cannot rollback transaction - SQL statements in progress. (
, SQL.)
Cannot commit transaction - SQL statements in progress. (
, SQL.)
Database table is locked: '%s' ( : %s.)
Read-only table. ( .)
String or blob too big. (
.)
Cannot open indexed column for writing. (
.)
Cannot open value of type %s. ( %s.)
No such rowid: %s< ( : %s<.)
Object name reserved for internal use: '%s' (
: %s.)
View '%s' may not be altered. ( %s.)
Default value of column '%s' is not constant. ( %s
.)
Not authorized to use function '%s' (
%s.)
Misuse of aggregate function '%s' (
%s.)
Misuse of aggregate: '%s' ( : %s.)
No such database: '%s' ( : %s.)
Table '%s' has no column named '%s' ( %s %s.)
No such module: '%s' ( : %s.)
No such savepoint: '%s' ( : %s.)
Cannot rollback - no transaction is active. ,
.)
Cannot commit - no transaction is active. (
, .)

23.11.2012.

1226

1227

68. AGAL (Adobe Graphics


Assembly Language)
AGAL (Adobe Graphics Assembly Language)
. AGAL
-, .

- AGAL
- AGAL Endian.LITTLE_ENDIAN.
-
- AGAL 7- :
A0 01000000 A1 00 -- for a vertex program
A0 01000000 A1 01 -- for a fragment program
(
)

(
)

magic

0xa0

version

shader type ID

0xa1

shader type

0 ; 1

. 192 (24 ),
:
[opcode][destination][source1][source2 or sampler]

. 0.

[opcode] 32 .

mov

0x00

move

source1 destination.

add

0x01

add

destination = source1 + source2,

sub

0x02

subtract

destination = source1 - source2,

mul

0x03

multiply

destination = source1 * source2,

23.11.2012.

ACTIONSCRIPT 3.0
AGAL (Adobe Graphics Assembly Language)

div

0x04

divide

destination = source1 / source2,

rcp

0x05

reciprocal

destination = 1/source1,

min

0x06

minimum

destination = minimum(source1,source2),

max

0x07

maximum

destination = maximum(source1,source2),

frc

0x08

fractional

destination = source1 - (float)floor(source1),

sqt

0x09

square root

destination = sqrt(source1),

rsq

0x0a

reciprocal root

destination = 1/sqrt(source1),

pow

0x0b

power

destination = pow(source1,source2),

log

0x0c

logarithm

destination = log_2(source1),

exp

0x0d

exponential

destination = 2^source1,

nrm

0x0e

normalize

destination = normalize(source1), (
,
.xyz )

sin

0x0f

sine

destination = sin(source1),

cos

0x10

cosine

destination = cos(source1),

crs

0x11

cross product

destination.x = source1.y * source2.z - source1.z * source2.y


destination.y = source1.z * source2.x - source1.x * source2.z
destination.z = source1.x * source2.y - source1.y * source2.x
( ,
.xyz )

dp3

0x12

dot product

destination = source1.x*source2.x + source1.y*source2.y +


source1.z*source2.z

dp4

0x13

dot product

destination = source1.x*source2.x + source1.y*source2.y +


source1.z*source2.z + source1.w*source2.w

abs

0x14

absolute

destination = abs(source1),

neg

0x15

negate

destination = -source1,

sat

0x16

saturate

destination = maximum(minimum(source1,1),0),

m33

0x17

multiply matrix 3x3 destination.x = (source1.x * source2[0].x) + (source1.y * source2[0].y)


+ (source1.z * source2[0].z)
destination.y = (source1.x * source2[1].x) + (source1.y * source2[1].y)
+ (source1.z * source2[1].z)
destination.z = (source1.x * source2[2].x) + (source1.y * source2[2].y)
+ (source1.z * source2[2].z)
( ,
.xyz )

23.11.2012.

1228

ACTIONSCRIPT 3.0
AGAL (Adobe Graphics Assembly Language)

m44

0x18

multiply matrix 4x4 destination.x = (source1.x * source2[0].x) + (source1.y * source2[0].y)


+ (source1.z * source2[0].z) + (source1.w * source2[0].w)

destination.y = (source1.x * source2[1].x) + (source1.y * source2[1].y)


+ (source1.z * source2[1].z) + (source1.w * source2[1].w)
destination.z = (source1.x * source2[2].x) + (source1.y * source2[2].y)
+ (source1.z * source2[2].z) + (source1.w * source2[2].w)
destination.w = (source1.x * source2[3].x) + (source1.y * source2[3].y)
+ (source1.z * source2[3].z) + (source1.w * source2[3].w)
m34

0x19

multiply matrix 3x4 destination.x = (source1.x * source2[0].x) + (source1.y * source2[0].y)


+ (source1.z * source2[0].z) + (source1.w * source2[0].w)
destination.y = (source1.x * source2[1].x) + (source1.y * source2[1].y)
+ (source1.z * source2[1].z) + (source1.w * source2[1].w)
destination.z = (source1.x * source2[2].x) + (source1.y * source2[2].y)
+ (source1.z * source2[2].z) + (source1.w * source2[2].w)
( ,
.xyz )

kil

0x27

kill/discard (
,
)
. ( )

tex

0x28

texture sample
(

sge

0x29

set-if-greater-equal destination = source1 >= source2 ? 1 : 0,

slt

0x2a

set-if-less-than

destination = source1 < source2 ? 1 : 0,

seq

0x2c

set-if-equal

destination = source1 == source2 ? 1 : 0,

sne

0x2d

set-if-not-equal

destination = source1 != source2 ? 1 : 0,

destination source2
source1. source2
.


[destination] 32 :
31.............................0
----TTTT----MMMMNNNNNNNNNNNNNNNN

T = (4 )
M = (4 )
N = (16 )
- = , 0

[source] 64 :
63.............................................................0
D-------------QQ----IIII----TTTTSSSSSSSSOOOOOOOONNNNNNNNNNNNNNNN

D = =0/=1, Q I , 1

23.11.2012.

1229

1230

ACTIONSCRIPT 3.0
AGAL (Adobe Graphics Assembly Language)

Q = (2 )
I = (4 )
T = (4 )
S = (8 , 2 )
O = (8 )
N = (16 )
- = , 0

[sampler],
64 .
63.............................................................0
FFFFMMMMWWWWSSSSDDDD--------TTTT--------BBBBBBBBNNNNNNNNNNNNNNNN

N = (16 )
B = , , 8.
: b/8,0 (8 )
T = , 5, (4 )
F = (0=,1=) (4 )
M = (0=.,1=, 2=)
W = (0=,1=)
S = ( 0)
D = (0=2D, 1=)

. ,
:

;
,
Context3D.setVertexBufferAt().

28

128

;

Context3D.setProgramConstants().

,
.

23.11.2012.

1231

ACTIONSCRIPT 3.0
AGAL (Adobe Graphics Assembly Language)

:

,
.



.

.

.

;
,
Context3D.setTextureAt().

23.11.2012.

Вам также может понравиться