diff options
author | Rogan Creswick <creswick@gmail.com> | 2013-01-02 15:31:43 -0800 |
---|---|---|
committer | Rogan Creswick <creswick@gmail.com> | 2013-01-02 15:31:43 -0800 |
commit | 91c8d16838b39c7726f6c0a0fb333f5ba38d2494 (patch) | |
tree | 136df17525e5e62f3ddc5b7a6dc71ffd31e2aa42 /tools | |
parent | f7b228c479bac8828e521a2826d7f57f150da877 (diff) |
updated addon-sdk to 1.12
Diffstat (limited to 'tools')
-rw-r--r-- | tools/addon-sdk-1.12/LICENSE (renamed from tools/addon-sdk-1.7/LICENSE) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/README (renamed from tools/addon-sdk-1.7/README) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/app-extension/application.ini (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/application.ini) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/app-extension/bootstrap.js | 262 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/app-extension/install.rdf (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/install.rdf) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/activate (renamed from tools/addon-sdk-1.7/bin/activate) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/activate.bat (renamed from tools/addon-sdk-1.7/bin/activate.bat) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/activate.ps1 (renamed from tools/addon-sdk-1.7/bin/activate.ps1) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/bin/cfx (renamed from tools/addon-sdk-1.7/bin/cfx) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/cfx.bat (renamed from tools/addon-sdk-1.7/bin/cfx.bat) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/deactivate.bat (renamed from tools/addon-sdk-1.7/bin/deactivate.bat) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/bin/integration-scripts/buildbot-run-cfx-helper (renamed from tools/addon-sdk-1.7/bin/integration-scripts/buildbot-run-cfx-helper) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/bin/integration-scripts/integration-check (renamed from tools/addon-sdk-1.7/bin/integration-scripts/integration-check) | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/index.html (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/index.html) | 1 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/moz_favicon.ico (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/moz_favicon.ico) | bin | 1406 -> 1406 bytes | |||
-rw-r--r-- | tools/addon-sdk-1.12/data/pagemod-css-include-file.css (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/pagemod-css-include-file.css) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-content-symbiont.js (renamed from tools/addon-sdk-1.7/packages/api-utils/data/test-content-symbiont.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-context-menu.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/test-context-menu.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-iframe-postmessage.html | 20 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-iframe.html | 9 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-iframe.js | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-message-manager.js (renamed from tools/addon-sdk-1.7/packages/api-utils/data/test-message-manager.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-net-url.txt | 1 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-page-mod.html (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/test-page-mod.html) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-page-worker.html (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.html) | 1 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-page-worker.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test-trusted-document.html (renamed from tools/addon-sdk-1.7/packages/api-utils/data/test-trusted-document.html) | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/data/test.html (renamed from tools/addon-sdk-1.7/packages/addon-kit/data/test.html) | 1 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/README.md (renamed from tools/addon-sdk-1.7/examples/annotator/README.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.html (renamed from tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.html (renamed from tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/jquery-1.4.2.min.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/jquery-1.4.2.min.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.css (renamed from tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.css) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.html (renamed from tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/matcher.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/matcher.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/selector.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/selector.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-off.png (renamed from tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-off.png) | bin | 1740 -> 1740 bytes | |||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-on.png (renamed from tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-on.png) | bin | 2054 -> 2054 bytes | |||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/data/widget/widget.js (renamed from tools/addon-sdk-1.7/examples/annotator/data/widget/widget.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/lib/main.js (renamed from tools/addon-sdk-1.7/examples/annotator/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/package.json (renamed from tools/addon-sdk-1.7/examples/annotator/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/annotator/tests/test-main.js (renamed from tools/addon-sdk-1.7/examples/annotator/tests/test-main.js) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/README.md (renamed from tools/addon-sdk-1.7/examples/library-detector/README.md) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/closure.ico (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/closure.ico) | bin | 1150 -> 1150 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery.ico (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery.ico) | bin | 3638 -> 3638 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery_ui.ico (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery_ui.ico) | bin | 1150 -> 1150 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/modernizr.ico (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/modernizr.ico) | bin | 1150 -> 1150 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/mootools.png (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/mootools.png) | bin | 386 -> 386 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/icons/yui.ico (renamed from tools/addon-sdk-1.7/examples/library-detector/data/icons/yui.ico) | bin | 6598 -> 6598 bytes | |||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/library-detector.js (renamed from tools/addon-sdk-1.7/examples/library-detector/data/library-detector.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/library-detector/data/panel.html | 16 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/data/widget.html | 50 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/lib/main.js | 67 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/examples/library-detector/package.json (renamed from tools/addon-sdk-1.7/examples/library-detector/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/library-detector/test/test-main.js (renamed from tools/addon-sdk-1.7/examples/library-detector/test/test-main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reading-data/data/mom.png (renamed from tools/addon-sdk-1.7/examples/reading-data/data/mom.png) | bin | 4778 -> 4778 bytes | |||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reading-data/data/sample.html (renamed from tools/addon-sdk-1.7/examples/reading-data/data/sample.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reading-data/lib/main.js (renamed from tools/addon-sdk-1.7/examples/reading-data/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reading-data/package.json (renamed from tools/addon-sdk-1.7/examples/reading-data/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reading-data/tests/test-main.js (renamed from tools/addon-sdk-1.7/examples/reading-data/tests/test-main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/README.md (renamed from tools/addon-sdk-1.7/examples/reddit-panel/README.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/data/jquery-1.4.4.min.js (renamed from tools/addon-sdk-1.7/examples/reddit-panel/data/jquery-1.4.4.min.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/data/panel.js (renamed from tools/addon-sdk-1.7/examples/reddit-panel/data/panel.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/lib/main.js (renamed from tools/addon-sdk-1.7/examples/reddit-panel/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/package.json (renamed from tools/addon-sdk-1.7/examples/reddit-panel/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/examples/reddit-panel/tests/test-main.js (renamed from tools/addon-sdk-1.7/examples/reddit-panel/tests/test-main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/addon-page.js | 38 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/addon/installer.js | 106 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/addon/runner.js | 153 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/base64.js | 41 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/clipboard.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/clipboard.js) | 143 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/console/plain-text.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/plain-text-console.js) | 22 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/console/traceback.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/traceback.js) | 39 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/content-proxy.js (renamed from tools/addon-sdk-1.7/packages/api-utils/data/content-proxy.js) | 71 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/content-worker.js (renamed from tools/addon-sdk-1.7/packages/api-utils/data/worker.js) | 167 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/content.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/content.js) | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/loader.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/content/loader.js) | 31 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/symbiont.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/content/symbiont.js) | 22 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/thumbnail.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/utils/thumbnail.js) | 19 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/content/worker.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/content/worker.js) | 221 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/context-menu.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/context-menu.js) | 56 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/core/heritage.js | 146 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/core/namespace.js | 43 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/core/promise.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/promise.js) | 37 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/api-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/api-utils.js) | 9 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/app-strings.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/app-strings.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/cortex.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/cortex.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/errors.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/errors.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/events.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/events.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/events/assembler.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/events/assembler.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/light-traits.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/light-traits.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/list.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/list.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/memory.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/memory.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/observer-service.js | 134 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/tab-browser.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/tab-browser.js) | 58 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/traits.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/traits.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/traits/core.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/traits/core.js) | 5 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test-finder.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/unit-test-finder.js) | 21 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/unit-test.js) | 19 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/deprecated/window-utils.js | 201 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/dom/events.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/dom/events.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/dom/events/keys.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/dom/events/keys.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/event/core.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/event/core.js) | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/event/target.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/event/target.js) | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/frame/hidden-frame.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/hidden-frame.js) | 35 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/frame/utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/frame/utils.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/hotkeys.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/hotkeys.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/io/byte-streams.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/byte-streams.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/io/data.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/utils/data.js) | 33 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/io/file.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/file.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/io/text-streams.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/text-streams.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/keyboard/hotkeys.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/hotkeys.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/keyboard/observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/observer.js) | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/keyboard/utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/utils.js) | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/l10n.js) | 84 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/core.js | 35 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/html.js | 93 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/loader.js | 71 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/locale.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/l10n/locale.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/plural-rules.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/l10n/plural-rules.js) | 336 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/l10n/prefs.js | 44 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/lang/functional.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/functional.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/lang/type.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/type.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/loader/cuddlefish.js | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/loader/sandbox.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/sandbox.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/net/url.js | 108 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/net/xhr.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/xhr.js) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/notifications.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/notifications.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/page-mod.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/page-mod.js) | 199 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/page-mod/match-pattern.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/match-pattern.js) | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/page-worker.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/page-worker.js) | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/panel.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/panel.js) | 126 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/passwords.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/passwords.js) | 9 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/passwords/utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/passwords/utils.js) | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/platform/xpcom.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/xpcom.js) | 120 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/preferences/event-target.js | 60 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/preferences/service.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/preferences-service.js) | 74 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/private-browsing.js | 36 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/private-browsing/utils.js | 74 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/querystring.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/querystring.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/request.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/request.js) | 31 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/selection.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/selection.js) | 130 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/self.js | 36 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/simple-prefs.js | 32 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/simple-storage.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/simple-storage.js) | 20 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/system.js) | 49 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/environment.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/environment.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/events.js | 113 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/globals.js | 54 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/runtime.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/runtime.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/unload.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/unload.js) | 57 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/system/xul-app.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/xul-app.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-timers.js) | 14 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/common.js | 23 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/events.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/tabs/events.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/helpers.js | 17 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/namespace.js | 9 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/tabs/observer.js) | 38 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/tab-fennec.js | 141 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/tab-firefox.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/tabs/tab.js) | 129 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/tab.js | 21 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/tabs-firefox.js | 26 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/tabs.js | 21 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/utils.js | 222 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/tabs/worker.js | 17 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/test.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/assert.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/test/assert.js) | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/harness.js (renamed from tools/addon-sdk-1.7/packages/test-harness/lib/harness.js) | 83 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/httpd.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/httpd.js) | 20 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/loader.js | 28 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/runner.js | 150 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/test/tmp-file.js | 73 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/timers.js | 53 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/url.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/url.js) | 125 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/array.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/array.js) | 22 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/collection.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/collection.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/deprecate.js | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/list.js | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/object.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/utils/object.js) | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/registry.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/utils/registry.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/util/uuid.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/uuid.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/widget.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/widget.js) | 73 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/window/browser.js | 41 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/window/namespace.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/timers.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/window/utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/window/utils.js) | 101 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows.js | 21 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/dom.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/windows/dom.js) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/fennec.js | 84 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/firefox.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/lib/windows.js) | 129 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/loader.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/windows/loader.js) | 32 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/windows/observer.js) | 17 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/tabs-fennec.js | 190 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/sdk/windows/tabs-firefox.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/windows/tabs.js) | 18 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/lib/toolkit/loader.js | 400 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/mapping.json | 81 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/package.json | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/__init__.py) | 135 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/_version.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/_version.py) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/bunch.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/bunch.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/docs/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apiparser.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apiparser.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apirenderer.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apirenderer.py) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/documentationitem.py | 124 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/generate.py | 199 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/linkrewriter.py | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/renderapi.readme.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/docs/renderapi.readme.md) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/python-lib/cuddlefish/docs/webdocs.py | 106 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/manifest.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/manifest.py) | 76 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/bootstrap.js | 55 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/install.rdf (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/install.rdf) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/options_defaults.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/options_defaults.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/options_xul.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/options_xul.py) | 36 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/packaging.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/packaging.py) | 17 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/python-lib/cuddlefish/preflight.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/preflight.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/prefs.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/prefs.py) | 3 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/property_parser.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/property_parser.py) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/rdf.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/rdf.py) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/runner.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/runner.py) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/templates.py | 31 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/main.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/two.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/two.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/data/text.data (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/data/text.data) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/unreachable.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/unreachable.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/msg.txt (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/msg.txt) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/subdir/submsg.txt (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/subdir/submsg.txt) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json | 50 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/high-level-modules.md | 18 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/low-level-modules.md | 36 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/aardvark-feeder.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/aardvark-feeder.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/anteater/anteater.md (renamed from tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md) | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/main.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/not_a_doc.js | 5 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/third-party-modules.md | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIreference.html (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIreference.html) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIsample.md (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIsample.md) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apiparser.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apiparser.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apirenderer.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apirenderer.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_generate.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_generate.py) | 30 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_init.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_init.py) | 55 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_licenses.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_licenses.py) | 0 | ||||
-rwxr-xr-x | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_linker.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_linker.py) | 32 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_manifest.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_manifest.py) | 31 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_packaging.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_packaging.py) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_preflight.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_preflight.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_property_parser.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_property_parser.py) | 28 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_rdf.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_rdf.py) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_runner.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_runner.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_util.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_util.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_version.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_version.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_webdocs.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_webdocs.py) | 29 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_xpi.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_xpi.py) | 109 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/util.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/util.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/version_comparator.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/version_comparator.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/cuddlefish/xpi.py (renamed from tools/addon-sdk-1.7/python-lib/cuddlefish/xpi.py) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/jetpack_sdk_env.py (renamed from tools/addon-sdk-1.7/python-lib/jetpack_sdk_env.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/AUTHORS (renamed from tools/addon-sdk-1.7/python-lib/markdown/AUTHORS) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/LICENSE (renamed from tools/addon-sdk-1.7/python-lib/markdown/LICENSE) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/blockparser.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/blockparser.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/blockprocessors.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/blockprocessors.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/commandline.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/commandline.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/etree_loader.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/etree_loader.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/__init__.py | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/abbr.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/abbr.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/codehilite.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/codehilite.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/def_list.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/def_list.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/extra.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/extra.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/fenced_code.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/fenced_code.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/footnotes.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/footnotes.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/headerid.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/headerid.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/html_tidy.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/html_tidy.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/imagelinks.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/imagelinks.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/meta.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/meta.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/rss.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/rss.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/tables.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/tables.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/toc.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/toc.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/extensions/wikilinks.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/extensions/wikilinks.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/html4.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/html4.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/inlinepatterns.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/inlinepatterns.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/odict.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/odict.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/postprocessors.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/postprocessors.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/preprocessors.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/preprocessors.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/markdown/treeprocessors.py (renamed from tools/addon-sdk-1.7/python-lib/markdown/treeprocessors.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/mozrunner/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/mozrunner/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/mozrunner/killableprocess.py (renamed from tools/addon-sdk-1.7/python-lib/mozrunner/killableprocess.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/mozrunner/qijo.py (renamed from tools/addon-sdk-1.7/python-lib/mozrunner/qijo.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/mozrunner/winprocess.py (renamed from tools/addon-sdk-1.7/python-lib/mozrunner/winprocess.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/mozrunner/wpk.py (renamed from tools/addon-sdk-1.7/python-lib/mozrunner/wpk.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/plural-rules-generator.py (renamed from tools/addon-sdk-1.7/python-lib/plural-rules-generator.py) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/LICENSE.txt (renamed from tools/addon-sdk-1.7/python-lib/simplejson/LICENSE.txt) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/__init__.py (renamed from tools/addon-sdk-1.7/python-lib/simplejson/__init__.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/decoder.py (renamed from tools/addon-sdk-1.7/python-lib/simplejson/decoder.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/encoder.py (renamed from tools/addon-sdk-1.7/python-lib/simplejson/encoder.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/scanner.py (renamed from tools/addon-sdk-1.7/python-lib/simplejson/scanner.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/python-lib/simplejson/tool.py (renamed from tools/addon-sdk-1.7/python-lib/simplejson/tool.py) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/data/test-localization.html | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/locale/en-GB.properties (renamed from tools/addon-sdk-1.7/packages/addon-kit/locale/en-GB.properties) | 5 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/locale/eo.properties (renamed from tools/addon-sdk-1.7/packages/addon-kit/locale/eo.properties) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/locale/fr-FR.properties (renamed from tools/addon-sdk-1.7/packages/addon-kit/locale/fr-FR.properties) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/main.js | 181 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/addons/l10n/package.json | 3 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/commonjs-test-adapter/asserts.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/commonjs-test-adapter/asserts.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/addon-install-unit-test@mozilla.com.xpi | bin | 0 -> 1596 bytes | |||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/addEventListener.js | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/jsctypes.js | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/onerror.js | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/onmessage.js | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/setTimeout.js | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/chrome-worker/xhr.js | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/es5.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/es5.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/loader/cycles/a.js (renamed from tools/addon-sdk-1.7/packages/api-utils/lib/find-tests.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/loader/cycles/b.js | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/loader/cycles/c.js | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/loader/cycles/main.js | 14 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/sandbox-complex-character.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-complex-character.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/fixtures/sandbox-normal.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-normal.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/loader/fixture.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/loader/fixture.js) | 3 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/add.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/add.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/async1.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/async1.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/async2.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/async2.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/badExportAndReturn.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/badExportAndReturn.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/badFirst.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/badFirst.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/badSecond.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/badSecond.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/blue.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/blue.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/castor.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/castor.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/cheetah.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/cheetah.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/color.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/color.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/dupe.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupe.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/dupeNested.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeNested.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/dupeSetExports.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeSetExports.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/exportsEquals.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/exportsEquals.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/green.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/green.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/lion.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/lion.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/orange.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/orange.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/pollux.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/pollux.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/red.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/red.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/setExports.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/setExports.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/subtract.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/subtract.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/tiger.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/tiger.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/traditional1.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional1.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/traditional2.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional2.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/modules/types/cat.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/modules/types/cat.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/pagemod-test-helpers.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/pagemod-test-helpers.js) | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/private-browsing-helper.js | 32 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/tabs/test-fennec-tabs.js | 621 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/tabs/test-firefox-tabs.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-tabs.js) | 362 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-addon-installer.js | 131 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-addon-page.js | 65 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-api-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-api-utils.js) | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-app-strings.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-app-strings.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-array.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-array.js) | 30 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-base64.js | 75 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-byte-streams.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-byte-streams.js) | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-chrome.js | 86 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-clipboard.js | 214 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-collection.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-collection.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-commonjs-test-adapter.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-commonjs-test-adapter.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-content-loader.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-content-loader.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-content-proxy.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-content-proxy.js) | 278 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-content-symbiont.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-content-symbiont.js) | 94 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-content-worker.js | 657 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-context-menu.html (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.html) | 3 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-context-menu.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.js) | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-cortex.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-cortex.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-cuddlefish.js | 49 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-deprecate.js | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-deprecated-list.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-list.js) | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-dom.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-dom.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-environment.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-environment.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-errors.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-errors.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-event-core.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-event-core.js) | 19 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-event-target.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-event-target.js) | 32 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-events.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-events.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-file.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-file.js) | 10 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-frame-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-frame-utils.js) | 42 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-functional.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-functional.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-globals.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-globals.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-heritage.js | 375 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-hidden-frame.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-hidden-frame.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-hotkeys.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-hotkeys.js) | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-httpd.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-httpd.js) | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-keyboard-observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-observer.js) | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-keyboard-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-utils.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-l10n-locale.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-locale.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-l10n-plural-rules.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-plural-rules.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-layout-change.js | 178 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-light-traits.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-light-traits.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-list.js | 43 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-loader.js | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-match-pattern.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-match-pattern.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-memory.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-memory.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-module.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-module.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-modules.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-modules.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-namespace.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-namespace.js) | 53 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-net-url.js | 212 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-notifications.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-notifications.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-observer-service.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-observer-service.js) | 19 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-packaging.js | 15 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-page-mod.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-mod.js) | 446 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-page-worker.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-worker.js) | 66 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-panel.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-panel.js) | 70 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-passwords-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-passwords-utils.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-passwords.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-passwords.js) | 5 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-plain-text-console.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-plain-text-console.js) | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-preferences-service.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-preferences-service.js) | 37 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-preferences-target.js | 42 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-private-browsing.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-private-browsing.js) | 20 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-promise.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-promise.js) | 18 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-querystring.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-querystring.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-registry.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-registry.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-request.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-request.js) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-require.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-require.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-sandbox.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-sandbox.js) | 16 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-selection.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-selection.js) | 71 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-self.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-self.js) | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-set-exports.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-set-exports.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-simple-prefs.js | 231 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-simple-storage.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-storage.js) | 56 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tab-browser.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-browser.js) | 138 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tab-observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-observer.js) | 14 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tab.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-tab.js) | 57 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tabs-common.js | 296 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tabs.js | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-text-streams.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-text-streams.js) | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-timer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-timer.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tmp-file.js | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-tmp-file.txt | 1 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-traceback.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-traceback.js) | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-traits-core.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-traits-core.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-traits.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-traits.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-type.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-type.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-unit-test.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-unit-test.js) | 9 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-unload.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-unload.js) | 30 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-url.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-url.js) | 71 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-uuid.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-uuid.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-widget.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-widget.js) | 308 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-window-loader.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-window-loader.js) | 4 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-window-observer.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-window-observer.js) | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-window-utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils.js) | 49 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-window-utils2.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils2.js) | 19 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-windows-common.js | 59 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-windows-private-browsing.js | 35 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-windows.js | 11 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-xhr.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-xhr.js) | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-xpcom.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-xpcom.js) | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/test-xul-app.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/test-xul-app.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/traits/assert.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/traits/assert.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/traits/descriptor-tests.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/traits/descriptor-tests.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/traits/inheritance-tests.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/traits/inheritance-tests.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/traits/object-tests.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/traits/object-tests.js) | 2 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/traits/utils.js (renamed from tools/addon-sdk-1.7/packages/api-utils/tests/traits/utils.js) | 0 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/windows/test-fennec-windows.js | 46 | ||||
-rw-r--r-- | tools/addon-sdk-1.12/test/windows/test-firefox-windows.js (renamed from tools/addon-sdk-1.7/packages/addon-kit/tests/test-windows.js) | 180 | ||||
-rwxr-xr-x | tools/addon-sdk-1.7/examples/library-detector/data/widget.js | 14 | ||||
-rwxr-xr-x | tools/addon-sdk-1.7/examples/library-detector/lib/main.js | 107 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/README.md | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/clipboard.md | 62 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/context-menu.md | 719 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/hotkeys.md | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/notifications.md | 64 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/page-mod.md | 412 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/page-worker.md | 325 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/panel.md | 607 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/passwords.md | 568 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/private-browsing.md | 50 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/request.md | 203 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/selection.md | 90 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/self.md | 79 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/simple-prefs.md | 75 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/simple-storage.md | 220 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/tabs.md | 385 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/timers.md | 52 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/widget.md | 909 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/docs/windows.md | 191 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/lib/addon-page.js | 33 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/lib/private-browsing.js | 61 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/lib/simple-prefs.js | 68 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/lib/tabs.js | 28 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/package.json | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/tests/helpers.js | 23 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/tests/test-addon-page.js | 51 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/tests/test-clipboard.js | 64 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/tests/test-l10n.js | 97 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-prefs.js | 175 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/README.md | 35 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md | 157 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md | 65 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/base.md | 207 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md | 68 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/collection.md | 77 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/content.md | 15 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md | 92 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md | 241 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md | 140 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md | 130 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md | 160 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/environment.md | 43 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/errors.md | 42 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md | 51 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md | 95 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/events.md | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/file.md | 151 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md | 53 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/globals.md | 100 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md | 83 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md | 31 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md | 295 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/list.md | 98 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md | 246 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/memory.md | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md | 71 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md | 73 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md | 7 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md | 116 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/promise.md | 394 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md | 37 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md | 75 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md | 51 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md | 140 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md | 102 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md | 66 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/traits.md | 244 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md | 393 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/unload.md | 61 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/url.md | 85 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md | 27 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md | 88 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md | 90 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md | 95 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md | 216 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md | 76 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/base.js | 177 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/channel.js | 46 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/cuddlefish.js | 302 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/env!.js | 20 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/globals!.js | 93 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/message-manager.js | 203 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/namespace.js | 43 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/observer-service.js | 175 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/process.js | 76 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/self!.js | 48 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/tabs/utils.js | 59 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/timer.js | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/lib/window-utils.js | 278 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/package.json | 14 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/helpers.js | 24 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/test-base.js | 240 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/test-content-worker.js | 465 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/test-loader.js | 35 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/test-message-manager.js | 600 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/api-utils/tests/test-process.js | 36 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/README.md | 12 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/docs/harness.md | 6 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/docs/run-tests.md | 13 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/lib/run-tests.js | 101 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/package.json | 8 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/packages/test-harness/tests/test-packaging.js | 18 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/bootstrap.js | 216 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/docs/generate.py | 292 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/docs/webdocs.py | 193 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/bootstrap.js | 78 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/templates.py | 83 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json | 18 | ||||
-rw-r--r-- | tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/docs/main.md | 5 |
682 files changed, 13255 insertions, 17573 deletions
diff --git a/tools/addon-sdk-1.7/LICENSE b/tools/addon-sdk-1.12/LICENSE index ad8d321..ad8d321 100644 --- a/tools/addon-sdk-1.7/LICENSE +++ b/tools/addon-sdk-1.12/LICENSE diff --git a/tools/addon-sdk-1.7/README b/tools/addon-sdk-1.12/README index edebf5f..92c7336 100644 --- a/tools/addon-sdk-1.7/README +++ b/tools/addon-sdk-1.12/README @@ -29,8 +29,12 @@ Then run: This should start a documentation server and open a web browser
with further instructions.
+If you get an error when running cfx or have any other problems getting
+started, see the "Troubleshooting" guide at:
+https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/troubleshooting.html
Bugs
-------
-* file a bug: https://bugzilla.mozilla.org/enter_bug.cgi?product=Add-on%20SDK
\ No newline at end of file +* file a bug: https://bugzilla.mozilla.org/enter_bug.cgi?product=Add-on%20SDK
+
diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/application.ini b/tools/addon-sdk-1.12/app-extension/application.ini index 6cec69a..6cec69a 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/application.ini +++ b/tools/addon-sdk-1.12/app-extension/application.ini diff --git a/tools/addon-sdk-1.12/app-extension/bootstrap.js b/tools/addon-sdk-1.12/app-extension/bootstrap.js new file mode 100644 index 0000000..7850a62 --- /dev/null +++ b/tools/addon-sdk-1.12/app-extension/bootstrap.js @@ -0,0 +1,262 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// @see http://mxr.mozilla.org/mozilla-central/source/js/src/xpconnect/loader/mozJSComponentLoader.cpp + +'use strict'; + +// IMPORTANT: Avoid adding any initialization tasks here, if you need to do +// something before add-on is loaded consider addon/runner module instead! + +const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, + results: Cr, manager: Cm } = Components; +const ioService = Cc['@mozilla.org/network/io-service;1']. + getService(Ci.nsIIOService); +const resourceHandler = ioService.getProtocolHandler('resource'). + QueryInterface(Ci.nsIResProtocolHandler); +const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); +const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. + getService(Ci.mozIJSSubScriptLoader); + +const REASON = [ 'unknown', 'startup', 'shutdown', 'enable', 'disable', + 'install', 'uninstall', 'upgrade', 'downgrade' ]; + +let loader = null; +let unload = null; +let cuddlefishSandbox = null; +let nukeTimer = null; + +// Utility function that synchronously reads local resource from the given +// `uri` and returns content string. +function readURI(uri) { + let ioservice = Cc['@mozilla.org/network/io-service;1']. + getService(Ci.nsIIOService); + let channel = ioservice.newChannel(uri, 'UTF-8', null); + let stream = channel.open(); + + let cstream = Cc['@mozilla.org/intl/converter-input-stream;1']. + createInstance(Ci.nsIConverterInputStream); + cstream.init(stream, 'UTF-8', 0, 0); + + let str = {}; + let data = ''; + let read = 0; + do { + read = cstream.readString(0xffffffff, str); + data += str.value; + } while (read != 0); + + cstream.close(); + + return data; +} + +// Utility function that converts cfx-py generated paths to a +// module ids. +function path2id(path) { + // Strips out `/lib` and `.js` from package/lib/path.js + return path.replace(/([^\/]*)\/lib/, '$1').replace(/.js$/, ''); +} +// Utility function that takes old manifest format and creates a manifest +// in a new format: https://github.com/mozilla/addon-sdk/wiki/JEP-Linker +function manifestV2(manifest) { + return Object.keys(manifest).reduce(function(result, path) { + let entry = manifest[path]; + let id = path2id(path); + let requirements = entry.requirements || {}; + result[id] = { + requirements: Object.keys(requirements).reduce(function(result, path) { + result[path] = path2id(requirements[path].path); + return result; + }, {}) + }; + return result + }, {}); +} + +// We don't do anything on install & uninstall yet, but in a future +// we should allow add-ons to cleanup after uninstall. +function install(data, reason) {} +function uninstall(data, reason) {} + +function startup(data, reasonCode) { + try { + let reason = REASON[reasonCode]; + // URI for the root of the XPI file. + // 'jar:' URI if the addon is packed, 'file:' URI otherwise. + // (Used by l10n module in order to fetch `locale` folder) + let rootURI = data.resourceURI.spec; + + // TODO: Maybe we should perform read harness-options.json asynchronously, + // since we can't do anything until 'sessionstore-windows-restored' anyway. + let options = JSON.parse(readURI(rootURI + './harness-options.json')); + + let id = options.jetpackID; + let name = options.name; + // Register a new resource 'domain' for this addon which is mapping to + // XPI's `resources` folder. + // Generate the domain name by using jetpack ID, which is the extension ID + // by stripping common characters that doesn't work as a domain name: + let uuidRe = + /^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/; + + let domain = id. + toLowerCase(). + replace(/@/g, '-at-'). + replace(/\./g, '-dot-'). + replace(uuidRe, '$1'); + + let prefixURI = 'resource://' + domain + '/'; + let resourcesURI = ioService.newURI(rootURI + '/resources/', null, null); + resourceHandler.setSubstitution(domain, resourcesURI); + + // Create path to URLs mapping supported by loader. + let paths = Object.keys(options.metadata).reduce(function(result, name) { + result[name + '/'] = prefixURI + name + '/lib/' + result[name + '/tests/'] = prefixURI + name + '/tests/' + return result + }, { + // Relative modules resolve to add-on package lib + './': prefixURI + name + '/lib/', + 'toolkit/': 'resource://gre/modules/toolkit/', + '': 'resources:///modules/' + }); + + // Make version 2 of the manifest + let manifest = manifestV2(options.manifest); + + // Import `cuddlefish.js` module using a Sandbox and bootstrap loader. + let cuddlefishURI = prefixURI + options.loader; + cuddlefishSandbox = loadSandbox(cuddlefishURI); + let cuddlefish = cuddlefishSandbox.exports; + + // Normalize `options.mainPath` so that it looks like one that will come + // in a new version of linker. + let main = path2id(options.mainPath); + + unload = cuddlefish.unload; + loader = cuddlefish.Loader({ + paths: paths, + // modules manifest. + manifest: manifest, + + // Add-on ID used by different APIs as a unique identifier. + id: id, + // Add-on name. + name: name, + // Add-on version. + version: options.metadata[name].version, + // Add-on package descriptor. + metadata: options.metadata[name], + // Add-on load reason. + loadReason: reason, + + prefixURI: prefixURI, + // Add-on URI. + rootURI: rootURI, + // options used by system module. + // File to write 'OK' or 'FAIL' (exit code emulation). + resultFile: options.resultFile, + // File to write stdout. + logFile: options.logFile, + // Arguments passed as --static-args + staticArgs: options.staticArgs, + + // Arguments related to test runner. + modules: { + '@test/options': { + allTestModules: options.allTestModules, + iterations: options.iterations, + filter: options.filter, + profileMemory: options.profileMemory, + stopOnError: options.stopOnError, + verbose: options.verbose, + } + } + }); + + let module = cuddlefish.Module('addon-sdk/sdk/loader/cuddlefish', cuddlefishURI); + let require = cuddlefish.Require(loader, module); + + require('sdk/addon/runner').startup(reason, { + loader: loader, + main: main, + prefsURI: rootURI + 'defaults/preferences/prefs.js' + }); + } catch (error) { + dump('Bootstrap error: ' + error.message + '\n' + + (error.stack || error.fileName + ': ' + error.lineNumber) + '\n'); + throw error; + } +}; + +function loadSandbox(uri) { + let proto = { + sandboxPrototype: { + loadSandbox: loadSandbox, + ChromeWorker: ChromeWorker + } + }; + let sandbox = Cu.Sandbox(systemPrincipal, proto); + // Create a fake commonjs environnement just to enable loading loader.js + // correctly + sandbox.exports = {}; + sandbox.module = { uri: uri, exports: sandbox.exports }; + sandbox.require = function () { + throw new Error("Bootstrap sandbox `require` method isn't implemented."); + }; + scriptLoader.loadSubScript(uri, sandbox, 'UTF-8'); + return sandbox; +} + +function unloadSandbox(sandbox) { + if ("nukeSandbox" in Cu) + Cu.nukeSandbox(sandbox); +} + +function setTimeout(callback, delay) { + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + timer.initWithCallback({ notify: callback }, delay, + Ci.nsITimer.TYPE_ONE_SHOT); + return timer; +} + +function shutdown(data, reasonCode) { + let reason = REASON[reasonCode]; + if (loader) { + unload(loader, reason); + unload = null; + // Avoid leaking all modules when something goes wrong with one particular + // module. Do not clean it up immediatly in order to allow executing some + // actions on addon disabling. + // We need to keep a reference to the timer, otherwise it is collected + // and won't ever fire. + nukeTimer = setTimeout(nukeModules, 1000); + } +}; + +function nukeModules() { + nukeTimer = null; + // module objects store `exports` which comes from sandboxes + // We should avoid keeping link to these object to avoid leaking sandboxes + for (let key in loader.modules) { + delete loader.modules[key]; + } + // Direct links to sandboxes should be removed too + for (let key in loader.sandboxes) { + let sandbox = loader.sandboxes[key]; + delete loader.sandboxes[key]; + // Bug 775067: From FF17 we can kill all CCW from a given sandbox + unloadSandbox(sandbox); + } + loader = null; + + // Unload sandbox used to evaluate loader.js + unloadSandbox(cuddlefishSandbox.loaderSandbox); + // Bug 764840: We need to unload cuddlefish otherwise it will stay alive + // and keep a reference to this compartment. + unloadSandbox(cuddlefishSandbox); + cuddlefishSandbox = null; +} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/install.rdf b/tools/addon-sdk-1.12/app-extension/install.rdf index 8bbcacb..b608691 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/install.rdf +++ b/tools/addon-sdk-1.12/app-extension/install.rdf @@ -17,8 +17,8 @@ <em:targetApplication> <Description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> - <em:minVersion>12.0</em:minVersion> - <em:maxVersion>13.*</em:maxVersion> + <em:minVersion>17.0</em:minVersion> + <em:maxVersion>18.*</em:maxVersion> </Description> </em:targetApplication> diff --git a/tools/addon-sdk-1.7/bin/activate b/tools/addon-sdk-1.12/bin/activate index 8f2d9dd..8f2d9dd 100644 --- a/tools/addon-sdk-1.7/bin/activate +++ b/tools/addon-sdk-1.12/bin/activate diff --git a/tools/addon-sdk-1.7/bin/activate.bat b/tools/addon-sdk-1.12/bin/activate.bat index 5a6b885..5a6b885 100644 --- a/tools/addon-sdk-1.7/bin/activate.bat +++ b/tools/addon-sdk-1.12/bin/activate.bat diff --git a/tools/addon-sdk-1.7/bin/activate.ps1 b/tools/addon-sdk-1.12/bin/activate.ps1 index 5d939d4..5d939d4 100644 --- a/tools/addon-sdk-1.7/bin/activate.ps1 +++ b/tools/addon-sdk-1.12/bin/activate.ps1 diff --git a/tools/addon-sdk-1.7/bin/cfx b/tools/addon-sdk-1.12/bin/cfx index 2be9d19..2be9d19 100755 --- a/tools/addon-sdk-1.7/bin/cfx +++ b/tools/addon-sdk-1.12/bin/cfx diff --git a/tools/addon-sdk-1.7/bin/cfx.bat b/tools/addon-sdk-1.12/bin/cfx.bat index 215b034..215b034 100644 --- a/tools/addon-sdk-1.7/bin/cfx.bat +++ b/tools/addon-sdk-1.12/bin/cfx.bat diff --git a/tools/addon-sdk-1.7/bin/deactivate.bat b/tools/addon-sdk-1.12/bin/deactivate.bat index e6bcd92..e6bcd92 100644 --- a/tools/addon-sdk-1.7/bin/deactivate.bat +++ b/tools/addon-sdk-1.12/bin/deactivate.bat diff --git a/tools/addon-sdk-1.7/bin/integration-scripts/buildbot-run-cfx-helper b/tools/addon-sdk-1.12/bin/integration-scripts/buildbot-run-cfx-helper index 56c76ad..56c76ad 100755 --- a/tools/addon-sdk-1.7/bin/integration-scripts/buildbot-run-cfx-helper +++ b/tools/addon-sdk-1.12/bin/integration-scripts/buildbot-run-cfx-helper diff --git a/tools/addon-sdk-1.7/bin/integration-scripts/integration-check b/tools/addon-sdk-1.12/bin/integration-scripts/integration-check index d64472f..8faec50 100644 --- a/tools/addon-sdk-1.7/bin/integration-scripts/integration-check +++ b/tools/addon-sdk-1.12/bin/integration-scripts/integration-check @@ -1,8 +1,8 @@ #!/usr/bin/env python
-# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - +# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
import os
import signal
import threading
@@ -260,7 +260,7 @@ class SDK: # Subprocess call to test the sample example for packaging.
if self.bin!=None:
if self.mswindows:
- p = subprocess.Popen('bin\\activate && cfx run --pkgdir examples\\reading-data --static-args="{\"quitWhenDone\":true}" -b \"" + self.bin + "\"' , stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+ p = subprocess.Popen('bin\\activate && cfx run --pkgdir examples\\reading-data --static-args="{\\"quitWhenDone\\":true}" -b \"" + self.bin + "\"' , stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
proc_handle = p._handle
(stdout, stderr) = p.communicate()
else:
@@ -269,7 +269,7 @@ class SDK: (stdout, stderr) = p.communicate()
elif self.bin==None:
if self.mswindows:
- p = subprocess.Popen('bin\\activate && cfx run --pkgdir examples\\reading-data --static-args="{\"quitWhenDone\":true}"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+ p = subprocess.Popen('bin\\activate && cfx run --pkgdir examples\\reading-data --static-args="{\\"quitWhenDone\\":true}"', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
proc_handle = p._handle
(stdout, stderr) = p.communicate()
else:
diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/index.html b/tools/addon-sdk-1.12/data/index.html index 7095e7d..e5b5859 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/index.html +++ b/tools/addon-sdk-1.12/data/index.html @@ -4,6 +4,7 @@ <html> <head> + <meta charset="UTF-8"> <title>Add-on Page</title> </head> <body> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/moz_favicon.ico b/tools/addon-sdk-1.12/data/moz_favicon.ico Binary files differindex d444389..d444389 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/moz_favicon.ico +++ b/tools/addon-sdk-1.12/data/moz_favicon.ico diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/pagemod-css-include-file.css b/tools/addon-sdk-1.12/data/pagemod-css-include-file.css index 91d8e25..91d8e25 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/pagemod-css-include-file.css +++ b/tools/addon-sdk-1.12/data/pagemod-css-include-file.css diff --git a/tools/addon-sdk-1.7/packages/api-utils/data/test-content-symbiont.js b/tools/addon-sdk-1.12/data/test-content-symbiont.js index 65a2a21..65a2a21 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/data/test-content-symbiont.js +++ b/tools/addon-sdk-1.12/data/test-content-symbiont.js diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/test-context-menu.js b/tools/addon-sdk-1.12/data/test-context-menu.js index 13c4eb2..13c4eb2 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/test-context-menu.js +++ b/tools/addon-sdk-1.12/data/test-context-menu.js diff --git a/tools/addon-sdk-1.12/data/test-iframe-postmessage.html b/tools/addon-sdk-1.12/data/test-iframe-postmessage.html new file mode 100644 index 0000000..cb9a870 --- /dev/null +++ b/tools/addon-sdk-1.12/data/test-iframe-postmessage.html @@ -0,0 +1,20 @@ +<!DOCTYPE HTML> +<html> + <head> + <meta charset="UTF-8"> + <script> + window.addEventListener("message", function(msg) { + parent.postMessage(msg.data, "*"); + }); + + parent.postMessage({ + first: "a string", + second: ["an", "array"], + third: {an: 'object'} + }, '*'); + </script> + </head> + <body> + <h1>Inner iframe</h1> + </body> +</html> diff --git a/tools/addon-sdk-1.12/data/test-iframe.html b/tools/addon-sdk-1.12/data/test-iframe.html new file mode 100644 index 0000000..ca7ac5c --- /dev/null +++ b/tools/addon-sdk-1.12/data/test-iframe.html @@ -0,0 +1,9 @@ +<!DOCTYPE HTML> +<html> +<head> + <meta charset="UTF-8"> +</head> +<body> + <iframe id="inner" src="about:blank"></iframe> +</body> +</html> diff --git a/tools/addon-sdk-1.12/data/test-iframe.js b/tools/addon-sdk-1.12/data/test-iframe.js new file mode 100644 index 0000000..5b0ec1b --- /dev/null +++ b/tools/addon-sdk-1.12/data/test-iframe.js @@ -0,0 +1,11 @@ + +var count = 0 + +setTimeout(function() { + window.addEventListener("message", function(msg) { + if (++count > 1) self.postMessage(msg.data); + else msg.source.postMessage(msg.data, '*'); + }); + + document.getElementById('inner').src = iframePath; +}, 0); diff --git a/tools/addon-sdk-1.7/packages/api-utils/data/test-message-manager.js b/tools/addon-sdk-1.12/data/test-message-manager.js index d647bd8..d647bd8 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/data/test-message-manager.js +++ b/tools/addon-sdk-1.12/data/test-message-manager.js diff --git a/tools/addon-sdk-1.12/data/test-net-url.txt b/tools/addon-sdk-1.12/data/test-net-url.txt new file mode 100644 index 0000000..9f8166e --- /dev/null +++ b/tools/addon-sdk-1.12/data/test-net-url.txt @@ -0,0 +1 @@ +Hello, ゼロ!
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-mod.html b/tools/addon-sdk-1.12/data/test-page-mod.html index da3ec99..901abef 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-mod.html +++ b/tools/addon-sdk-1.12/data/test-page-mod.html @@ -1,9 +1,9 @@ <!-- This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - <html> <head> + <meta charset="UTF-8"> <title>Page Mod test</title> </head> <body> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.html b/tools/addon-sdk-1.12/data/test-page-worker.html index aabe1df..8526403 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.html +++ b/tools/addon-sdk-1.12/data/test-page-worker.html @@ -4,6 +4,7 @@ <html> <head> + <meta charset="UTF-8"> <title>Page Worker test</title> </head> <body> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.js b/tools/addon-sdk-1.12/data/test-page-worker.js index d59ccae..d59ccae 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/test-page-worker.js +++ b/tools/addon-sdk-1.12/data/test-page-worker.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/data/test-trusted-document.html b/tools/addon-sdk-1.12/data/test-trusted-document.html index 5845cf5..e9f9169 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/data/test-trusted-document.html +++ b/tools/addon-sdk-1.12/data/test-trusted-document.html @@ -2,16 +2,17 @@ - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> -<html>
-<head>
- <title>Worker test</title>
-</head>
-<body>
- <p id="paragraph">Lorem ipsum dolor sit amet.</p>
- <script>
- addon.port.on('addon-to-document', function (arg) {
- addon.port.emit('document-to-addon', arg);
- });
- </script>
-</body>
-</html>
+<html> +<head> + <meta charset="UTF-8"> + <title>Worker test</title> +</head> +<body> + <p id="paragraph">Lorem ipsum dolor sit amet.</p> + <script> + addon.port.on('addon-to-document', function (arg) { + addon.port.emit('document-to-addon', arg); + }); + </script> +</body> +</html> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/data/test.html b/tools/addon-sdk-1.12/data/test.html index 0c7cf24..181e85f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/data/test.html +++ b/tools/addon-sdk-1.12/data/test.html @@ -4,6 +4,7 @@ <html> <head> + <meta charset="UTF-8"> <title>foo</title> </head> <body> diff --git a/tools/addon-sdk-1.7/examples/annotator/README.md b/tools/addon-sdk-1.12/examples/annotator/README.md index d376240..d376240 100644 --- a/tools/addon-sdk-1.7/examples/annotator/README.md +++ b/tools/addon-sdk-1.12/examples/annotator/README.md diff --git a/tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.html b/tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.html index f61c5e1..f61c5e1 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.html +++ b/tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.html diff --git a/tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.js b/tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.js index c1f57aa..c1f57aa 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/annotation/annotation.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/annotation/annotation.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.html b/tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.html index 6125999..6125999 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.html +++ b/tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.html diff --git a/tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.js b/tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.js index 2fe5888..2fe5888 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/editor/annotation-editor.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/editor/annotation-editor.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/jquery-1.4.2.min.js b/tools/addon-sdk-1.12/examples/annotator/data/jquery-1.4.2.min.js index 7c24308..7c24308 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/jquery-1.4.2.min.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/jquery-1.4.2.min.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.css b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.css index 9063682..9063682 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.css +++ b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.css diff --git a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.html b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.html index 32a5409..32a5409 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.html +++ b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.html diff --git a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.js b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.js index 5653ba5..5653ba5 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/list/annotation-list.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/list/annotation-list.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/matcher.js b/tools/addon-sdk-1.12/examples/annotator/data/matcher.js index 86d6bc7..86d6bc7 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/matcher.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/matcher.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/selector.js b/tools/addon-sdk-1.12/examples/annotator/data/selector.js index f42dbfa..f42dbfa 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/selector.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/selector.js diff --git a/tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-off.png b/tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-off.png Binary files differindex b14d961..b14d961 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-off.png +++ b/tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-off.png diff --git a/tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-on.png b/tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-on.png Binary files differindex 71a609f..71a609f 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/widget/pencil-on.png +++ b/tools/addon-sdk-1.12/examples/annotator/data/widget/pencil-on.png diff --git a/tools/addon-sdk-1.7/examples/annotator/data/widget/widget.js b/tools/addon-sdk-1.12/examples/annotator/data/widget/widget.js index 1efb914..1efb914 100644 --- a/tools/addon-sdk-1.7/examples/annotator/data/widget/widget.js +++ b/tools/addon-sdk-1.12/examples/annotator/data/widget/widget.js diff --git a/tools/addon-sdk-1.7/examples/annotator/lib/main.js b/tools/addon-sdk-1.12/examples/annotator/lib/main.js index a21320a..a21320a 100644 --- a/tools/addon-sdk-1.7/examples/annotator/lib/main.js +++ b/tools/addon-sdk-1.12/examples/annotator/lib/main.js diff --git a/tools/addon-sdk-1.7/examples/annotator/package.json b/tools/addon-sdk-1.12/examples/annotator/package.json index 3870710..3870710 100644 --- a/tools/addon-sdk-1.7/examples/annotator/package.json +++ b/tools/addon-sdk-1.12/examples/annotator/package.json diff --git a/tools/addon-sdk-1.7/examples/annotator/tests/test-main.js b/tools/addon-sdk-1.12/examples/annotator/tests/test-main.js index 72fedf4..72fedf4 100644 --- a/tools/addon-sdk-1.7/examples/annotator/tests/test-main.js +++ b/tools/addon-sdk-1.12/examples/annotator/tests/test-main.js diff --git a/tools/addon-sdk-1.7/examples/library-detector/README.md b/tools/addon-sdk-1.12/examples/library-detector/README.md index 72285ac..72285ac 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/README.md +++ b/tools/addon-sdk-1.12/examples/library-detector/README.md diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/closure.ico b/tools/addon-sdk-1.12/examples/library-detector/data/icons/closure.ico Binary files differindex a8c91a0..a8c91a0 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/closure.ico +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/closure.ico diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery.ico b/tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery.ico Binary files differindex 8df8f38..8df8f38 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery.ico +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery.ico diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery_ui.ico b/tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery_ui.ico Binary files differindex 77e3bd2..77e3bd2 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/jquery_ui.ico +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/jquery_ui.ico diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/modernizr.ico b/tools/addon-sdk-1.12/examples/library-detector/data/icons/modernizr.ico Binary files differindex c37d438..c37d438 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/modernizr.ico +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/modernizr.ico diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/mootools.png b/tools/addon-sdk-1.12/examples/library-detector/data/icons/mootools.png Binary files differindex 2a5df7d..2a5df7d 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/mootools.png +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/mootools.png diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/icons/yui.ico b/tools/addon-sdk-1.12/examples/library-detector/data/icons/yui.ico Binary files differindex 06acd8a..06acd8a 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/icons/yui.ico +++ b/tools/addon-sdk-1.12/examples/library-detector/data/icons/yui.ico diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/library-detector.js b/tools/addon-sdk-1.12/examples/library-detector/data/library-detector.js index af3a88e..af3a88e 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/data/library-detector.js +++ b/tools/addon-sdk-1.12/examples/library-detector/data/library-detector.js diff --git a/tools/addon-sdk-1.12/examples/library-detector/data/panel.html b/tools/addon-sdk-1.12/examples/library-detector/data/panel.html new file mode 100644 index 0000000..2829006 --- /dev/null +++ b/tools/addon-sdk-1.12/examples/library-detector/data/panel.html @@ -0,0 +1,16 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<html> +<head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> + <title>Library detector</title> + <script type="text/javascript"> + addon.on('message', function (libraryInfo) { + document.body.innerHTML = libraryInfo; + }); + </script> +</head> +<body></body> +</html> diff --git a/tools/addon-sdk-1.12/examples/library-detector/data/widget.html b/tools/addon-sdk-1.12/examples/library-detector/data/widget.html new file mode 100755 index 0000000..4ca5b50 --- /dev/null +++ b/tools/addon-sdk-1.12/examples/library-detector/data/widget.html @@ -0,0 +1,50 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<html> +<head> + <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> + <title>Library detector</title> + <style type="text/css" media="all"> + img { + display: inline; + width: 16px; + height: 16px; + } + </style> + <script type="text/javascript"> + var icons = { + 'jQuery' : 'jquery.ico', + 'jQuery UI' : 'jquery_ui.ico', + 'MooTools' : 'mootools.png', + 'YUI' : 'yui.ico', + 'Closure' : 'closure.ico', + 'Modernizr': 'modernizr.ico', + }; + + // Listen for mouse events over icons, in order to send a message up to + // the panel and update its content with library name and version + window.addEventListener('mouseover', function (event) { + if (event.target.tagName == 'IMG') { + addon.port.emit('setLibraryInfo', event.target.title); + } + }, false); + + addon.port.on('update', function (libraries) { + // Cleanup previous content + document.body.innerHTML = ''; + + // Create new updated list of icons + libraries.forEach(function(library) { + var img = document.createElement('img'); + img.setAttribute('src', 'icons/' + icons[library.name]); + img.setAttribute('title', library.name + "<br>Version: " + + library.version); + document.body.appendChild(img); + }); + }); + </script> +</head> +<body></body> +</html> diff --git a/tools/addon-sdk-1.12/examples/library-detector/lib/main.js b/tools/addon-sdk-1.12/examples/library-detector/lib/main.js new file mode 100755 index 0000000..3f2b0c5 --- /dev/null +++ b/tools/addon-sdk-1.12/examples/library-detector/lib/main.js @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const tabs = require('tabs'); +const widgets = require('widget'); +const data = require('self').data; +const pageMod = require('page-mod'); +const panel = require('panel'); + +const ICON_WIDTH = 16; + +function updateWidgetView(tab) { + let widgetView = widget.getView(tab.window); + if (!tab.libraries) { + tab.libraries = []; + } + widgetView.port.emit("update", tab.libraries); + widgetView.width = tab.libraries.length * ICON_WIDTH; +} + +var widget = widgets.Widget({ + id: "library-detector", + label: "Library Detector", + contentURL: data.url("widget.html"), + panel: panel.Panel({ + width: 240, + height: 60, + contentURL: data.url("panel.html") + }) +}); + +widget.port.on('setLibraryInfo', function(libraryInfo) { + widget.panel.postMessage(libraryInfo); +}); + +pageMod.PageMod({ + include: "*", + contentScriptWhen: 'end', + contentScriptFile: (data.url('library-detector.js')), + onAttach: function(worker) { + worker.on('message', function(libraryList) { + if (!worker.tab.libraries) { + worker.tab.libraries = []; + } + libraryList.forEach(function(library) { + if (worker.tab.libraries.indexOf(library) == -1) { + worker.tab.libraries.push(library); + } + }); + if (worker.tab == tabs.activeTab) { + updateWidgetView(worker.tab); + } + }); + } +}); + +tabs.on('activate', function(tab) { + updateWidgetView(tab); +}); + +/* +For change of location +*/ +tabs.on('ready', function(tab) { + tab.libraries = []; +});
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/examples/library-detector/package.json b/tools/addon-sdk-1.12/examples/library-detector/package.json index 6d868ff..6d868ff 100755 --- a/tools/addon-sdk-1.7/examples/library-detector/package.json +++ b/tools/addon-sdk-1.12/examples/library-detector/package.json diff --git a/tools/addon-sdk-1.7/examples/library-detector/test/test-main.js b/tools/addon-sdk-1.12/examples/library-detector/test/test-main.js index 72fedf4..72fedf4 100644 --- a/tools/addon-sdk-1.7/examples/library-detector/test/test-main.js +++ b/tools/addon-sdk-1.12/examples/library-detector/test/test-main.js diff --git a/tools/addon-sdk-1.7/examples/reading-data/data/mom.png b/tools/addon-sdk-1.12/examples/reading-data/data/mom.png Binary files differindex 4ba89a2..4ba89a2 100644 --- a/tools/addon-sdk-1.7/examples/reading-data/data/mom.png +++ b/tools/addon-sdk-1.12/examples/reading-data/data/mom.png diff --git a/tools/addon-sdk-1.7/examples/reading-data/data/sample.html b/tools/addon-sdk-1.12/examples/reading-data/data/sample.html index c7c09cb..c7c09cb 100644 --- a/tools/addon-sdk-1.7/examples/reading-data/data/sample.html +++ b/tools/addon-sdk-1.12/examples/reading-data/data/sample.html diff --git a/tools/addon-sdk-1.7/examples/reading-data/lib/main.js b/tools/addon-sdk-1.12/examples/reading-data/lib/main.js index 89a62a2..89a62a2 100644 --- a/tools/addon-sdk-1.7/examples/reading-data/lib/main.js +++ b/tools/addon-sdk-1.12/examples/reading-data/lib/main.js diff --git a/tools/addon-sdk-1.7/examples/reading-data/package.json b/tools/addon-sdk-1.12/examples/reading-data/package.json index 5fc6b2b..5fc6b2b 100644 --- a/tools/addon-sdk-1.7/examples/reading-data/package.json +++ b/tools/addon-sdk-1.12/examples/reading-data/package.json diff --git a/tools/addon-sdk-1.7/examples/reading-data/tests/test-main.js b/tools/addon-sdk-1.12/examples/reading-data/tests/test-main.js index 1a455fd..1a455fd 100644 --- a/tools/addon-sdk-1.7/examples/reading-data/tests/test-main.js +++ b/tools/addon-sdk-1.12/examples/reading-data/tests/test-main.js diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/README.md b/tools/addon-sdk-1.12/examples/reddit-panel/README.md index 5edfb70..5edfb70 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/README.md +++ b/tools/addon-sdk-1.12/examples/reddit-panel/README.md diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/data/jquery-1.4.4.min.js b/tools/addon-sdk-1.12/examples/reddit-panel/data/jquery-1.4.4.min.js index 8f3ca2e..8f3ca2e 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/data/jquery-1.4.4.min.js +++ b/tools/addon-sdk-1.12/examples/reddit-panel/data/jquery-1.4.4.min.js diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/data/panel.js b/tools/addon-sdk-1.12/examples/reddit-panel/data/panel.js index 03f803c..03f803c 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/data/panel.js +++ b/tools/addon-sdk-1.12/examples/reddit-panel/data/panel.js diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/lib/main.js b/tools/addon-sdk-1.12/examples/reddit-panel/lib/main.js index 4ea8352..4ea8352 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/lib/main.js +++ b/tools/addon-sdk-1.12/examples/reddit-panel/lib/main.js diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/package.json b/tools/addon-sdk-1.12/examples/reddit-panel/package.json index b183fac..b183fac 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/package.json +++ b/tools/addon-sdk-1.12/examples/reddit-panel/package.json diff --git a/tools/addon-sdk-1.7/examples/reddit-panel/tests/test-main.js b/tools/addon-sdk-1.12/examples/reddit-panel/tests/test-main.js index f098135..f098135 100644 --- a/tools/addon-sdk-1.7/examples/reddit-panel/tests/test-main.js +++ b/tools/addon-sdk-1.12/examples/reddit-panel/tests/test-main.js diff --git a/tools/addon-sdk-1.12/lib/sdk/addon-page.js b/tools/addon-sdk-1.12/lib/sdk/addon-page.js new file mode 100644 index 0000000..6440b25 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/addon-page.js @@ -0,0 +1,38 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'experimental' +}; + +const { WindowTracker } = require('./deprecated/window-utils'); +const { isXULBrowser } = require('./window/utils'); +const { add, remove } = require('./util/array'); +const { getTabs, closeTab, getURI } = require('./tabs/utils'); +const { data } = require('./self'); + +const addonURL = data.url('index.html'); + +WindowTracker({ + onTrack: function onTrack(window) { + if (isXULBrowser(window)) + add(window.XULBrowserWindow.inContentWhitelist, addonURL); + }, + onUntrack: function onUntrack(window) { + if (isXULBrowser(window)) + getTabs(window).filter(tabFilter).forEach(untrackTab.bind(null, window)); + } +}); + +function tabFilter(tab) { + return getURI(tab) === addonURL; +} + +function untrackTab(window, tab) { + // Note: `onUntrack` will be called for all windows on add-on unloads, + // so we want to clean them up from these URLs. + remove(window.XULBrowserWindow.inContentWhitelist, addonURL); + closeTab(tab); +} diff --git a/tools/addon-sdk-1.12/lib/sdk/addon/installer.js b/tools/addon-sdk-1.12/lib/sdk/addon/installer.js new file mode 100644 index 0000000..f72b21e --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/addon/installer.js @@ -0,0 +1,106 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.metadata = { + "stability": "experimental" +}; + +const { Cc, Ci, Cu } = require("chrome"); +const { AddonManager } = Cu.import("resource://gre/modules/AddonManager.jsm"); +const { defer } = require("../core/promise"); +const { setTimeout } = require("../timers"); + +/** + * `install` method error codes: + * + * https://developer.mozilla.org/en/Addons/Add-on_Manager/AddonManager#AddonInstall_errors + */ +exports.ERROR_NETWORK_FAILURE = AddonManager.ERROR_NETWORK_FAILURE; +exports.ERROR_INCORRECT_HASH = AddonManager.ERROR_INCORRECT_HASH; +exports.ERROR_CORRUPT_FILE = AddonManager.ERROR_CORRUPT_FILE; +exports.ERROR_FILE_ACCESS = AddonManager.ERROR_FILE_ACCESS; + +/** + * Immediatly install an addon. + * + * @param {String} xpiPath + * file path to an xpi file to install + * @return {Promise} + * A promise resolved when the addon is finally installed. + * Resolved with addon id as value or rejected with an error code. + */ +exports.install = function install(xpiPath) { + let { promise, resolve, reject } = defer(); + + // Create nsIFile for the xpi file + let file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile); + try { + file.initWithPath(xpiPath); + } + catch(e) { + reject(exports.ERROR_FILE_ACCESS); + return promise; + } + + // Listen for installation end + let listener = { + onInstallEnded: function(aInstall, aAddon) { + aInstall.removeListener(listener); + // Bug 749745: on FF14+, onInstallEnded is called just before `startup()` + // is called, but we expect to resolve the promise only after it. + // As startup is called synchronously just after onInstallEnded, + // a simple setTimeout(0) is enough + setTimeout(resolve, 0, aAddon.id); + }, + onInstallFailed: function (aInstall) { + console.log("failed"); + aInstall.removeListener(listener); + reject(aInstall.error); + }, + onDownloadFailed: function(aInstall) { + this.onInstallFailed(aInstall); + } + }; + + // Order AddonManager to install the addon + AddonManager.getInstallForFile(file, function(install) { + install.addListener(listener); + install.install(); + }); + + return promise; +}; + +exports.uninstall = function uninstall(addonId) { + let { promise, resolve, reject } = defer(); + + // Listen for uninstallation end + let listener = { + onUninstalled: function onUninstalled(aAddon) { + if (aAddon.id != addonId) + return; + AddonManager.removeAddonListener(listener); + resolve(); + } + }; + AddonManager.addAddonListener(listener); + + // Order Addonmanager to uninstall the addon + AddonManager.getAddonByID(addonId, function (addon) { + addon.uninstall(); + }); + + return promise; +}; + +exports.disable = function disable(addonId) { + let { promise, resolve, reject } = defer(); + + AddonManager.getAddonByID(addonId, function (addon) { + addon.userDisabled = true; + resolve(); + }); + + return promise; +}; diff --git a/tools/addon-sdk-1.12/lib/sdk/addon/runner.js b/tools/addon-sdk-1.12/lib/sdk/addon/runner.js new file mode 100644 index 0000000..0552de2 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/addon/runner.js @@ -0,0 +1,153 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +module.metadata = { + "stability": "experimental" +}; + +const { Cc, Ci } = require('chrome'); +const { descriptor, Sandbox, evaluate, main, resolveURI } = require('toolkit/loader'); +const { once } = require('../system/events'); +const { exit, env, staticArgs, name } = require('../system'); +const { when: unload } = require('../system/unload'); +const { loadReason } = require('../self'); +const { rootURI } = require("@loader/options"); +const globals = require('../system/globals'); + +const NAME2TOPIC = { + 'Firefox': 'sessionstore-windows-restored', + 'Fennec': 'sessionstore-windows-restored', + 'SeaMonkey': 'sessionstore-windows-restored', + 'Thunderbird': 'mail-startup-done', + '*': 'final-ui-startup' +}; + +// Gets the topic that fit best as application startup event, in according with +// the current application (e.g. Firefox, Fennec, Thunderbird...) +const APP_STARTUP = NAME2TOPIC[name] || NAME2TOPIC['*']; + +// Initializes default preferences +function setDefaultPrefs(prefsURI) { + const prefs = Cc['@mozilla.org/preferences-service;1']. + getService(Ci.nsIPrefService). + QueryInterface(Ci.nsIPrefBranch2); + const branch = prefs.getDefaultBranch(''); + const sandbox = Sandbox({ + name: prefsURI, + prototype: { + pref: function(key, val) { + switch (typeof val) { + case 'boolean': + branch.setBoolPref(key, val); + break; + case 'number': + if (val % 1 == 0) // number must be a integer, otherwise ignore it + branch.setIntPref(key, val); + break; + case 'string': + branch.setCharPref(key, val); + break; + } + } + } + }); + // load preferences. + evaluate(sandbox, prefsURI); +} + +function definePseudo(loader, id, exports) { + let uri = resolveURI(id, loader.mapping); + loader.modules[uri] = { exports: exports }; +} + +function wait(reason, options) { + once(APP_STARTUP, function() { + startup(null, options); + }); +} + +function startup(reason, options) { + if (reason === 'startup') + return wait(reason, options); + + // Inject globals ASAP in order to have console API working ASAP + Object.defineProperties(options.loader.globals, descriptor(globals)); + + // Load localization manifest and .properties files. + // Run the addon even in case of error (best effort approach) + require('../l10n/loader'). + load(rootURI). + then(null, function failure(error) { + console.info("Error while loading localization: " + error.message); + }). + then(function onLocalizationReady(data) { + // Exports data to a pseudo module so that api-utils/l10n/core + // can get access to it + if (data) + definePseudo(options.loader, '@l10n/data', data); + run(options); + }); +} + +function run(options) { + try { + // Try initializing HTML localization before running main module. Just print + // an exception in case of error, instead of preventing addon to be run. + try { + // Do not enable HTML localization while running test as it is hard to + // disable. Because unit tests are evaluated in a another Loader who + // doesn't have access to this current loader. + if (options.main !== 'test-harness/run-tests') + require('../l10n/html').enable(); + } + catch(error) { + console.exception(error); + } + // Initialize inline options localization, without preventing addon to be + // run in case of error + try { + require('../l10n/prefs'); + } + catch(error) { + console.exception(error); + } + + // TODO: When bug 564675 is implemented this will no longer be needed + // Always set the default prefs, because they disappear on restart + setDefaultPrefs(options.prefsURI); + + // this is where the addon's main.js finally run. + let program = main(options.loader, options.main); + + if (typeof(program.onUnload) === 'function') + unload(program.onUnload); + + if (typeof(program.main) === 'function') { + + program.main({ + loadReason: loadReason, + staticArgs: staticArgs + }, { + print: function print(_) { dump(_ + '\n') }, + quit: exit + }); + } + } catch (error) { + console.exception(error); + throw error; + } +} +exports.startup = startup; + +// If add-on is lunched via `cfx run` we need to use `system.exit` to let +// cfx know we're done (`cfx test` will take care of exit so we don't do +// anything here). +if (env.CFX_COMMAND === 'run') { + unload(function(reason) { + if (reason === 'shutdown') + exit(0); + }); +} diff --git a/tools/addon-sdk-1.12/lib/sdk/base64.js b/tools/addon-sdk-1.12/lib/sdk/base64.js new file mode 100644 index 0000000..42fea57 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/base64.js @@ -0,0 +1,41 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "unstable" +}; + +const { Cu } = require("chrome"); + +// If an object is not given as second argument, the JavaScript Module scope is +// returned, so we can obtain from it the `atob` and `btoa` functions +const { atob, btoa } = Cu.import("resource://gre/modules/Services.jsm"); + +function isUTF8(charset) { + let type = typeof charset; + + if (type === "undefined") + return false; + + if (type === "string" && charset.toLowerCase() === "utf-8") + return true; + + throw new Error("The charset argument can be only 'utf-8'"); +} + +exports.decode = function (data, charset) { + if (isUTF8(charset)) + return decodeURIComponent(escape(atob(data))) + + return atob(data); +} + +exports.encode = function (data, charset) { + if (isUTF8(charset)) + return btoa(unescape(encodeURIComponent(data))) + + return btoa(data); +} diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/clipboard.js b/tools/addon-sdk-1.12/lib/sdk/clipboard.js index 2feab22..58a3d7e 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/clipboard.js +++ b/tools/addon-sdk-1.12/lib/sdk/clipboard.js @@ -6,22 +6,27 @@ "use strict"; -const {Cc,Ci} = require("chrome"); -const errors = require("api-utils/errors"); -const apiUtils = require("api-utils/api-utils"); - +module.metadata = { + "stability": "stable" +}; + +const { Cc, Ci } = require("chrome"); +const { DataURL } = require("./url"); +const errors = require("./deprecated/errors"); +const apiUtils = require("./deprecated/api-utils"); /* While these data flavors resemble Internet media types, they do no directly map to them. */ const kAllowableFlavors = [ "text/unicode", - "text/html" + "text/html", + "image/png" /* CURRENTLY UNSUPPORTED FLAVORS "text/plain", - "image/png", "image/jpg", - "image/gif" + "image/jpeg", + "image/gif", "text/x-moz-text-internal", "AOLMAIL", "application/x-moz-file", @@ -45,9 +50,8 @@ Jetpack API druid. */ const kFlavorMap = [ { short: "text", long: "text/unicode" }, - { short: "html", long: "text/html" } - // Images are currently unsupported. - //{ short: "image", long: "image/png" }, + { short: "html", long: "text/html" }, + { short: "image", long: "image/png" } ]; let clipboardService = Cc["@mozilla.org/widget/clipboard;1"]. @@ -56,12 +60,30 @@ let clipboardService = Cc["@mozilla.org/widget/clipboard;1"]. let clipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"]. getService(Ci.nsIClipboardHelper); +let imageTools = Cc["@mozilla.org/image/tools;1"]. + getService(Ci.imgITools); exports.set = function(aData, aDataType) { + let options = { data: aData, datatype: aDataType || "text" }; + + // If `aDataType` is not given or if it's "image", the data is parsed as + // data URL to detect a better datatype + if (aData && (!aDataType || aDataType === "image")) { + try { + let dataURL = new DataURL(aData); + + options.datatype = dataURL.mimeType; + options.data = dataURL.data; + } + catch (e if e.name === "URIError") { + // Not a valid Data URL + } + } + options = apiUtils.validateOptions(options, { data: { is: ["string"] @@ -71,10 +93,10 @@ exports.set = function(aData, aDataType) { } }); - var flavor = fromJetpackFlavor(options.datatype); + let flavor = fromJetpackFlavor(options.datatype); if (!flavor) - throw new Error("Invalid flavor"); + throw new Error("Invalid flavor for " + options.datatype); // Additional checks for using the simple case if (flavor == "text/unicode") { @@ -87,8 +109,11 @@ exports.set = function(aData, aDataType) { var xferable = Cc["@mozilla.org/widget/transferable;1"]. createInstance(Ci.nsITransferable); if (!xferable) - throw new Error("Couldn't set the clipboard due to an internal error " + + throw new Error("Couldn't set the clipboard due to an internal error " + "(couldn't create a Transferable object)."); + // Bug 769440: Starting with FF16, transferable have to be inited + if ("init" in xferable) + xferable.init(null); switch (flavor) { case "text/html": @@ -114,7 +139,40 @@ exports.set = function(aData, aDataType) { xferable.setTransferData("text/unicode", str, str.data.length * 2); } break; - // TODO: images! + + // Set images to the clipboard is not straightforward, to have an idea how + // it works on platform side, see: + // http://mxr.mozilla.org/mozilla-central/source/content/base/src/nsCopySupport.cpp?rev=7857c5bff017#530 + case "image/png": + let image = options.data; + + let container = {}; + + try { + let input = Cc["@mozilla.org/io/string-input-stream;1"]. + createInstance(Ci.nsIStringInputStream); + + input.setData(image, image.length); + + imageTools.decodeImageData(input, flavor, container); + } + catch (e) { + throw new Error("Unable to decode data given in a valid image."); + } + + // Store directly the input stream makes the cliboard's data available + // for Firefox but not to the others application or to the OS. Therefore, + // a `nsISupportsInterfacePointer` object that reference an `imgIContainer` + // with the image is needed. + var imgPtr = Cc["@mozilla.org/supports-interface-pointer;1"]. + createInstance(Ci.nsISupportsInterfacePointer); + + imgPtr.data = container.value; + + xferable.addDataFlavor(flavor); + xferable.setTransferData(flavor, imgPtr, -1); + + break; default: throw new Error("Unable to handle the flavor " + flavor + "."); } @@ -135,8 +193,17 @@ exports.set = function(aData, aDataType) { exports.get = function(aDataType) { let options = { - datatype: aDataType || "text" + datatype: aDataType }; + + // Figure out the best data type for the clipboard's data, if omitted + if (!aDataType) { + if (~currentFlavors().indexOf("image")) + options.datatype = "image"; + else + options.datatype = "text"; + } + options = apiUtils.validateOptions(options, { datatype: { is: ["string"] @@ -146,20 +213,22 @@ exports.get = function(aDataType) { var xferable = Cc["@mozilla.org/widget/transferable;1"]. createInstance(Ci.nsITransferable); if (!xferable) - throw new Error("Couldn't set the clipboard due to an internal error " + + throw new Error("Couldn't set the clipboard due to an internal error " + "(couldn't create a Transferable object)."); + // Bug 769440: Starting with FF16, transferable have to be inited + if ("init" in xferable) + xferable.init(null); var flavor = fromJetpackFlavor(options.datatype); // Ensure that the user hasn't requested a flavor that we don't support. if (!flavor) throw new Error("Getting the clipboard with the flavor '" + flavor + - "' is > not supported."); + "' is not supported."); // TODO: Check for matching flavor first? Probably not worth it. xferable.addDataFlavor(flavor); - // Get the data into our transferable. clipboardService.getData( xferable, @@ -185,6 +254,38 @@ exports.get = function(aDataType) { case "text/html": data = data.value.QueryInterface(Ci.nsISupportsString).data; break; + case "image/png": + let dataURL = new DataURL(); + + dataURL.mimeType = flavor; + dataURL.base64 = true; + + let image = data.value; + + // Due to the differences in how images could be stored in the clipboard + // the checks below are needed. The clipboard could already provide the + // image as byte streams, but also as pointer, or as image container. + // If it's not possible obtain a byte stream, the function returns `null`. + if (image instanceof Ci.nsISupportsInterfacePointer) + image = image.data; + + if (image instanceof Ci.imgIContainer) + image = imageTools.encodeImage(image, flavor); + + if (image instanceof Ci.nsIInputStream) { + let binaryStream = Cc["@mozilla.org/binaryinputstream;1"]. + createInstance(Ci.nsIBinaryInputStream); + + binaryStream.setInputStream(image); + + dataURL.data = binaryStream.readBytes(binaryStream.available()); + + data = dataURL.toString(); + } + else + data = null; + + break; default: data = null; } @@ -192,7 +293,7 @@ exports.get = function(aDataType) { return data; }; -exports.__defineGetter__("currentFlavors", function() { +function currentFlavors() { // Loop over kAllowableFlavors, calling hasDataMatchingFlavors for each. // This doesn't seem like the most efficient way, but we can't get // confirmation for specific flavors any other way. This is supposed to be @@ -208,7 +309,9 @@ exports.__defineGetter__("currentFlavors", function() { currentFlavors.push(toJetpackFlavor(flavor)); } return currentFlavors; -}); +}; + +Object.defineProperty(exports, "currentFlavors", { get : currentFlavors }); // SUPPORT FUNCTIONS //////////////////////////////////////////////////////// diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/plain-text-console.js b/tools/addon-sdk-1.12/lib/sdk/console/plain-text.js index d76fddb..9e3b748 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/plain-text-console.js +++ b/tools/addon-sdk-1.12/lib/sdk/console/plain-text.js @@ -4,7 +4,12 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const {Cc,Ci} = require("chrome"); +const self = require("../self"); function stringify(arg) { try { @@ -19,8 +24,9 @@ function stringifyArgs(args) { return Array.map(args, stringify).join(" "); } -function message(print, level, args) { - print(level + ": " + stringifyArgs(args) + "\n", level); +function message(print, level, args, name) { + print(level + ": " + name + ": " + + stringifyArgs(args) + "\n", level); } var Console = exports.PlainTextConsole = function PlainTextConsole(print) { @@ -48,23 +54,23 @@ var Console = exports.PlainTextConsole = function PlainTextConsole(print) { Console.prototype = { log: function log() { - message(this.print, "info", arguments); + message(this.print, "info", arguments, self.name); }, info: function info() { - message(this.print, "info", arguments); + message(this.print, "info", arguments, self.name); }, warn: function warn() { - message(this.print, "warning", arguments); + message(this.print, "warning", arguments, self.name); }, error: function error() { - message(this.print, "error", arguments); + message(this.print, "error", arguments, self.name); }, debug: function debug() { - message(this.print, "debug", arguments); + message(this.print, "debug", arguments, self.name); }, exception: function exception(e) { @@ -77,6 +83,6 @@ Console.prototype = { var traceback = require("./traceback"); var stack = traceback.get(); stack.splice(-1, 1); - message(this.print, "info", [traceback.format(stack)]); + message(this.print, "info", [traceback.format(stack)], self.name); } }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/traceback.js b/tools/addon-sdk-1.12/lib/sdk/console/traceback.js index c55fd9d..6b23be1 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/traceback.js +++ b/tools/addon-sdk-1.12/lib/sdk/console/traceback.js @@ -4,37 +4,25 @@ "use strict"; -const {Cc,Ci,components} = require("chrome"); +module.metadata = { + "stability": "experimental" +}; + +const { Cc, Ci, components } = require("chrome"); +const { readURISync } = require("../net/url"); // Undo the auto-parentification of URLs done in bug 418356. function deParentifyURL(url) { return url ? url.split(" -> ").slice(-1)[0] : url; } -// TODO: We might want to move this function to url or some similar -// module. -function getLocalFile(path) { - var ios = Cc['@mozilla.org/network/io-service;1'] - .getService(Ci.nsIIOService); - var channel = ios.newChannel(path, null, null); - var iStream = channel.open(); - var siStream = Cc['@mozilla.org/scriptableinputstream;1'] - .createInstance(Ci.nsIScriptableInputStream); - siStream.init(iStream); - var data = new String(); - data += siStream.read(-1); - siStream.close(); - iStream.close(); - return data; -} - function safeGetFileLine(path, line) { try { - var scheme = require("./url").URL(path).scheme; + var scheme = require("../url").URL(path).scheme; // TODO: There should be an easier, more accurate way to figure out // what's the case here. if (!(scheme == "http" || scheme == "https")) - return getLocalFile(path).split("\n")[line - 1]; + return readURISync(path).split("\n")[line - 1]; } catch (e) {} return null; } @@ -52,7 +40,13 @@ function errorStackToJSON(stack) { var filename = deParentifyURL(line.slice(atIndex + 1, colonIndex)); var lineNo = parseInt(line.slice(colonIndex + 1)); var funcSig = line.slice(0, atIndex); - var funcName = funcSig.slice(0, funcSig.indexOf("(")); + var endFuncName = funcSig.indexOf("("); + // Bug 751149: FF15 changed function signature + // Instead of: runTest([object Object]) + // We now have: runTest + var funcName = endFuncName != -1 + ? funcSig.slice(0, endFuncName) + : funcSig; frames.unshift({filename: filename, funcName: funcName, lineNo: lineNo}); @@ -111,7 +105,8 @@ var format = exports.format = function format(tbOrException) { tb.forEach( function(frame) { if (!(frame.filename || frame.lineNo || frame.funcName)) - return; + return; + lines.push(' File "' + frame.filename + '", line ' + frame.lineNo + ', in ' + frame.funcName); var sourceLine = safeGetFileLine(frame.filename, frame.lineNo); diff --git a/tools/addon-sdk-1.7/packages/api-utils/data/content-proxy.js b/tools/addon-sdk-1.12/lib/sdk/content/content-proxy.js index f0a39d3..76df7f6 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/data/content-proxy.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/content-proxy.js @@ -4,7 +4,13 @@ "use strict"; -let Ci = Components.interfaces; +/* Trick the linker in order to avoid error on `Components.interfaces` usage. + We are tricking the linker with `require('./content-proxy.js')` from + worjer.js in order to ensure shipping this file! But then the linker think + that this file is going to be used as a CommonJS module where we forbid usage + of `Components`. +*/ +let Ci = Components['interfaces']; /** * Access key that allows privileged code to unwrap proxy wrappers through @@ -477,7 +483,7 @@ function isEventName(id) { // Here is a list of functions that return a value when it detects a miss: const NODES_INDEXED_BY_NAME = ["IMG", "FORM", "APPLET", "EMBED", "OBJECT"]; const xRayWrappersMissFixes = [ - + // Fix bug with XPCNativeWrapper on HTMLCollection // We can only access array item once, then it's undefined :o function (obj, name) { @@ -488,7 +494,7 @@ const xRayWrappersMissFixes = [ } return null; }, - + // Trap access to document["form name"] // that may refer to an existing form node // http://mxr.mozilla.org/mozilla-central/source/dom/base/nsDOMClassInfo.cpp#9285 @@ -502,7 +508,7 @@ const xRayWrappersMissFixes = [ } return null; }, - + // Trap access to window["frame name"] and window.frames[i] // that refer to an (i)frame internal window object // http://mxr.mozilla.org/mozilla-central/source/dom/base/nsDOMClassInfo.cpp#6824 @@ -535,11 +541,11 @@ const xRayWrappersMissFixes = [ } return null; }, - + // Trap access to form["node name"] // http://mxr.mozilla.org/mozilla-central/source/dom/base/nsDOMClassInfo.cpp#9477 function (obj, name) { - if (typeof obj == "object" && obj.tagName == "FORM") { + if (typeof obj == "object" && "tagName" in obj && obj.tagName == "FORM") { let match = obj.wrappedJSObject[name]; let nodes = obj.ownerDocument.getElementsByName(name); for (let i = 0, l = nodes.length; i < l; i++) { @@ -549,21 +555,6 @@ const xRayWrappersMissFixes = [ } } return null; - }, - - // Fix XPathResult's constants being undefined on XrayWrappers - // these constants are defined here: - // http://mxr.mozilla.org/mozilla-central/source/dom/interfaces/xpath/nsIDOMXPathResult.idl - // and are only numbers. - // The platform bug 665279 was fixed in Gecko 10.0a1. - // FIXME: remove this workaround once the SDK no longer supports Firefox 9. - function (obj, name) { - if (typeof obj == "object" && name in Ci.nsIDOMXPathResult) { - let value = Ci.nsIDOMXPathResult[name]; - if (typeof value == "number" && value === obj.wrappedJSObject[name]) - return value; - } - return null; } ]; @@ -587,13 +578,18 @@ const xRayWrappersMethodsFixes = { catch(e) { return null; } + // Create a wrapper that is going to call `postMessage` through `eval` let f = function postMessage(message, targetOrigin) { - message = message.toString().replace(/['\\]/g,"\\$&"); + let jscode = "this.postMessage("; + if (typeof message != "string") + jscode += JSON.stringify(message); + else + jscode += "'" + message.toString().replace(/['\\]/g,"\\$&") + "'"; + targetOrigin = targetOrigin.toString().replace(/['\\]/g,"\\$&"); - let jscode = "this.postMessage('" + message + "', '" + - targetOrigin + "')"; + jscode += ", '" + targetOrigin + "')"; return this.wrappedJSObject.eval(jscode); }; return getProxyForFunction(f, NativeFunctionWrapper(f)); @@ -657,6 +653,33 @@ const xRayWrappersMethodsFixes = { }; return getProxyForFunction(f, NativeFunctionWrapper(f)); + }, + + // Bug 769006: nsIDOMMutationObserver.observe fails with proxy as options + // attributes + observe: function observe(obj) { + // Ensure that we are on a DOMMutation object + try { + // nsIDOMMutationObserver starts with FF14 + if ("nsIDOMMutationObserver" in Ci) + obj.QueryInterface(Ci.nsIDOMMutationObserver); + else + return null; + } + catch(e) { + return null; + } + return function nsIDOMMutationObserverObserveFix(target, options) { + // Gets native/unwrapped this + let self = this && typeof this.valueOf == "function" ? + this.valueOf(UNWRAP_ACCESS_KEY) : this; + // Unwrap the xraywrapper target out of JS proxy + let targetXray = unwrap(target); + // But do not wrap `options` through ContentScriptObjectWrapper + let result = wrap(self.observe(targetXray, options)); + // Finally wrap result into JS proxies + return wrap(result); + }; } }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/data/worker.js b/tools/addon-sdk-1.12/lib/sdk/content/content-worker.js index aba594d..8cf9c5c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/data/worker.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/content-worker.js @@ -30,7 +30,7 @@ const ContentWorker = Object.freeze({ removeListener: function removeListener(name, callback) { if (!(name in listeners)) return; - let index = listeners[name].indexOf(name); + let index = listeners[name].indexOf(callback); if (index == -1) return; listeners[name].splice(index, 1); @@ -129,49 +129,98 @@ const ContentWorker = Object.freeze({ clearInterval: chromeClearInterval } = chromeAPI.timers; - exports.setTimeout = function ContentScriptSetTimeout(callback, delay) { - let params = Array.slice(arguments, 2); - let id = chromeSetTimeout(function() { + function registerTimer(timer) { + let registerMethod = null; + if (timer.kind == "timeout") + registerMethod = chromeSetTimeout; + else if (timer.kind == "interval") + registerMethod = chromeSetInterval; + else + throw new Error("Unknown timer kind: " + timer.kind); + let id = registerMethod(onFire, timer.delay); + function onFire() { try { - delete _timers[id]; - callback.apply(null, params); + if (timer.kind == "timeout") + delete _timers[id]; + timer.fun.apply(null, timer.args); } catch(e) { console.exception(e); } - }, delay); - _timers[id] = "timeout"; + } + _timers[id] = timer; return id; + } + + function unregisterTimer(id) { + if (!(id in _timers)) + return; + let { kind } = _timers[id]; + delete _timers[id]; + if (kind == "timeout") + chromeClearTimeout(id); + else if (kind == "interval") + chromeClearInterval(id); + else + throw new Error("Unknown timer kind: " + kind); + } + + function disableAllTimers() { + Object.keys(_timers).forEach(unregisterTimer); + } + + exports.setTimeout = function ContentScriptSetTimeout(callback, delay) { + return registerTimer({ + kind: "timeout", + fun: callback, + delay: delay, + args: Array.slice(arguments, 2) + }); }; exports.clearTimeout = function ContentScriptClearTimeout(id) { - delete _timers[id]; - return chromeClearTimeout(id); + unregisterTimer(id); }; exports.setInterval = function ContentScriptSetInterval(callback, delay) { - let params = Array.slice(arguments, 2); - let id = chromeSetInterval(function() { - try { - callback.apply(null, params); - } catch(e) { - console.exception(e); - } - }, delay); - _timers[id] = "interval"; - return id; + return registerTimer({ + kind: "interval", + fun: callback, + delay: delay, + args: Array.slice(arguments, 2) + }); }; exports.clearInterval = function ContentScriptClearInterval(id) { - delete _timers[id]; - return chromeClearInterval(id); + unregisterTimer(id); }; - pipe.on("destroy", function clearTimeouts() { - // Unregister all setTimeout/setInterval on page unload - for (let id in _timers) { - let kind = _timers[id]; - if (kind == "timeout") - chromeClearTimeout(id); - else - chromeClearInterval(id); - } + + // On page-hide, save a list of all existing timers before disabling them, + // in order to be able to restore them on page-show. + // These events are fired when the page goes in/out of bfcache. + // https://developer.mozilla.org/En/Working_with_BFCache + let frozenTimers = []; + pipe.on("pageshow", function onPageShow() { + frozenTimers.forEach(registerTimer); + }); + pipe.on("pagehide", function onPageHide() { + frozenTimers = []; + for (let id in _timers) + frozenTimers.push(_timers[id]); + disableAllTimers(); + // Some other pagehide listeners may register some timers that won't be + // frozen as this particular pagehide listener is called first. + // So freeze these timers on next cycle. + chromeSetTimeout(function () { + for (let id in _timers) + frozenTimers.push(_timers[id]); + disableAllTimers(); + }, 0); + }); + + // Unregister all timers when the page is destroyed + // (i.e. when it is removed from bfcache) + pipe.on("detach", function clearTimeouts() { + disableAllTimers(); + _timers = {}; + frozenTimers = []; }); }, @@ -181,35 +230,35 @@ const ContentWorker = Object.freeze({ ContentWorker.createEventEmitter(pipe.emit.bind(null, "event")); pipe.on("event", portEmit); - let self = Object.freeze({ + let self = { port: port, postMessage: pipe.emit.bind(null, "message"), on: pipe.on.bind(null), once: pipe.once.bind(null), removeListener: pipe.removeListener.bind(null), - }); + }; Object.defineProperty(exports, "self", { value: self }); // Deprecated use of on/postMessage from globals exports.postMessage = function deprecatedPostMessage() { - console.warn("The global `postMessage()` function in content " + - "scripts is deprecated in favor of the " + - "`self.postMessage()` function, which works the same. " + - "Replace calls to `postMessage()` with calls to " + - "`self.postMessage()`." + - "For more info on `self.on`, see " + - "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); + console.error("DEPRECATED: The global `postMessage()` function in " + + "content scripts is deprecated in favor of the " + + "`self.postMessage()` function, which works the same. " + + "Replace calls to `postMessage()` with calls to " + + "`self.postMessage()`." + + "For more info on `self.on`, see " + + "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); return self.postMessage.apply(null, arguments); }; exports.on = function deprecatedOn() { - console.warn("The global `on()` function in content scripts is " + - "deprecated in favor of the `self.on()` function, " + - "which works the same. Replace calls to `on()` with " + - "calls to `self.on()`" + - "For more info on `self.on`, see " + - "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); + console.error("DEPRECATED: The global `on()` function in content " + + "scripts is deprecated in favor of the `self.on()` " + + "function, which works the same. Replace calls to `on()` " + + "with calls to `self.on()`" + + "For more info on `self.on`, see " + + "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); return self.on.apply(null, arguments); }; @@ -220,12 +269,13 @@ const ContentWorker = Object.freeze({ set: function (v) { if (onMessage) self.removeListener("message", onMessage); - console.warn("The global `onMessage` function in content scripts " + - "is deprecated in favor of the `self.on()` function. " + - "Replace `onMessage = function (data){}` definitions " + - "with calls to `self.on('message', function (data){})`. " + - "For more info on `self.on`, see " + - "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); + console.error("DEPRECATED: The global `onMessage` function in content" + + "scripts is deprecated in favor of the `self.on()` " + + "function. Replace `onMessage = function (data){}` " + + "definitions with calls to `self.on('message', " + + "function (data){})`. " + + "For more info on `self.on`, see " + + "<https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/addon-development/web-content.html>."); onMessage = v; if (typeof onMessage == "function") self.on("message", onMessage); @@ -233,12 +283,23 @@ const ContentWorker = Object.freeze({ }); }, - inject: function (exports, chromeAPI, emitToChrome) { + injectOptions: function (exports, options) { + Object.defineProperty( exports.self, "options", { value: JSON.parse( options ) }); + }, + + inject: function (exports, chromeAPI, emitToChrome, options) { let { pipe, onChromeEvent, hasListenerFor } = ContentWorker.createPipe(emitToChrome); + ContentWorker.injectConsole(exports, pipe); ContentWorker.injectTimers(exports, chromeAPI, pipe, exports.console); ContentWorker.injectMessageAPI(exports, pipe); + if ( options !== undefined ) { + ContentWorker.injectOptions(exports, options); + } + + Object.freeze( exports.self ); + return { emitToContent: onChromeEvent, hasListenerFor: hasListenerFor diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/content.js b/tools/addon-sdk-1.12/lib/sdk/content/content.js index a4acb94..4bffd45 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/content.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/content.js @@ -5,7 +5,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -exports.Loader = require('./content/loader').Loader; -exports.Symbiont = require('./content/symbiont').Symbiont; -exports.Worker = require('./content/worker').Worker; +module.metadata = { + "stability": "unstable" +}; + +exports.Loader = require('./loader').Loader; +exports.Symbiont = require('./symbiont').Symbiont; +exports.Worker = require('./worker').Worker; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/content/loader.js b/tools/addon-sdk-1.12/lib/sdk/content/loader.js index 62c3ad0..b01675c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/content/loader.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/loader.js @@ -6,10 +6,14 @@ "use strict"; -const { EventEmitter } = require('../events'); -const { validateOptions } = require('../api-utils'); +module.metadata = { + "stability": "unstable" +}; + +const { EventEmitter } = require('../deprecated/events'); +const { validateOptions } = require('../deprecated/api-utils'); const { URL } = require('../url'); -const file = require('../file'); +const file = require('../io/file'); const LOCAL_URI_SCHEMES = ['resource', 'data']; @@ -71,6 +75,15 @@ const valid = { return value || 'end'; }, msg: 'The `contentScriptWhen` option must be either "start", "ready" or "end".' + }, + contentScriptOptions: { + ok: function(value) { + if ( value === undefined ) { return true; } + try { JSON.parse( JSON.stringify( value ) ); } catch(e) { return false; } + return true; + }, + map: function(value) 'undefined' === getTypeOf(value) ? null : value, + msg: 'The contentScriptOptions should be a jsonable value.' } }; exports.validationAttributes = valid; @@ -144,6 +157,18 @@ const Loader = EventEmitter.compose({ }, _contentScriptWhen: 'end', /** + * Options avalaible from the content script as `self.options`. + * The value of options can be of any type (object, array, string, etc.) + * but only jsonable values will be available as frozen objects from the + * content script. + * Property change emits `propertyChange` event on instance with this key + * and new value. + * @type {Object} + */ + get contentScriptOptions() this._contentScriptOptions, + set contentScriptOptions(value) this._contentScriptOptions = value, + _contentScriptOptions: null, + /** * The URLs of content scripts. * Property change emits `propertyChange` event on instance with this key * and new value. diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/content/symbiont.js b/tools/addon-sdk-1.12/lib/sdk/content/symbiont.js index e7c959c..186e9d3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/content/symbiont.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/symbiont.js @@ -5,11 +5,17 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Worker } = require('./worker'); const { Loader } = require('./loader'); -const hiddenFrames = require('../hidden-frame'); -const observers = require('../observer-service'); -const unload = require('../unload'); +const hiddenFrames = require('../frame/hidden-frame'); +const observers = require('../deprecated/observer-service'); +const unload = require('../system/unload'); + +const assetsURI = require('../self').data.url(); /** * This trait is layered on top of `Worker` and in contrast to symbiont @@ -40,6 +46,8 @@ const Symbiont = Worker.resolve({ this.contentURL = options.contentURL; if ('contentScriptWhen' in options) this.contentScriptWhen = options.contentScriptWhen; + if ('contentScriptOptions' in options) + this.contentScriptOptions = options.contentScriptOptions; if ('contentScriptFile' in options) this.contentScriptFile = options.contentScriptFile; if ('contentScript' in options) @@ -58,6 +66,12 @@ const Symbiont = Worker.resolve({ this._hiddenFrame = hiddenFrames.HiddenFrame({ onReady: function onFrame() { self._initFrame(this.element); + }, + onUnload: function onUnload() { + // Bug 751211: Remove reference to _frame when hidden frame is + // automatically removed on unload, otherwise we are going to face + // "dead object" exception + self.destroy(); } }); hiddenFrames.add(this._hiddenFrame); @@ -99,7 +113,7 @@ const Symbiont = Worker.resolve({ // one of our addon folder and if no content script are defined. bug 612726 let isDataResource = typeof this._contentURL == "string" && - this._contentURL.indexOf(require("@packaging").uriPrefix) == 0; + this._contentURL.indexOf(assetsURI) == 0; let hasContentScript = (Array.isArray(this.contentScript) ? this.contentScript.length > 0 : !!this.contentScript) || diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/thumbnail.js b/tools/addon-sdk-1.12/lib/sdk/content/thumbnail.js index dfd03dd..9e57274 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/thumbnail.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/thumbnail.js @@ -1,15 +1,18 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -"use strict"; +module.metadata = { + 'stability': 'unstable' +}; -const { Cc, Ci, Cu } = require("chrome"); -const AppShellService = Cc["@mozilla.org/appshell/appShellService;1"]. - getService(Ci.nsIAppShellService); +const { Cc, Ci, Cu } = require('chrome'); +const AppShellService = Cc['@mozilla.org/appshell/appShellService;1']. + getService(Ci.nsIAppShellService); -const NS = "http://www.w3.org/1999/xhtml"; -const COLOR = "rgb(255,255,255)"; +const NS = 'http://www.w3.org/1999/xhtml'; +const COLOR = 'rgb(255,255,255)'; /** * Creates canvas element with a thumbnail of the passed window. @@ -19,11 +22,11 @@ const COLOR = "rgb(255,255,255)"; function getThumbnailCanvasForWindow(window) { let aspectRatio = 0.5625; // 16:9 let thumbnail = AppShellService.hiddenDOMWindow.document - .createElementNS(NS, "canvas"); + .createElementNS(NS, 'canvas'); thumbnail.mozOpaque = true; thumbnail.width = Math.ceil(window.screen.availWidth / 5.75); thumbnail.height = Math.round(thumbnail.width * aspectRatio); - let ctx = thumbnail.getContext("2d"); + let ctx = thumbnail.getContext('2d'); let snippetWidth = window.innerWidth * .6; let scale = thumbnail.width / snippetWidth; ctx.scale(scale, scale); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/content/worker.js b/tools/addon-sdk-1.12/lib/sdk/content/worker.js index c6f35d9..b2f204c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/content/worker.js +++ b/tools/addon-sdk-1.12/lib/sdk/content/worker.js @@ -5,25 +5,42 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Trait } = require('../traits'); -const { EventEmitter, EventEmitterTrait } = require('../events'); +module.metadata = { + "stability": "unstable" +}; + +const { Trait } = require('../deprecated/traits'); +const { EventEmitter, EventEmitterTrait } = require('../deprecated/events'); const { Ci, Cu, Cc } = require('chrome'); -const timer = require('../timer'); +const timer = require('../timers'); const { URL } = require('../url'); -const unload = require('../unload'); -const observers = require('../observer-service'); -const { Cortex } = require('../cortex'); -const self = require("self"); -const { sandbox, evaluate, load } = require("../sandbox"); -const { merge } = require('../utils/object'); - -const CONTENT_PROXY_URL = self.data.url("content-proxy.js"); -const CONTENT_WORKER_URL = self.data.url("worker.js"); +const unload = require('../system/unload'); +const observers = require('../deprecated/observer-service'); +const { Cortex } = require('../deprecated/cortex'); +const { sandbox, evaluate, load } = require("../loader/sandbox"); +const { merge } = require('../util/object'); +const xulApp = require("../system/xul-app"); +const USE_JS_PROXIES = !xulApp.versionInRange(xulApp.platformVersion, + "17.0a2", "*"); +const { getTabForWindow } = require('../tabs/helpers'); + +/* Trick the linker in order to ensure shipping these files in the XPI. + require('./content-proxy.js'); + require('./content-worker.js'); + Then, retrieve URL of these files in the XPI: +*/ +let prefix = module.uri.split('worker.js')[0]; +const CONTENT_PROXY_URL = prefix + 'content-proxy.js'; +const CONTENT_WORKER_URL = prefix + 'content-worker.js'; const JS_VERSION = '1.8'; const ERR_DESTROYED = - "The page has been destroyed and can no longer be used."; + "Couldn't find the worker to receive this message. " + + "The script may not be initialized yet, or may already have been unloaded."; + +const ERR_FROZEN = "The page is currently hidden and can no longer be used " + + "until it is visible again."; /** * This key is not exported and should only be used for proxy tests. @@ -63,7 +80,13 @@ const WorkerSandbox = EventEmitter.compose({ * Mainly used by context-menu in order to avoid breaking it. */ emitSync: function emitSync() { - return this._emitToContent(Array.slice(arguments)); + let args = Array.slice(arguments); + // Bug 732716: Ensure wrapping xrays sent to the content script + // otherwise it will have access to raw xraywrappers and content script + // will assume it is an user object coming from the content script sandbox + if ("_wrap" in this) + args = args.map(this._wrap); + return this._emitToContent(args); }, /** @@ -105,15 +128,18 @@ const WorkerSandbox = EventEmitter.compose({ // Instantiate trusted code in another Sandbox in order to prevent content // script from messing with standard classes used by proxy and API code. - let apiSanbox = sandbox(window, { wantXrays: true }); + let apiSandbox = sandbox(window, { wantXrays: true }); // Build content proxies only if the document has a non-system principal - if (window.wrappedJSObject) { - apiSanbox.console = console; + // And only on old firefox versions that doesn't ship bug 738244 + if (USE_JS_PROXIES && XPCNativeWrapper.unwrap(window) !== window) { + apiSandbox.console = console; // Execute the proxy code - load(apiSanbox, CONTENT_PROXY_URL); + load(apiSandbox, CONTENT_PROXY_URL); // Get a reference of the window's proxy - proto = apiSanbox.create(window); + proto = apiSandbox.create(window); + // Keep a reference to `wrap` function for `emitSync` usage + this._wrap = apiSandbox.wrap; } // Create the sandbox and bind it to window in order for content scripts to @@ -122,10 +148,16 @@ const WorkerSandbox = EventEmitter.compose({ sandboxPrototype: proto, wantXrays: true }); + // We have to ensure that window.top and window.parent are the exact same + // object than window object, i.e. the sandbox global object. But not + // always, in case of iframes, top and parent are another window object. + let top = window.top === window ? content : content.top; + let parent = window.parent === window ? content : content.parent; merge(content, { // We need "this === window === top" to be true in toplevel scope: get window() content, - get top() content, + get top() top, + get parent() parent, // Use the Greasemonkey naming convention to provide access to the // unwrapped window object so the content script can access document // JavaScript values. @@ -137,23 +169,41 @@ const WorkerSandbox = EventEmitter.compose({ // Load trusted code that will inject content script API. // We need to expose JS objects defined in same principal in order to // avoid having any kind of wrapper. - load(apiSanbox, CONTENT_WORKER_URL); + load(apiSandbox, CONTENT_WORKER_URL); + + // prepare a clean `self.options` + let options = 'contentScriptOptions' in worker ? + JSON.stringify( worker.contentScriptOptions ) : + undefined; // Then call `inject` method and communicate with this script // by trading two methods that allow to send events to the other side: // - `onEvent` called by content script // - `result.emitToContent` called by addon script + // Bug 758203: We have to explicitely define `__exposedProps__` in order + // to allow access to these chrome object attributes from this sandbox with + // content priviledges + // https://developer.mozilla.org/en/XPConnect_wrappers#Other_security_wrappers let chromeAPI = { timers: { setTimeout: timer.setTimeout, setInterval: timer.setInterval, clearTimeout: timer.clearTimeout, - clearInterval: timer.clearInterval + clearInterval: timer.clearInterval, + __exposedProps__: { + setTimeout: 'r', + setInterval: 'r', + clearTimeout: 'r', + clearInterval: 'r' + } + }, + __exposedProps__: { + timers: 'r' } }; let onEvent = this._onContentEvent.bind(this); // `ContentWorker` is defined in CONTENT_WORKER_URL file - let result = apiSanbox.ContentWorker.inject(content, chromeAPI, onEvent); + let result = apiSandbox.ContentWorker.inject(content, chromeAPI, onEvent, options); this._emitToContent = result.emitToContent; this._hasListenerFor = result.hasListenerFor; @@ -166,19 +216,23 @@ const WorkerSandbox = EventEmitter.compose({ // self.postMessage calls this.on("message", function postMessage(data) { - self._addonWorker._emit('message', data); + // destroyed? + if (self._addonWorker) + self._addonWorker._emit('message', data); }); // self.port.emit calls this.on("event", function portEmit(name, args) { - self._addonWorker._onContentScriptEvent.apply(self._addonWorker, arguments); + // destroyed? + if (self._addonWorker) + self._addonWorker._onContentScriptEvent.apply(self._addonWorker, arguments); }); // Internal feature that is only used by SDK tests: // Expose unlock key to content script context. // See `PRIVATE_KEY` definition for more information. - if (apiSanbox && worker._expose_key) - content.UNWRAP_ACCESS_KEY = apiSanbox.UNWRAP_ACCESS_KEY; + if (apiSandbox && worker._expose_key) + content.UNWRAP_ACCESS_KEY = apiSandbox.UNWRAP_ACCESS_KEY; // Inject `addon` global into target document if document is trusted, // `addon` in document is equivalent to `self` in content script. @@ -210,23 +264,24 @@ const WorkerSandbox = EventEmitter.compose({ } }, destroy: function destroy() { - this.emitSync("destroy"); + this.emitSync("detach"); this._sandbox = null; this._addonWorker = null; + this._wrap = null; }, - + /** * JavaScript sandbox where all the content scripts are evaluated. * {Sandbox} */ _sandbox: null, - + /** * Reference to the addon side of the worker. * @type {Worker} */ _addonWorker: null, - + /** * Evaluates code in the sandbox. * @param {String} code @@ -276,7 +331,7 @@ const WorkerSandbox = EventEmitter.compose({ const Worker = EventEmitter.compose({ on: Trait.required, _removeAllListeners: Trait.required, - + /** * Sends a message to the worker's global scope. Method takes single * argument, which represents data to be sent to the worker. The data may @@ -292,19 +347,22 @@ const Worker = EventEmitter.compose({ postMessage: function postMessage(data) { if (!this._contentWorker) throw new Error(ERR_DESTROYED); + if (this._frozen) + throw new Error(ERR_FROZEN); + this._contentWorker.emit("message", data); }, - + /** * EventEmitter, that behaves (calls listeners) asynchronously. * A way to send customized messages to / from the worker. - * Events from in the worker can be observed / emitted via + * Events from in the worker can be observed / emitted via * worker.on / worker.emit. */ get port() { // We generate dynamically this attribute as it needs to be accessible // before Worker.constructor gets called. (For ex: Panel) - + // create an event emitter that receive and send events from/to the worker let self = this; this._port = EventEmitterTrait.create({ @@ -313,35 +371,38 @@ const Worker = EventEmitter.compose({ // expose wrapped port, that exposes only public properties: // We need to destroy this getter in order to be able to set the - // final value. We need to update only public port attribute as we never + // final value. We need to update only public port attribute as we never // try to access port attribute from private API. delete this._public.port; this._public.port = Cortex(this._port); // Replicate public port to the private object delete this.port; this.port = this._public.port; - + return this._port; }, - + /** * Same object than this.port but private API. * Allow access to _emit, in order to send event to port. */ _port: null, - + /** - * Emit a custom event to the content script, + * Emit a custom event to the content script, * i.e. emit this event on `self.port` */ _emitEventToContent: function _emitEventToContent(args) { - // We need to save events that are emitted before the worker is + // We need to save events that are emitted before the worker is // initialized if (!this._inited) { this._earlyEvents.push(args); return; } + if (this._frozen) + throw new Error(ERR_FROZEN); + // We throw exception when the worker has been destroyed if (!this._contentWorker) { throw new Error(ERR_DESTROYED); @@ -350,17 +411,21 @@ const Worker = EventEmitter.compose({ // Forward the event to the WorkerSandbox object this._contentWorker.emit.apply(null, ["event"].concat(args)); }, - + // Is worker connected to the content worker sandbox ? _inited: false, - + + // Is worker being frozen? i.e related document is frozen in bfcache. + // Content script should not be reachable if frozen. + _frozen: true, + // List of custom events fired before worker is initialized get _earlyEvents() { delete this._earlyEvents; this._earlyEvents = []; return this._earlyEvents; }, - + constructor: function Worker(options) { options = options || {}; @@ -368,6 +433,8 @@ const Worker = EventEmitter.compose({ this._window = options.window; if ('contentScriptFile' in options) this.contentScriptFile = options.contentScriptFile; + if ('contentScriptOptions' in options) + this.contentScriptOptions = options.contentScriptOptions; if ('contentScript' in options) this.contentScript = options.contentScript; if ('onError' in options) @@ -383,33 +450,43 @@ const Worker = EventEmitter.compose({ this._expose_key = true; // Track document unload to destroy this worker. - // We can't watch for unload event on page's window object as it - // prevents bfcache from working: + // We can't watch for unload event on page's window object as it + // prevents bfcache from working: // https://developer.mozilla.org/En/Working_with_BFCache this._windowID = this._window. QueryInterface(Ci.nsIInterfaceRequestor). getInterface(Ci.nsIDOMWindowUtils). currentInnerWindowID; - observers.add("inner-window-destroyed", + observers.add("inner-window-destroyed", this._documentUnload = this._documentUnload.bind(this)); - + + // Listen to pagehide event in order to freeze the content script + // while the document is frozen in bfcache: + this._window.addEventListener("pageshow", + this._pageShow = this._pageShow.bind(this), + true); + this._window.addEventListener("pagehide", + this._pageHide = this._pageHide.bind(this), + true); + unload.ensure(this._public, "destroy"); - + // Ensure that worker._port is initialized for contentWorker to be able // to send use event during WorkerSandbox(this) this.port; - + // will set this._contentWorker pointing to the private API: this._contentWorker = WorkerSandbox(this); - + // Mainly enable worker.port.emit to send event to the content worker this._inited = true; + this._frozen = false; // Flush all events that have been fired before the worker is initialized. this._earlyEvents.forEach((function (args) this._emitEventToContent(args)). bind(this)); }, - + _documentUnload: function _documentUnload(subject, topic, data) { let innerWinID = subject.QueryInterface(Ci.nsISupportsPRUint64).data; if (innerWinID != this._windowID) return false; @@ -417,29 +494,39 @@ const Worker = EventEmitter.compose({ return true; }, + _pageShow: function _pageShow() { + this._contentWorker.emitSync("pageshow"); + this._emit("pageshow"); + this._frozen = false; + }, + + _pageHide: function _pageHide() { + this._contentWorker.emitSync("pagehide"); + this._emit("pagehide"); + this._frozen = true; + }, + get url() { // this._window will be null after detach return this._window ? this._window.document.location.href : null; }, - + get tab() { - if (this._window) { - let tab = require("../tabs/tab"); - // this._window will be null after detach - return tab.getTabForWindow(this._window); - } + // this._window will be null after detach + if (this._window) + return getTabForWindow(this._window); return null; }, - + /** - * Tells content worker to unload itself and + * Tells content worker to unload itself and * removes all the references from itself. */ destroy: function destroy() { this._workerCleanup(); this._removeAllListeners(); }, - + /** * Remove all internal references to the attached document * Tells _port to unload itself and removes all the references from itself. @@ -447,9 +534,13 @@ const Worker = EventEmitter.compose({ _workerCleanup: function _workerCleanup() { // maybe unloaded before content side is created // As Symbiont call worker.constructor on document load - if (this._contentWorker) + if (this._contentWorker) this._contentWorker.destroy(); this._contentWorker = null; + if (this._window) { + this._window.removeEventListener("pageshow", this._pageShow, true); + this._window.removeEventListener("pagehide", this._pageHide, true); + } this._window = null; // This method may be called multiple times, // avoid dispatching `detach` event more than once @@ -460,15 +551,15 @@ const Worker = EventEmitter.compose({ this._emit("detach"); } }, - + /** - * Receive an event from the content script that need to be sent to + * Receive an event from the content script that need to be sent to * worker.port. Provide a way for composed object to catch all events. */ _onContentScriptEvent: function _onContentScriptEvent() { this._port._emit.apply(this._port, arguments); }, - + /** * Reference to the content side of the worker. * @type {WorkerGlobalScope} diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/context-menu.js b/tools/addon-sdk-1.12/lib/sdk/context-menu.js index 75ccbea..9d20f0b 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/context-menu.js +++ b/tools/addon-sdk-1.12/lib/sdk/context-menu.js @@ -6,9 +6,13 @@ "use strict"; +module.metadata = { + "stability": "stable" +}; + const {Ci} = require("chrome"); -if (!require("api-utils/xul-app").is("Firefox")) { +if (!require("./system/xul-app").is("Firefox")) { throw new Error([ "The context-menu module currently supports only Firefox. In the future ", "we would like it to support other applications, however. Please see ", @@ -16,19 +20,19 @@ if (!require("api-utils/xul-app").is("Firefox")) { ].join("")); } -const apiUtils = require("api-utils/api-utils"); -const collection = require("api-utils/collection"); -const { Worker } = require("api-utils/content"); -const { URL } = require("api-utils/url"); -const { MatchPattern } = require("api-utils/match-pattern"); -const { EventEmitterTrait: EventEmitter } = require("api-utils/events"); -const observerServ = require("api-utils/observer-service"); -const jpSelf = require("self"); -const winUtils = require("api-utils/window-utils"); -const { getInnerId } = require("api-utils/window/utils"); -const { Trait } = require("api-utils/light-traits"); -const { Cortex } = require("api-utils/cortex"); -const timer = require("timer"); +const apiUtils = require("./deprecated/api-utils"); +const collection = require("./util/collection"); +const { Worker } = require("./content/worker"); +const { URL } = require("./url"); +const { MatchPattern } = require("./page-mod/match-pattern"); +const { EventEmitterTrait: EventEmitter } = require("./deprecated/events"); +const observerServ = require("./deprecated/observer-service"); +const jpSelf = require("./self"); +const { WindowTracker } = require("./deprecated/window-utils"); +const { getInnerId, isBrowser } = require("./window/utils"); +const { Trait } = require("./deprecated/light-traits"); +const { Cortex } = require("./deprecated/cortex"); +const timer = require("./timers"); // All user items we add have this class name. const ITEM_CLASS = "jetpack-context-menu-item"; @@ -708,7 +712,8 @@ WorkerRegistry.prototype = { // Creates a worker for each window that needs a worker but doesn't have one. createNeededWorkers: function WR_createNeededWorkers() { - for (let [innerWinID, win] in Iterator(this.winsWithoutWorkers)) { + for (let innerWinID in this.winsWithoutWorkers) { + let win = this.winsWithoutWorkers[innerWinID] delete this.winsWithoutWorkers[innerWinID]; this.registerContentWin(win); } @@ -716,7 +721,8 @@ WorkerRegistry.prototype = { // Destroys the worker for each window that has a worker but doesn't need it. destroyUnneededWorkers: function WR_destroyUnneededWorkers() { - for (let [innerWinID, winWorker] in Iterator(this.winWorkers)) { + for (let innerWinID in this.winWorkers) { + let winWorker = this.winWorkers[innerWinID]; if (!this._doesURLNeedWorker(winWorker.win.document.URL)) { this.unregisterContentWin(innerWinID); this.winsWithoutWorkers[innerWinID] = winWorker.win; @@ -836,8 +842,8 @@ let browserManager = { // Note that calling this method will cause onTrack to be called immediately // for each currently open browser window. init: function BM_init() { - require("api-utils/unload").ensure(this); - let windowTracker = winUtils.WindowTracker(this); + require("./system/unload").ensure(this); + let windowTracker = WindowTracker(this); // Register content windows on content-document-global-created and // unregister them on inner-window-destroyed. For rationale, see bug 667957 @@ -912,7 +918,7 @@ let browserManager = { // chrome window, and for each chrome window that is open when the loader // loads this module. onTrack: function BM_onTrack(window) { - if (!this._isBrowserWindow(window)) + if (!isBrowser(window)) return; let browserWin = new BrowserWindow(window); @@ -953,7 +959,7 @@ let browserManager = { // chrome window, and for each chrome window that is open when this module is // unloaded. onUntrack: function BM_onUntrack(window) { - if (!this._isBrowserWindow(window)) + if (!isBrowser(window)) return; // Remove the window from the window list. @@ -968,11 +974,6 @@ let browserManager = { // Remove all top-level items from the window. this.topLevelItems.forEach(function (i) browserWin.removeTopLevelItem(i)); browserWin.destroy(); - }, - - _isBrowserWindow: function BM__isBrowserWindow(win) { - let winType = win.document.documentElement.getAttribute("windowtype"); - return winType === "navigator:browser"; } }; @@ -1363,7 +1364,8 @@ ContextMenuPopup.prototype = { let popupNode = this._getPopupNode(); // Show and hide items. Set a "jetpackContextCurrent" property on the // DOM elements to signal which of our items match the current context. - for (let [itemID, item] in Iterator(this.topLevelItems)) { + for (let itemID in this.topLevelItems) { + let item = this.topLevelItems[itemID] let areContextsCurr = this.browserWin.areAllContextsCurrent(item, popupNode); @@ -1470,7 +1472,7 @@ ContextMenuPopup.prototype = { // Returns the OVERFLOW_THRESH_PREF pref value if it exists or // OVERFLOW_THRESH_DEFAULT if it doesn't. get _overflowThreshold() { - let prefs = require("api-utils/preferences-service"); + let prefs = require("./preferences/service"); return prefs.get(OVERFLOW_THRESH_PREF, OVERFLOW_THRESH_DEFAULT); }, diff --git a/tools/addon-sdk-1.12/lib/sdk/core/heritage.js b/tools/addon-sdk-1.12/lib/sdk/core/heritage.js new file mode 100644 index 0000000..1c62e6c --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/core/heritage.js @@ -0,0 +1,146 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +module.metadata = { + "stability": "unstable" +}; + +var getPrototypeOf = Object.getPrototypeOf; +var getNames = Object.getOwnPropertyNames; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var create = Object.create; +var freeze = Object.freeze; +var unbind = Function.call.bind(Function.bind, Function.call); + +// This shortcut makes sure that we do perform desired operations, even if +// associated methods have being overridden on the used object. +var owns = unbind(Object.prototype.hasOwnProperty); +var apply = unbind(Function.prototype.apply); +var slice = Array.slice || unbind(Array.prototype.slice); +var reduce = Array.reduce || unbind(Array.prototype.reduce); +var map = Array.map || unbind(Array.prototype.map); +var concat = Array.concat || unbind(Array.prototype.concat); + +// Utility function to get own properties descriptor map. +function getOwnPropertyDescriptors(object) { + return reduce(getNames(object), function(descriptor, name) { + descriptor[name] = getOwnPropertyDescriptor(object, name); + return descriptor; + }, {}); +} + +/** + * Takes `source` object as an argument and returns identical object + * with the difference that all own properties will be non-enumerable + */ +function obscure(source) { + var descriptor = reduce(getNames(source), function(descriptor, name) { + var property = getOwnPropertyDescriptor(source, name); + property.enumerable = false; + descriptor[name] = property; + return descriptor; + }, {}); + return create(getPrototypeOf(source), descriptor); +} +exports.obscure = obscure; + +/** + * Takes arbitrary number of source objects and returns fresh one, that + * inherits from the same prototype as a first argument and implements all + * own properties of all argument objects. If two or more argument objects + * have own properties with the same name, the property is overridden, with + * precedence from right to left, implying, that properties of the object on + * the left are overridden by a same named property of the object on the right. + */ +var mix = function(source) { + var descriptor = reduce(slice(arguments), function(descriptor, source) { + return reduce(getNames(source), function(descriptor, name) { + descriptor[name] = getOwnPropertyDescriptor(source, name); + return descriptor; + }, descriptor); + }, {}); + + return create(getPrototypeOf(source), descriptor); +}; +exports.mix = mix; + +/** + * Returns a frozen object with that inherits from the given `prototype` and + * implements all own properties of the given `properties` object. + */ +function extend(prototype, properties) { + return freeze(create(prototype, getOwnPropertyDescriptors(properties))); +} +exports.extend = extend; + +/** + * Returns a constructor function with a proper `prototype` setup. Returned + * constructor's `prototype` inherits from a given `options.extends` or + * `Class.prototype` if omitted and implements all the properties of the + * given `option`. If `options.implemens` array is passed, it's elements + * will be mixed into prototype as well. Also, `options.extends` can be + * a function or a prototype. If function than it's prototype is used as + * an ancestor of the prototype, if it's an object that it's used directly. + * Also `options.implements` may contain functions or objects, in case of + * functions their prototypes are used for mixing. + */ +var Class = new function() { + function prototypeOf(input) { + return typeof(input) === 'function' ? input.prototype : input; + } + var none = freeze([]); + + return function Class(options) { + // Create descriptor with normalized `options.extends` and + // `options.implements`. + var descriptor = { + // Normalize extends property of `options.extends` to a prototype object + // in case it's constructor. If property is missing that fallback to + // `Type.prototype`. + extends: owns(options, 'extends') ? + prototypeOf(options.extends) : Class.prototype, + // Normalize `options.implements` to make sure that it's array of + // prototype objects instead of constructor functions. + implements: owns(options, 'implements') ? + freeze(map(options.implements, prototypeOf)) : none + }; + + // Create array of property descriptors who's properties will be defined + // on the resulting prototype. Note: Using reflection `concat` instead of + // method as it may be overridden. + var descriptors = concat(descriptor.implements, options, descriptor); + // Create `prototype` that inherits from given ancestor passed as + // `options.extends`, falling back to `Type.prototype`, implementing all + // properties of given `options.implements` and `options` itself. + var prototype = extend(descriptor.extends, mix.apply(mix, descriptors)); + + // Note: we use reflection `apply` in the constructor instead of method + // call since later may be overridden. + function constructor() { + return apply(prototype.constructor, create(prototype), arguments); + } + constructor.prototype = prototype; + return freeze(constructor); + }; +} +Class.prototype = extend(null, obscure({ + constructor: function constructor() { + this.initialize.apply(this, arguments); + return this; + }, + initialize: function initialize() { + // Do your initialization logic here + }, + // Copy useful properties from `Object.prototype`. + toString: Object.prototype.toString, + toLocaleString: Object.prototype.toLocaleString, + toSource: Object.prototype.toSource, + valueOf: Object.prototype.valueOf, + isPrototypeOf: Object.prototype.isPrototypeOf +})); +exports.Class = freeze(Class); diff --git a/tools/addon-sdk-1.12/lib/sdk/core/namespace.js b/tools/addon-sdk-1.12/lib/sdk/core/namespace.js new file mode 100644 index 0000000..3ceb73b --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/core/namespace.js @@ -0,0 +1,43 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "unstable" +}; + +const create = Object.create; +const prototypeOf = Object.getPrototypeOf; + +/** + * Returns a new namespace, function that may can be used to access an + * namespaced object of the argument argument. Namespaced object are associated + * with owner objects via weak references. Namespaced objects inherit from the + * owners ancestor namespaced object. If owner's ancestor is `null` then + * namespaced object inherits from given `prototype`. Namespaces can be used + * to define internal APIs that can be shared via enclosing `namespace` + * function. + * @examples + * const internals = ns(); + * internals(object).secret = secret; + */ +function ns() { + const map = new WeakMap(); + return function namespace(target) { + if (!target) // If `target` is not an object return `target` itself. + return target; + // If target has no namespaced object yet, create one that inherits from + // the target prototype's namespaced object. + if (!map.has(target)) + map.set(target, create(namespace(prototypeOf(target) || null))); + + return map.get(target); + }; +}; + +// `Namespace` is a e4x function in the scope, so we export the function also as +// `ns` as alias to avoid clashing. +exports.ns = ns; +exports.Namespace = ns; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/promise.js b/tools/addon-sdk-1.12/lib/sdk/core/promise.js index 7c8d7a5..2506c80 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/promise.js +++ b/tools/addon-sdk-1.12/lib/sdk/core/promise.js @@ -1,22 +1,33 @@ /* vim:set ts=2 sw=2 sts=2 expandtab */ -/*jshint asi: true undef: true es5: true node: true devel: true - forin: true latedef: false supernew: true */ -/*global define: true */ -!function(factory) { +/*jshint asi: true undef: true es5: true node: true browser: true devel: true + forin: true latedef: false */ +/*global define: true, Cu: true, __URI__: true */ +;(function(id, factory) { // Module boilerplate :( if (typeof(define) === 'function') { // RequireJS - define(factory) - } else if (typeof(exports) === 'object') { // CommonJS - factory(require, exports) + define(factory); + } else if (typeof(require) === 'function') { // CommonJS + factory.call(this, require, exports, module); } else if (~String(this).indexOf('BackstagePass')) { // JSM - factory(undefined, this) - this.EXPORTED_SYMBOLS = Object.keys(this) - } else { - factory(undefined, (this.promise = {})) + factory(function require(uri) { + var imports = {}; + this['Components'].utils.import(uri, imports); + return imports; + }, this, { uri: __URI__, id: id }); + this.EXPORTED_SYMBOLS = Object.keys(this); + } else { // Browser or alike + var globals = this + factory(function require(id) { + return globals[id]; + }, (globals[id] = {}), { uri: document.location.href + '#' + id, id: id }); } -}.call(this, function(require, exports) { +}).call(this, 'loader', function(require, exports, module) { 'use strict'; +module.metadata = { + "stability": "unstable" +}; + function resolution(value) { /** Returns non-standard compliant (`then` does not returns a promise) promise @@ -186,7 +197,7 @@ var promised = (function() { function promisedConcat(promises, unknown) { return promises.then(function(values) { return resolve(unknown).then(function(value) { - return values.concat(value) + return values.concat([ value ]) }) }) } diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/api-utils.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/api-utils.js index 94d13b7..521ad6e 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/api-utils.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/api-utils.js @@ -6,7 +6,11 @@ "use strict"; -const memory = require("api-utils/memory"); +module.metadata = { + "stability": "deprecated" +}; + +const memory = require("./memory"); // The possible return values of getTypeOf. const VALID_TYPES = [ "array", @@ -82,7 +86,8 @@ exports.validateOptions = function validateOptions(options, requirements) { let validatedOptions = {}; let mapThrew = false; - for (let [key, req] in Iterator(requirements)) { + for (let key in requirements) { + let req = requirements[key]; let [optsVal, keyInOpts] = (key in options) ? [options[key], true] : [undefined, false]; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/app-strings.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/app-strings.js index c03ae7c..e09f79e 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/app-strings.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/app-strings.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + const {Cc,Ci} = require("chrome"); const apiUtils = require("./api-utils"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/cortex.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/cortex.js index 1c3a1b3..8eef91c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/cortex.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/cortex.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + // `var` is being used in the module in order to make it reusable in // environments in which `let` and `const` is not yet supported. diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/errors.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/errors.js index 7029158..b640d05 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/errors.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/errors.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + function logToConsole(e) { console.exception(e); } diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/events.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/events.js index 531a7a3..0c28a1a 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/events.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/events.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + const ERROR_TYPE = 'error', UNCAUGHT_ERROR = 'An error event was dispatched for which there was' + ' no listener.', diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/events/assembler.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/events/assembler.js index 5d11be2..fcde1e3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/events/assembler.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/events/assembler.js @@ -6,7 +6,7 @@ "use strict"; const { Trait } = require("../light-traits"); -const { removeListener, on } = require("../dom/events"); +const { removeListener, on } = require("../../dom/events"); /** * Trait may be used for building objects / composing traits that wish to handle diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/light-traits.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/light-traits.js index 954d093..b18dccb 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/light-traits.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/light-traits.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + // `var` is being used in the module in order to make it reusable in // environments in which `let` is not yet supported. diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/list.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/list.js index 4c6c126..5de69e7 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/list.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/list.js @@ -3,7 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Trait } = require('./traits'); +module.metadata = { + "stability": "experimental" +}; + +const { Trait } = require('../deprecated/traits'); /** * @see https://jetpack.mozillalabs.com/sdk/latest/docs/#module/api-utils/list diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/memory.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/memory.js index be84969..70bcffc 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/memory.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/memory.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + const {Cc,Ci,Cu,components} = require("chrome"); var trackedObjects = {}; @@ -104,7 +108,7 @@ var gc = exports.gc = function gc() { test_utils.garbageCollect(); }; -require("./unload").when( +require("../system/unload").when( function() { trackedObjects = {}; if (timer) { diff --git a/tools/addon-sdk-1.12/lib/sdk/deprecated/observer-service.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/observer-service.js new file mode 100644 index 0000000..6a25109 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/observer-service.js @@ -0,0 +1,134 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "deprecated" +}; + +const { Cc, Ci } = require("chrome"); +const { when: unload } = require("../system/unload"); +const { ns } = require("../core/namespace"); +const { on, off, emit, once } = require("../system/events"); +const { id } = require("../self"); + +const subscribers = ns(); +const cache = []; + +/** + * Topics specifically available to Jetpack-generated extensions. + * + * Using these predefined consts instead of the platform strings is good: + * - allows us to scope topics specifically for Jetpacks + * - addons aren't dependent on strings nor behavior of core platform topics + * - the core platform topics are not clearly named + * + */ +exports.topics = { + /** + * A topic indicating that the application is in a state usable + * by add-ons. + */ + APPLICATION_READY: id + "_APPLICATION_READY" +}; + +function Listener(callback, target) { + return function listener({ subject, data }) { + callback.call(target || callback, subject, data); + } +} + +/** + * Register the given callback as an observer of the given topic. + * + * @param topic {String} + * the topic to observe + * + * @param callback {Object} + * the callback; an Object that implements nsIObserver or a Function + * that gets called when the notification occurs + * + * @param target {Object} [optional] + * the object to use as |this| when calling a Function callback + * + * @returns the observer + */ +function add(topic, callback, target) { + let listeners = subscribers(callback); + if (!(topic in listeners)) { + let listener = Listener(callback, target); + listeners[topic] = listener; + + // Cache callback unless it's already cached. + if (!~cache.indexOf(callback)) + cache.push(callback); + + on(topic, listener); + } +}; +exports.add = add; + +/** + * Unregister the given callback as an observer of the given topic. + * + * @param topic {String} + * the topic being observed + * + * @param callback {Object} + * the callback doing the observing + * + * @param target {Object} [optional] + * the object being used as |this| when calling a Function callback + */ +function remove(topic, callback, target) { + let listeners = subscribers(callback); + if (topic in listeners) { + let listener = listeners[topic]; + delete listeners[topic]; + + // If no more observers are registered and callback is still in cache + // then remove it. + let index = cache.indexOf(callback); + if (~index && !Object.keys(listeners).length) + cache.splice(index, 1) + + off(topic, listener); + } +}; +exports.remove = remove; + +/** + * Notify observers about something. + * + * @param topic {String} + * the topic to notify observers about + * + * @param subject {Object} [optional] + * some information about the topic; can be any JS object or primitive + * + * @param data {String} [optional] [deprecated] + * some more information about the topic; deprecated as the subject + * is sufficient to pass all needed information to the JS observers + * that this module targets; if you have multiple values to pass to + * the observer, wrap them in an object and pass them via the subject + * parameter (i.e.: { foo: 1, bar: "some string", baz: myObject }) + */ +function notify(topic, subject, data) { + emit(topic, { + subject: subject === undefined ? null : subject, + data: data === undefined ? null : data + }); +} +exports.notify = notify; + +unload(function() { + // Make a copy of cache first, since cache will be changing as we + // iterate through it. + cache.slice().forEach(function(callback) { + Object.keys(subscribers(callback)).forEach(function(topic) { + remove(topic, callback); + }); + }); +}) diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/tab-browser.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/tab-browser.js index 13d365a..068471c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/tab-browser.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/tab-browser.js @@ -1,16 +1,22 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -"use strict"; -const {Cc,Ci,Cu} = require("chrome"); +module.metadata = { + 'stability': 'deprecated' +}; + +const {Cc,Ci,Cu} = require('chrome'); var NetUtil = {}; -Cu.import("resource://gre/modules/NetUtil.jsm", NetUtil); +Cu.import('resource://gre/modules/NetUtil.jsm', NetUtil); NetUtil = NetUtil.NetUtil; -const errors = require("./errors"); -const windowUtils = require("./window-utils"); -const apiUtils = require("./api-utils"); -const collection = require("./collection"); +const errors = require('./errors'); +const windowUtils = require('./window-utils'); +const apiUtils = require('./api-utils'); +const collection = require('../util/collection'); +const { getMostRecentBrowserWindow } = require('../window/utils'); +const { getSelectedTab } = require('../tabs/utils'); // TODO: The hard-coding of app-specific info here isn't very nice; // ideally such app-specific info should be more decoupled, and the @@ -18,7 +24,7 @@ const collection = require("./collection"); // runtime, perhaps by inspecting supported packages (e.g. via // dynamically-named modules or package-defined extension points). -if (!require("./xul-app").is("Firefox")) { +if (!require("../system/xul-app").is("Firefox")) { throw new Error([ "The tab-browser module currently supports only Firefox. In the future ", "it will support other applications. Please see ", @@ -30,7 +36,7 @@ function onBrowserLoad(callback, event) { if (event.target && event.target.defaultView == this) { this.removeEventListener("load", onBrowserLoad, true); try { - require("timer").setTimeout(function () { + require("../timers").setTimeout(function () { callback(event); }, 10); } catch (e) { console.exception(e); } @@ -79,19 +85,18 @@ exports.addTab = function addTab(url, options) { } }); - var wm = Cc["@mozilla.org/appshell/window-mediator;1"] - .getService(Ci.nsIWindowMediator); - var win = wm.getMostRecentWindow("navigator:browser"); + var win = getMostRecentBrowserWindow(); if (!win || options.inNewWindow) { openBrowserWindow(function(e) { if(options.isPinned) { //get the active tab in the recently created window let mainWindow = e.target.defaultView; - mainWindow.gBrowser.pinTab(mainWindow.gBrowser.selectedTab); + mainWindow.gBrowser.pinTab(getSelectedTab(mainWindow)); } require("./errors").catchAndLog(function(e) options.onLoad(e))(e); }, options.url); - } else { + } + else { let tab = win.gBrowser.addTab(options.url); if (!options.inBackground) win.gBrowser.selectedTab = tab; @@ -132,7 +137,7 @@ function Tracker(delegate, window) { this._window = window; this._windowTracker = windowUtils.WindowTracker(this); - require("./unload").ensure(this); + require("../system/unload").ensure(this); } Tracker.prototype = { __iterator__: function __iterator__() { @@ -182,7 +187,7 @@ function TabTracker(delegate, window) { this._delegate = delegate; this._tabs = []; this._tracker = new Tracker(this, window); - require("./unload").ensure(this); + require("../system/unload").ensure(this); } TabTracker.prototype = { _TAB_EVENTS: ["TabOpen", "TabClose"], @@ -260,11 +265,10 @@ exports.whenContentLoaded = function whenContentLoaded(callback) { return tracker; }; -exports.__defineGetter__("activeTab", function() { - const wm = Cc["@mozilla.org/appshell/window-mediator;1"]. - getService(Ci.nsIWindowMediator); - let mainWindow = wm.getMostRecentWindow("navigator:browser"); - return mainWindow.gBrowser.selectedTab; +Object.defineProperty(exports, 'activeTab', { + get: function() { + return getSelectedTab(getMostRecentBrowserWindow()); + } }); /******************* TabModule *********************/ @@ -354,7 +358,7 @@ let TabModule = exports.TabModule = function TabModule(window) { */ this.__defineGetter__("activeTab", function() { try { - return window ? tabConstructor(window.gBrowser.selectedTab) + return window ? tabConstructor(getSelectedTab(window)) : tabConstructor(exports.activeTab); } catch (e) { } @@ -418,7 +422,7 @@ let TabModule = exports.TabModule = function TabModule(window) { this.tabs.splice(0); } }; - require("./unload").ensure(eventsTabDelegate); + require("../system/unload").ensure(eventsTabDelegate); let eventsTabTracker = new ModuleTabTracker({ onTrack: function TETT_onTrack(tab) { @@ -445,7 +449,7 @@ let TabModule = exports.TabModule = function TabModule(window) { eventsTabDelegate.pushTabEvent("onPaint", tab); } }, window); - require("./unload").ensure(eventsTabTracker); + require("../system/unload").ensure(eventsTabTracker); // Iterator for all tabs this.__iterator__ = function tabsIterator() { @@ -460,7 +464,7 @@ let TabModule = exports.TabModule = function TabModule(window) { // Unregister tabs event listeners events.forEach(function(e) self[e] = []); } - require("./unload").ensure(this); + require("../system/unload").ensure(this); } // End of TabModule constructor @@ -536,7 +540,7 @@ function openURLInNewTab(options, window, tabConstructor) { // for subsequent loads in same tab. tabBrowser.removeEventListener("load", onLoad, true); let tab = tabConstructor(tabEl); - require("./timer").setTimeout(function() { + require("../timers").setTimeout(function() { require("./errors").catchAndLog(function(tab) options.onOpen(tab))(tab); }, 10); }, true); @@ -565,7 +569,7 @@ function ModuleTabTracker(delegate, window) { this._delegate = delegate; this._tabs = []; this._tracker = new Tracker(this, window); - require("./unload").ensure(this); + require("../system/unload").ensure(this); } ModuleTabTracker.prototype = { _TAB_EVENTS: ["TabOpen", "TabClose", "TabSelect", "DOMContentLoaded", diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/traits.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/traits.js index 7c1c4ec..30ae342 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/traits.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/traits.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "deprecated" +}; + const { compose: _compose, override: _override, diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/traits/core.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/traits/core.js index 6e802c7..c08c38f 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/traits/core.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/traits/core.js @@ -3,6 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; + +module.metadata = { + "stability": "deprecated" +}; + // Design inspired by: http://www.traitsjs.org/ // shortcuts diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/unit-test-finder.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test-finder.js index 993749b..880f554 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/unit-test-finder.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test-finder.js @@ -4,10 +4,13 @@ "use strict"; -const file = require("./file"); -const packaging = require('@packaging'); -const memory = require('api-utils/memory'); -const suites = packaging.allTestModules; +module.metadata = { + "stability": "deprecated" +}; + +const file = require("../io/file"); +const memory = require('./memory'); +const suites = require('@test/options').allTestModules; const NOT_TESTS = ['setup', 'teardown']; @@ -20,14 +23,6 @@ var TestFinder = exports.TestFinder = function TestFinder(options) { }; TestFinder.prototype = { - _makeTest: function _makeTest(suite, name, test) { - function runTest(runner) { - console.info("executing '" + suite + "." + name + "'"); - test(runner); - } - return runTest; - }, - findTests: function findTests(cb) { var self = this; var tests = []; @@ -64,7 +59,7 @@ TestFinder.prototype = { tests.push({ setup: module.setup, teardown: module.teardown, - testFunction: self._makeTest(suite, name, module[name]), + testFunction: module[name], name: suite + "." + name }); } diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/unit-test.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test.js index 4018487..6a8ac1b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/unit-test.js +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/unit-test.js @@ -5,8 +5,12 @@ "use strict"; -const memory = require('api-utils/memory'); -var timer = require("./timer"); +module.metadata = { + "stability": "deprecated" +}; + +const memory = require('./memory'); +var timer = require("../timers"); exports.findAndRunTests = function findAndRunTests(options) { var TestFinder = require("./unit-test-finder").TestFinder; @@ -43,6 +47,8 @@ TestRunner.prototype = { PAUSE_DELAY: 500, _logTestFailed: function _logTestFailed(why) { + if (!(why in this.test.errors)) + this.test.errors[why] = 0; this.test.errors[why]++; if (!this.testFailureLogged) { this.console.error("TEST FAILED: " + this.test.name + " (" + why + ")"); @@ -239,6 +245,8 @@ TestRunner.prototype = { timer.clearTimeout(this.waitTimeout); this.waitTimeout = null; } + // Do not leave any callback set when calling to `waitUntil` + this.waitUntilCallback = null; if (this.test.passed == 0 && this.test.failed == 0) { this._logTestFailed("empty test"); this.failed++; @@ -303,7 +311,7 @@ TestRunner.prototype = { let test = this; // capture a traceback before we go async. - let traceback = require("./traceback"); + let traceback = require("../console/traceback"); let stack = traceback.get(); stack.splice(-2, 2); let currentWaitStack = traceback.format(stack); @@ -348,7 +356,8 @@ TestRunner.prototype = { a = a(); } catch(e) { - test.fail("Exception when calling asynchronous assertion: " + e); + test.fail("Exception when calling asynchronous assertion: " + e + + "\n" + e.stack); finished = true; return; } @@ -427,6 +436,8 @@ TestRunner.prototype = { this.testFailureLogged = false; try { + this.console.info("executing '" + this.test.name + "'"); + if(this.test.setup) { this.test.setup(this); } diff --git a/tools/addon-sdk-1.12/lib/sdk/deprecated/window-utils.js b/tools/addon-sdk-1.12/lib/sdk/deprecated/window-utils.js new file mode 100644 index 0000000..66fcfba --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/deprecated/window-utils.js @@ -0,0 +1,201 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'deprecated' +}; + +const { Cc, Ci } = require('chrome'); +const { EventEmitter } = require('../deprecated/events'); +const { Trait } = require('../deprecated/traits'); +const { when } = require('../system/unload'); +const { getInnerId, getOuterId, windows, isDocumentLoaded, isBrowser, + getMostRecentBrowserWindow } = require('../window/utils'); +const errors = require('../deprecated/errors'); +const { deprecateFunction } = require('../util/deprecate'); + +const windowWatcher = Cc['@mozilla.org/embedcomp/window-watcher;1']. + getService(Ci.nsIWindowWatcher); +const appShellService = Cc['@mozilla.org/appshell/appShellService;1']. + getService(Ci.nsIAppShellService); + +/** + * An iterator for XUL windows currently in the application. + * + * @return A generator that yields XUL windows exposing the + * nsIDOMWindow interface. + */ +function windowIterator() { + // Bug 752631: We only pass already loaded window in order to avoid + // breaking XUL windows DOM. DOM is broken when some JS code try + // to access DOM during "uninitialized" state of the related document. + let list = windows().filter(isDocumentLoaded); + for (let i = 0, l = list.length; i < l; i++) { + yield list[i]; + } +}; +exports.windowIterator = windowIterator; + +/** + * An iterator for browser windows currently open in the application. + * @returns {Function} + * A generator that yields browser windows exposing the `nsIDOMWindow` + * interface. + */ +function browserWindowIterator() { + for each (let window in windowIterator()) { + if (isBrowser(window)) + yield window; + } +} +exports.browserWindowIterator = browserWindowIterator; + +function WindowTracker(delegate) { + if (!(this instanceof WindowTracker)) { + return new WindowTracker(delegate); + } + + this._delegate = delegate; + this._loadingWindows = []; + + for each (let window in windows()) + this._regWindow(window); + windowWatcher.registerNotification(this); + + require('../system/unload').ensure(this); + + return this; +}; + +WindowTracker.prototype = { + _regLoadingWindow: function _regLoadingWindow(window) { + this._loadingWindows.push(window); + window.addEventListener('load', this, true); + }, + + _unregLoadingWindow: function _unregLoadingWindow(window) { + var index = this._loadingWindows.indexOf(window); + + if (index != -1) { + this._loadingWindows.splice(index, 1); + window.removeEventListener('load', this, true); + } + }, + + _regWindow: function _regWindow(window) { + if (window.document.readyState == 'complete') { + this._unregLoadingWindow(window); + this._delegate.onTrack(window); + } else + this._regLoadingWindow(window); + }, + + _unregWindow: function _unregWindow(window) { + if (window.document.readyState == 'complete') { + if (this._delegate.onUntrack) + this._delegate.onUntrack(window); + } else { + this._unregLoadingWindow(window); + } + }, + + unload: function unload() { + windowWatcher.unregisterNotification(this); + for each (let window in windows()) + this._unregWindow(window); + }, + + handleEvent: errors.catchAndLog(function handleEvent(event) { + if (event.type == 'load' && event.target) { + var window = event.target.defaultView; + if (window) + this._regWindow(window); + } + }), + + observe: errors.catchAndLog(function observe(subject, topic, data) { + var window = subject.QueryInterface(Ci.nsIDOMWindow); + if (topic == 'domwindowopened') + this._regWindow(window); + else + this._unregWindow(window); + }) +}; +exports.WindowTracker = WindowTracker; + +const WindowTrackerTrait = Trait.compose({ + _onTrack: Trait.required, + _onUntrack: Trait.required, + constructor: function WindowTrackerTrait() { + WindowTracker({ + onTrack: this._onTrack.bind(this), + onUntrack: this._onUntrack.bind(this) + }); + } +}); +exports.WindowTrackerTrait = WindowTrackerTrait; + +var gDocsToClose = []; + +function onDocUnload(event) { + var index = gDocsToClose.indexOf(event.target); + if (index == -1) + throw new Error('internal error: unloading document not found'); + var document = gDocsToClose.splice(index, 1)[0]; + // Just in case, let's remove the event listener too. + document.defaultView.removeEventListener('unload', onDocUnload, false); +} + +onDocUnload = require('./errors').catchAndLog(onDocUnload); + +exports.closeOnUnload = function closeOnUnload(window) { + window.addEventListener('unload', onDocUnload, false); + gDocsToClose.push(window.document); +}; + +Object.defineProperties(exports, { + activeWindow: { + enumerable: true, + get: function() { + return Cc['@mozilla.org/appshell/window-mediator;1'] + .getService(Ci.nsIWindowMediator) + .getMostRecentWindow(null); + }, + set: function(window) { + try { window.focus(); } catch (e) { } + } + }, + activeBrowserWindow: { + enumerable: true, + get: getMostRecentBrowserWindow + } +}); + + +/** + * Returns the ID of the window's current inner window. + */ +exports.getInnerId = deprecateFunction(getInnerId, + 'require("window-utils").getInnerId is deprecated, ' + + 'please use require("window/utils").getInnerId instead' +); + +exports.getOuterId = deprecateFunction(getOuterId, + 'require("window-utils").getOuterId is deprecated, ' + + 'please use require("window/utils").getOuterId instead' +); + +exports.isBrowser = deprecateFunction(isBrowser, + 'require("window-utils").isBrowser is deprecated, ' + + 'please use require("window/utils").isBrowser instead' +); + +exports.hiddenWindow = appShellService.hiddenDOMWindow; + +when( + function() { + gDocsToClose.slice().forEach( + function(doc) { doc.defaultView.close(); }); + }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/dom/events.js b/tools/addon-sdk-1.12/lib/sdk/dom/events.js index 2168f42..3f2d21c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/dom/events.js +++ b/tools/addon-sdk-1.12/lib/sdk/dom/events.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + // Utility function that returns copy of the given `text` with last character // removed if it is `"s"`. function singularify(text) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/dom/events/keys.js b/tools/addon-sdk-1.12/lib/sdk/dom/events/keys.js index 53107ae..01e4a0d 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/dom/events/keys.js +++ b/tools/addon-sdk-1.12/lib/sdk/dom/events/keys.js @@ -5,10 +5,14 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { emit } = require("../events"); const { getCodeForKey, toJSON } = require("../../keyboard/utils"); -const { has } = require("../../array"); -const { isString } = require("../../type"); +const { has } = require("../../util/array"); +const { isString } = require("../../lang/type"); const INITIALIZER = "initKeyEvent"; const CATEGORY = "KeyboardEvent"; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/event/core.js b/tools/addon-sdk-1.12/lib/sdk/event/core.js index ed2a0d4..e63e3b9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/event/core.js +++ b/tools/addon-sdk-1.12/lib/sdk/event/core.js @@ -6,10 +6,14 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const UNCAUGHT_ERROR = 'An error event was emitted for which there was no listener.'; const BAD_LISTENER = 'The event listener must be a function.'; -const { ns } = require('../namespace'); +const { ns } = require('../core/namespace'); const event = ns(); @@ -76,8 +80,9 @@ exports.once = once; * More arguments that will be passed to listeners. */ function emit(target, type, message /*, ...*/) { - for each (let item in emit.lazy.apply(emit.lazy, arguments)) - item; + for each (let item in emit.lazy.apply(emit.lazy, arguments)) { + // We just iterate, iterator take care of emitting events. + } } /** diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/event/target.js b/tools/addon-sdk-1.12/lib/sdk/event/target.js index 60b19d2..b8906c0 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/event/target.js +++ b/tools/addon-sdk-1.12/lib/sdk/event/target.js @@ -6,9 +6,13 @@ 'use strict'; +module.metadata = { + "stability": "stable" +}; + const { on, once, off } = require('./core'); -const { method } = require('../functional'); -const { Base } = require('../base'); +const { method } = require('../lang/functional'); +const { Class } = require('../core/heritage'); const EVENT_TYPE_PATTERN = /^on([A-Z]\w+$)/; @@ -17,7 +21,7 @@ const EVENT_TYPE_PATTERN = /^on([A-Z]\w+$)/; * add / remove event listeners on them. Events on these objects may be emitted * via `emit` function exported by 'event/core' module. */ -const EventTarget = Base.extend({ +const EventTarget = Class({ /** * Method initializes `this` event source. It goes through properties of a * given `options` and registers listeners for the ones that look like an diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/hidden-frame.js b/tools/addon-sdk-1.12/lib/sdk/frame/hidden-frame.js index 6f0016b..1bf51de 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/hidden-frame.js +++ b/tools/addon-sdk-1.12/lib/sdk/frame/hidden-frame.js @@ -6,16 +6,20 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + const {Cc, Ci} = require("chrome"); -const errors = require("./errors"); -const apiUtils = require("./api-utils"); -const timer = require("./timer"); +const errors = require("../deprecated/errors"); +const apiUtils = require("../deprecated/api-utils"); +const timer = require("../timers"); const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; let hostFrame, hostDocument, hiddenWindow, isHostFrameReady = false; -if (!require("./xul-app").isOneOf(["Firefox", "Fennec", "Thunderbird"])) { +if (!require("../system/xul-app").isOneOf(["Firefox", "Fennec", "Thunderbird"])) { throw new Error([ "The hidden-frame module currently supports only Firefox and Thunderbird. ", "In the future, we would like it to support other applications, however. ", @@ -62,8 +66,7 @@ exports.HiddenFrame = apiUtils.publicConstructor(HiddenFrame); function HiddenFrame(options) { options = options || {}; let self = this; - - for each (let [key, val] in Iterator(apiUtils.validateOptions(options, { + let validOptions = apiUtils.validateOptions(options, { onReady: { is: ["undefined", "function", "array"], ok: function(v) { @@ -73,15 +76,23 @@ function HiddenFrame(options) { } return true; } + }, + onUnload: { + is: ["undefined", "function"] } - }))) { + }); + + for (let key in validOptions) { + let val = validOptions[key]; if (typeof(val) != "undefined") options[key] = val; } - require("./collection").addCollectionProperty(this, "onReady"); + require("../util/collection").addCollectionProperty(this, "onReady"); if (options.onReady) this.onReady.add(options.onReady); + if (options.onUnload) + this.onUnload = options.onUnload; if (!hostFrame) { hostFrame = hiddenWindow.document.createElement("iframe"); @@ -130,6 +141,9 @@ exports.add = function JP_SDK_Frame_add(frame) { frame: frame, element: element, unload: function unload() { + // Call before removing to let a chance to avoid "dead object" exception + if (typeof frame.onUnload === "function") + frame.onUnload(); hostDocument.documentElement.removeChild(element); } }); @@ -153,11 +167,12 @@ exports.remove = function remove(frame) { if (!entry) return; - entry.unload(); + // Remove from cache before calling in order to avoid loop cache.splice(cache.indexOf(entry), 1); + entry.unload(); } -require("./unload").when(function () { +require("../system/unload").when(function () { for each (let entry in cache.slice()) exports.remove(entry.frame); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/frame/utils.js b/tools/addon-sdk-1.12/lib/sdk/frame/utils.js index 5c9da38..ad4ca7c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/frame/utils.js +++ b/tools/addon-sdk-1.12/lib/sdk/frame/utils.js @@ -4,6 +4,10 @@ 'use strict'; +module.metadata = { + "stability": "experimental" +}; + const XUL = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; /** diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/hotkeys.js b/tools/addon-sdk-1.12/lib/sdk/hotkeys.js index f864f1f..3491d2c 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/hotkeys.js +++ b/tools/addon-sdk-1.12/lib/sdk/hotkeys.js @@ -5,11 +5,15 @@ "use strict"; +module.metadata = { + "stability": "stable" +}; + const INVALID_HOTKEY = "Hotkey must have at least one modifier."; const { toJSON: jsonify, toString: stringify, - isFunctionKey } = require("api-utils/keyboard/utils"); -const { register, unregister } = require("api-utils/keyboard/hotkeys"); + isFunctionKey } = require("./keyboard/utils"); +const { register, unregister } = require("./keyboard/hotkeys"); const Hotkey = exports.Hotkey = function Hotkey(options) { if (!(this instanceof Hotkey)) diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/byte-streams.js b/tools/addon-sdk-1.12/lib/sdk/io/byte-streams.js index edc8407..27b1802 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/byte-streams.js +++ b/tools/addon-sdk-1.12/lib/sdk/io/byte-streams.js @@ -6,6 +6,10 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + exports.ByteReader = ByteReader; exports.ByteWriter = ByteWriter; @@ -87,7 +91,7 @@ function StreamManager(stream, rawStream) { self.unload(); }; - require("./unload").ensure(this); + require("../system/unload").ensure(this); } StreamManager.prototype = { diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/data.js b/tools/addon-sdk-1.12/lib/sdk/io/data.js index 33356cd..9dd7246 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/data.js +++ b/tools/addon-sdk-1.12/lib/sdk/io/data.js @@ -4,15 +4,20 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci, Cu } = require("chrome"); +const base64 = require("../base64"); + const IOService = Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService); -const AppShellService = Cc["@mozilla.org/appshell/appShellService;1"]. - getService(Ci.nsIAppShellService); const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm"); const FaviconService = Cc["@mozilla.org/browser/favicon-service;1"]. getService(Ci.nsIFaviconService); +const { deprecateFunction, deprecatedUsage } = require("../util/deprecate"); const PNG_B64 = "data:image/png;base64,"; const DEF_FAVICON_URI = "chrome://mozapps/skin/places/defaultFavicon.png"; @@ -34,7 +39,7 @@ exports.getFaviconURIForLocation = function getFaviconURIForLocation(uri) { catch(e) { if (!DEF_FAVICON) { DEF_FAVICON = PNG_B64 + - base64Encode(getChromeURIContent(DEF_FAVICON_URI)); + base64.encode(getChromeURIContent(DEF_FAVICON_URI)); } return DEF_FAVICON; } @@ -49,23 +54,31 @@ function getChromeURIContent(chromeURI) { let channel = IOService.newChannel(chromeURI, null, null); let input = channel.open(); let stream = Cc["@mozilla.org/binaryinputstream;1"]. - createInstance(Ci.nsIBinaryInputStream); + createInstance(Ci.nsIBinaryInputStream); stream.setInputStream(input); let content = stream.readBytes(input.available()); stream.close(); input.close(); return content; } -exports.getChromeURIContent = getChromeURIContent; +exports.getChromeURIContent = function deprecated_getChromeURIContent() { + deprecatedUsage( + 'getChromeURIContent is deprecated, ' + + 'please use require("sdk/net/url").readURI instead.' + ); +}; /** * Creates a base-64 encoded ASCII string from a string of binary data. */ -function base64Encode(data) AppShellService.hiddenDOMWindow.btoa(String(data)); -exports.base64Encode = base64Encode; - +exports.base64Encode = deprecateFunction(base64.encode, + 'base64Encode is deprecated, ' + + 'please use require("sdk/base64").encode instead.' +); /** * Decodes a string of data which has been encoded using base-64 encoding. */ -function base64Decode(data) AppShellService.hiddenDOMWindow.atob(String(data)); -exports.base64Decode = base64Decode; +exports.base64Decode = deprecateFunction(base64.decode, + 'base64Dencode is deprecated, ' + + 'please use require("sdk/base64").decode instead.' +); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/file.js b/tools/addon-sdk-1.12/lib/sdk/io/file.js index 0b4eac9..735edea 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/file.js +++ b/tools/addon-sdk-1.12/lib/sdk/io/file.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + const {Cc,Ci,Cr} = require("chrome"); const byteStreams = require("./byte-streams"); const textStreams = require("./text-streams"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/text-streams.js b/tools/addon-sdk-1.12/lib/sdk/io/text-streams.js index 96217eb..0aa469d 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/text-streams.js +++ b/tools/addon-sdk-1.12/lib/sdk/io/text-streams.js @@ -6,6 +6,10 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + const {Cc,Ci,Cu,components} = require("chrome"); var NetUtil = {}; Cu.import("resource://gre/modules/NetUtil.jsm", NetUtil); @@ -214,7 +218,7 @@ function StreamManager(stream, rawStream) { self.unload(); }; - require("./unload").ensure(this); + require("../system/unload").ensure(this); } StreamManager.prototype = { diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/hotkeys.js b/tools/addon-sdk-1.12/lib/sdk/keyboard/hotkeys.js index bb296ed..2d963ab 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/hotkeys.js +++ b/tools/addon-sdk-1.12/lib/sdk/keyboard/hotkeys.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { observer: keyboardObserver } = require("./observer"); const { getKeyForCode, normalize, isFunctionKey, MODIFIERS } = require("./utils"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/observer.js b/tools/addon-sdk-1.12/lib/sdk/keyboard/observer.js index dd24865..26c0a83 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/observer.js +++ b/tools/addon-sdk-1.12/lib/sdk/keyboard/observer.js @@ -5,10 +5,15 @@ "use strict"; -const { Trait } = require("../light-traits"); -const { EventEmitterTrait: EventEmitter } = require("../events"); -const { DOMEventAssembler } = require("../events/assembler"); -const { browserWindowIterator, isBrowser } = require('../window-utils'); +module.metadata = { + "stability": "unstable" +}; + +const { Trait } = require("../deprecated/light-traits"); +const { EventEmitterTrait: EventEmitter } = require("../deprecated/events"); +const { DOMEventAssembler } = require("../deprecated/events/assembler"); +const { browserWindowIterator } = require('../deprecated/window-utils'); +const { isBrowser } = require('../window/utils'); const { observer: windowObserver } = require("../windows/observer"); // Event emitter objects used to register listeners and emit events on them diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/utils.js b/tools/addon-sdk-1.12/lib/sdk/keyboard/utils.js index 4693a12..a4a8f76 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/keyboard/utils.js +++ b/tools/addon-sdk-1.12/lib/sdk/keyboard/utils.js @@ -5,10 +5,14 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci } = require("chrome"); -const runtime = require("../runtime"); -const { isString } = require("../type"); -const array = require("../array"); +const runtime = require("../system/runtime"); +const { isString } = require("../lang/type"); +const array = require("../util/array"); const SWP = "{{SEPARATOR}}"; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/l10n.js b/tools/addon-sdk-1.12/lib/sdk/l10n.js index 198f711..40f219c 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/l10n.js +++ b/tools/addon-sdk-1.12/lib/sdk/l10n.js @@ -3,25 +3,25 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Cc, Ci } = require("chrome"); -const { getPreferedLocales, findClosestLocale } = require("api-utils/l10n/locale"); -const { getRulesForLocale } = require("api-utils/l10n/plural-rules"); +module.metadata = { + "stability": "stable" +}; -// Get URI for the addon root folder: -const { rootURI } = require("@packaging"); +const core = require("./l10n/core"); +const { getRulesForLocale } = require("./l10n/plural-rules"); -let globalHash = {}; -let pluralMappingFunction = getRulesForLocale("en"); +// Retrieve the plural mapping function +let pluralMappingFunction = getRulesForLocale(core.language()) || + getRulesForLocale("en"); exports.get = function get(k) { - // For now, we only accept a "string" as first argument // TODO: handle plural forms in gettext pattern if (typeof k !== "string") throw new Error("First argument of localization method should be a string"); // Get translation from big hashmap or default to hard coded string: - let localized = globalHash[k] || k; + let localized = core.get(k) || k; // # Simplest usecase: // // String hard coded in source code: @@ -81,69 +81,3 @@ exports.get = function get(k) { return localized; } - -function readURI(uri) { - let request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]. - createInstance(Ci.nsIXMLHttpRequest); - request.open('GET', uri, false); - request.overrideMimeType('text/plain'); - request.send(); - return request.responseText; -} - -function readJsonUri(uri) { - try { - return JSON.parse(readURI(uri)); - } - catch(e) { - console.error("Error while reading locale file:\n" + uri + "\n" + e); - } - return {}; -} - -// Returns the array stored in `locales.json` manifest that list available -// locales files -function getAvailableLocales() { - let uri = rootURI + "locales.json"; - let manifest = readJsonUri(uri); - - return "locales" in manifest && Array.isArray(manifest.locales) ? - manifest.locales : []; -} - -// Returns URI of the best locales file to use from the XPI -function getBestLocaleFile() { - - // Read localization manifest file that contains list of available languages - let availableLocales = getAvailableLocales(); - - // Retrieve list of prefered locales to use - let preferedLocales = getPreferedLocales(); - - // Compute the most preferable locale to use by using these two lists - let bestMatchingLocale = findClosestLocale(availableLocales, preferedLocales); - - // It may be null if the addon doesn't have any locale file - if (!bestMatchingLocale) - return null; - - // Retrieve the related plural mapping function - let shortLocaleCode = bestMatchingLocale.split("-")[0].toLowerCase(); - pluralMappingFunction = getRulesForLocale(shortLocaleCode); - - return rootURI + "locale/" + bestMatchingLocale + ".json"; -} - -function init() { - // First, search for a locale file: - let localeURI = getBestLocaleFile(); - if (!localeURI) - return; - - // Locale files only contains one big JSON object that is used as - // an hashtable of: "key to translate" => "translated key" - // TODO: We are likely to change this in order to be able to overload - // a specific key translation. For a specific package, module or line? - globalHash = readJsonUri(localeURI); -} -init(); diff --git a/tools/addon-sdk-1.12/lib/sdk/l10n/core.js b/tools/addon-sdk-1.12/lib/sdk/l10n/core.js new file mode 100644 index 0000000..50472e9 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/core.js @@ -0,0 +1,35 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Following pseudo module is set by `api-utils/addon/runner` and its load +// method needs to be called before loading `core` module. But it may have +// failed, so that this pseudo won't be available + +module.metadata = { + "stability": "unstable" +}; + + +let hash = {}, bestMatchingLocale = null; +try { + let data = require("@l10n/data"); + hash = data.hash; + bestMatchingLocale = data.bestMatchingLocale; +} +catch(e) {} + +// Returns the translation for a given key, if available. +exports.get = function get(k) { + return k in hash ? hash[k] : null; +} + +// Returns the full length locale code: ja-JP-mac, en-US or fr +exports.locale = function locale() { + return bestMatchingLocale; +} +// Returns the short locale code: ja, en, fr +exports.language = function language() { + return bestMatchingLocale ? bestMatchingLocale.split("-")[0].toLowerCase() + : null; +} diff --git a/tools/addon-sdk-1.12/lib/sdk/l10n/html.js b/tools/addon-sdk-1.12/lib/sdk/l10n/html.js new file mode 100644 index 0000000..1a36415 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/html.js @@ -0,0 +1,93 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +module.metadata = { + "stability": "unstable" +}; + +const { Ci } = require("chrome"); +const events = require("../system/events"); +const core = require("./core"); + +const assetsURI = require('../self').data.url(); + +// Taken from Gaia: +// https://github.com/andreasgal/gaia/blob/04fde2640a7f40314643016a5a6c98bf3755f5fd/webapi.js#L1470 +function translateElement(element) { + element = element || document; + + // check all translatable children (= w/ a `data-l10n-id' attribute) + var children = element.querySelectorAll('*[data-l10n-id]'); + var elementCount = children.length; + for (var i = 0; i < elementCount; i++) { + var child = children[i]; + + // translate the child + var key = child.dataset.l10nId; + var data = core.get(key); + if (data) + child.textContent = data; + } +} +exports.translateElement = translateElement; + +function onDocumentReady2Translate(event) { + let document = event.target; + document.removeEventListener("DOMContentLoaded", onDocumentReady2Translate, + false); + + translateElement(document); + + // Finally display document when we finished replacing all text content + document.documentElement.style.visibility = "visible"; +} + +function onContentWindow(event) { + let document = event.subject; + + // Accept only HTML documents + if (!(document instanceof Ci.nsIDOMHTMLDocument)) + return; + + // Bug 769483: data:URI documents instanciated with nsIDOMParser + // have a null `location` attribute at this time + if (!document.location) + return; + + // Accept only document from this addon + if (document.location.href.indexOf(assetsURI) !== 0) + return; + + // First hide content of the document in order to have content blinking + // between untranslated and translated states + // TODO: use result of bug 737003 discussion in order to avoid any conflict + // with document CSS + document.documentElement.style.visibility = "hidden"; + + // Wait for DOM tree to be built before applying localization + document.addEventListener("DOMContentLoaded", onDocumentReady2Translate, + false); +} + +// Listen to creation of content documents in order to translate them as soon +// as possible in their loading process +const ON_CONTENT = "document-element-inserted"; +let enabled = false; +function enable() { + if (!enabled) { + events.on(ON_CONTENT, onContentWindow); + enabled = true; + } +} +exports.enable = enable; + +function disable() { + if (enabled) { + events.off(ON_CONTENT, onContentWindow); + enabled = false; + } +} +exports.disable = disable; + +require("api-utils/unload").when(disable); diff --git a/tools/addon-sdk-1.12/lib/sdk/l10n/loader.js b/tools/addon-sdk-1.12/lib/sdk/l10n/loader.js new file mode 100644 index 0000000..9af6c5c --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/loader.js @@ -0,0 +1,71 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci } = require("chrome"); +const { getPreferedLocales, findClosestLocale } = require("./locale"); +const { readURI } = require("../net/url"); +const { resolve } = require("../core/promise"); + +function parseJsonURI(uri) { + return readURI(uri). + then(JSON.parse). + then(null, function (error) { + throw Error("Failed to parse locale file:\n" + uri + "\n" + error); + }); +} + +// Returns the array stored in `locales.json` manifest that list available +// locales files +function getAvailableLocales(rootURI) { + let uri = rootURI + "locales.json"; + return parseJsonURI(uri).then(function (manifest) { + return "locales" in manifest && + Array.isArray(manifest.locales) ? + manifest.locales : []; + }); +} + +// Returns URI of the best locales file to use from the XPI +function getBestLocale(rootURI) { + // Read localization manifest file that contains list of available languages + return getAvailableLocales(rootURI).then(function (availableLocales) { + // Retrieve list of prefered locales to use + let preferedLocales = getPreferedLocales(); + + // Compute the most preferable locale to use by using these two lists + return findClosestLocale(availableLocales, preferedLocales); + }); +} + +/** + * Read localization files and returns a promise of data to put in `@l10n/data` + * pseudo module, in order to allow l10n/core to fetch it. + */ +exports.load = function load(rootURI) { + // First, search for a locale file: + return getBestLocale(rootURI).then(function (bestMatchingLocale) { + // It may be null if the addon doesn't have any locale file + if (!bestMatchingLocale) + return resolve(null); + + let localeURI = rootURI + "locale/" + bestMatchingLocale + ".json"; + + // Locale files only contains one big JSON object that is used as + // an hashtable of: "key to translate" => "translated key" + // TODO: We are likely to change this in order to be able to overload + // a specific key translation. For a specific package, module or line? + return parseJsonURI(localeURI).then(function (json) { + return { + hash: json, + bestMatchingLocale: bestMatchingLocale + }; + }); + }); +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/l10n/locale.js b/tools/addon-sdk-1.12/lib/sdk/l10n/locale.js index ed82789..0e59a64 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/l10n/locale.js +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/locale.js @@ -3,7 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const prefs = require("preferences-service"); +module.metadata = { + "stability": "unstable" +}; + +const prefs = require("../preferences/service"); const { Cu, Cc, Ci } = require("chrome"); const { Services } = Cu.import("resource://gre/modules/Services.jsm"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/l10n/plural-rules.js b/tools/addon-sdk-1.12/lib/sdk/l10n/plural-rules.js index c891870..22e5b8b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/l10n/plural-rules.js +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/plural-rules.js @@ -6,177 +6,182 @@ // Fetching data from: http://unicode.org/repos/cldr/trunk/common/supplemental/plurals.xml // Mapping of short locale name == to == > rule index in following list + +module.metadata = { + "stability": "unstable" +}; + const LOCALES_TO_RULES = { - "af": 2, - "ak": 3, - "am": 3, + "af": 3, + "ak": 4, + "am": 4, "ar": 1, - "asa": 2, + "asa": 3, "az": 0, - "be": 10, - "bem": 2, - "bez": 2, - "bg": 2, - "bh": 3, + "be": 11, + "bem": 3, + "bez": 3, + "bg": 3, + "bh": 4, "bm": 0, - "bn": 2, + "bn": 3, "bo": 0, - "br": 19, - "brx": 2, - "bs": 10, - "ca": 2, - "cgg": 2, - "chr": 2, - "cs": 11, - "cy": 16, - "da": 2, - "de": 2, - "dv": 2, + "br": 20, + "brx": 3, + "bs": 11, + "ca": 3, + "cgg": 3, + "chr": 3, + "cs": 12, + "cy": 17, + "da": 3, + "de": 3, + "dv": 3, "dz": 0, - "ee": 2, - "el": 2, - "en": 2, - "eo": 2, - "es": 2, - "et": 2, - "eu": 2, + "ee": 3, + "el": 3, + "en": 3, + "eo": 3, + "es": 3, + "et": 3, + "eu": 3, "fa": 0, - "ff": 4, - "fi": 2, - "fil": 3, - "fo": 2, - "fr": 4, - "fur": 2, - "fy": 2, - "ga": 7, - "gd": 23, - "gl": 2, - "gsw": 2, - "gu": 2, - "guw": 3, - "gv": 22, - "ha": 2, - "haw": 2, + "ff": 5, + "fi": 3, + "fil": 4, + "fo": 3, + "fr": 5, + "fur": 3, + "fy": 3, + "ga": 8, + "gd": 24, + "gl": 3, + "gsw": 3, + "gu": 3, + "guw": 4, + "gv": 23, + "ha": 3, + "haw": 3, "he": 2, - "hi": 3, - "hr": 10, + "hi": 4, + "hr": 11, "hu": 0, "id": 0, "ig": 0, "ii": 0, - "is": 2, - "it": 2, - "iu": 6, + "is": 3, + "it": 3, + "iu": 7, "ja": 0, - "jmc": 2, + "jmc": 3, "jv": 0, "ka": 0, - "kab": 4, - "kaj": 2, - "kcg": 2, + "kab": 5, + "kaj": 3, + "kcg": 3, "kde": 0, "kea": 0, - "kk": 2, - "kl": 2, + "kk": 3, + "kl": 3, "km": 0, "kn": 0, "ko": 0, - "ksb": 2, - "ksh": 20, - "ku": 2, - "kw": 6, - "lag": 17, - "lb": 2, - "lg": 2, - "ln": 3, + "ksb": 3, + "ksh": 21, + "ku": 3, + "kw": 7, + "lag": 18, + "lb": 3, + "lg": 3, + "ln": 4, "lo": 0, - "lt": 9, - "lv": 5, - "mas": 2, - "mg": 3, - "mk": 15, - "ml": 2, - "mn": 2, - "mo": 8, - "mr": 2, + "lt": 10, + "lv": 6, + "mas": 3, + "mg": 4, + "mk": 16, + "ml": 3, + "mn": 3, + "mo": 9, + "mr": 3, "ms": 0, - "mt": 14, + "mt": 15, "my": 0, - "nah": 2, - "naq": 6, - "nb": 2, - "nd": 2, - "ne": 2, - "nl": 2, - "nn": 2, - "no": 2, - "nr": 2, - "nso": 3, - "ny": 2, - "nyn": 2, - "om": 2, - "or": 2, - "pa": 2, - "pap": 2, - "pl": 12, - "ps": 2, - "pt": 2, - "rm": 2, - "ro": 8, - "rof": 2, - "ru": 10, - "rwk": 2, + "nah": 3, + "naq": 7, + "nb": 3, + "nd": 3, + "ne": 3, + "nl": 3, + "nn": 3, + "no": 3, + "nr": 3, + "nso": 4, + "ny": 3, + "nyn": 3, + "om": 3, + "or": 3, + "pa": 3, + "pap": 3, + "pl": 13, + "ps": 3, + "pt": 3, + "rm": 3, + "ro": 9, + "rof": 3, + "ru": 11, + "rwk": 3, "sah": 0, - "saq": 2, - "se": 6, - "seh": 2, + "saq": 3, + "se": 7, + "seh": 3, "ses": 0, "sg": 0, - "sh": 10, - "shi": 18, - "sk": 11, - "sl": 13, - "sma": 6, - "smi": 6, - "smj": 6, - "smn": 6, - "sms": 6, - "sn": 2, - "so": 2, - "sq": 2, - "sr": 10, - "ss": 2, - "ssy": 2, - "st": 2, - "sv": 2, - "sw": 2, - "syr": 2, - "ta": 2, - "te": 2, - "teo": 2, + "sh": 11, + "shi": 19, + "sk": 12, + "sl": 14, + "sma": 7, + "smi": 7, + "smj": 7, + "smn": 7, + "sms": 7, + "sn": 3, + "so": 3, + "sq": 3, + "sr": 11, + "ss": 3, + "ssy": 3, + "st": 3, + "sv": 3, + "sw": 3, + "syr": 3, + "ta": 3, + "te": 3, + "teo": 3, "th": 0, - "ti": 3, - "tig": 2, - "tk": 2, - "tl": 3, - "tn": 2, + "ti": 4, + "tig": 3, + "tk": 3, + "tl": 4, + "tn": 3, "to": 0, "tr": 0, - "ts": 2, - "tzm": 21, - "uk": 10, - "ur": 2, - "ve": 2, + "ts": 3, + "tzm": 22, + "uk": 11, + "ur": 3, + "ve": 3, "vi": 0, - "vun": 2, - "wa": 3, - "wae": 2, + "vun": 3, + "wa": 4, + "wae": 3, "wo": 0, - "xh": 2, - "xog": 2, + "xh": 3, + "xog": 3, "yo": 0, "zh": 0, - "zu": 2 + "zu": 3 }; // Utility functions for plural rules methods @@ -203,35 +208,44 @@ const RULES = { return "other" }, "2": function (n) { + if (n != 0 && (n % 10) == 0) + return "many"; + if (n == 2) + return "two"; if (n == 1) return "one"; return "other" }, "3": function (n) { - if ((isBetween(n, 0, 1))) + if (n == 1) return "one"; return "other" }, "4": function (n) { - if ((isBetween(n, 0, 2)) && n != 2) + if ((isBetween(n, 0, 1))) return "one"; return "other" }, "5": function (n) { + if ((isBetween(n, 0, 2)) && n != 2) + return "one"; + return "other" + }, + "6": function (n) { if (n == 0) return "zero"; if ((n % 10) == 1 && (n % 100) != 11) return "one"; return "other" }, - "6": function (n) { + "7": function (n) { if (n == 2) return "two"; if (n == 1) return "one"; return "other" }, - "7": function (n) { + "8": function (n) { if ((isBetween(n, 3, 6))) return "few"; if ((isBetween(n, 7, 10))) @@ -242,21 +256,21 @@ const RULES = { return "one"; return "other" }, - "8": function (n) { + "9": function (n) { if (n == 0 || n != 1 && (isBetween((n % 100), 1, 19))) return "few"; if (n == 1) return "one"; return "other" }, - "9": function (n) { + "10": function (n) { if ((isBetween((n % 10), 2, 9)) && !(isBetween((n % 100), 11, 19))) return "few"; if ((n % 10) == 1 && !(isBetween((n % 100), 11, 19))) return "one"; return "other" }, - "10": function (n) { + "11": function (n) { if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) return "few"; if ((n % 10) == 0 || (isBetween((n % 10), 5, 9)) || (isBetween((n % 100), 11, 14))) @@ -265,14 +279,14 @@ const RULES = { return "one"; return "other" }, - "11": function (n) { + "12": function (n) { if ((isBetween(n, 2, 4))) return "few"; if (n == 1) return "one"; return "other" }, - "12": function (n) { + "13": function (n) { if ((isBetween((n % 10), 2, 4)) && !(isBetween((n % 100), 12, 14))) return "few"; if (n != 1 && (isBetween((n % 10), 0, 1)) || (isBetween((n % 10), 5, 9)) || (isBetween((n % 100), 12, 14))) @@ -281,7 +295,7 @@ const RULES = { return "one"; return "other" }, - "13": function (n) { + "14": function (n) { if ((isBetween((n % 100), 3, 4))) return "few"; if ((n % 100) == 2) @@ -290,7 +304,7 @@ const RULES = { return "one"; return "other" }, - "14": function (n) { + "15": function (n) { if (n == 0 || (isBetween((n % 100), 2, 10))) return "few"; if ((isBetween((n % 100), 11, 19))) @@ -299,12 +313,12 @@ const RULES = { return "one"; return "other" }, - "15": function (n) { + "16": function (n) { if ((n % 10) == 1 && n != 11) return "one"; return "other" }, - "16": function (n) { + "17": function (n) { if (n == 3) return "few"; if (n == 0) @@ -317,21 +331,21 @@ const RULES = { return "one"; return "other" }, - "17": function (n) { + "18": function (n) { if (n == 0) return "zero"; if ((isBetween(n, 0, 2)) && n != 0 && n != 2) return "one"; return "other" }, - "18": function (n) { + "19": function (n) { if ((isBetween(n, 2, 10))) return "few"; if ((isBetween(n, 0, 1))) return "one"; return "other" }, - "19": function (n) { + "20": function (n) { if ((isBetween((n % 10), 3, 4) || ((n % 10) == 9)) && !(isBetween((n % 100), 10, 19) || isBetween((n % 100), 70, 79) || isBetween((n % 100), 90, 99))) return "few"; if ((n % 1000000) == 0 && n != 0) @@ -342,24 +356,24 @@ const RULES = { return "one"; return "other" }, - "20": function (n) { + "21": function (n) { if (n == 0) return "zero"; if (n == 1) return "one"; return "other" }, - "21": function (n) { + "22": function (n) { if ((isBetween(n, 0, 1)) || (isBetween(n, 11, 99))) return "one"; return "other" }, - "22": function (n) { + "23": function (n) { if ((isBetween((n % 10), 1, 2)) || (n % 20) == 0) return "one"; return "other" }, - "23": function (n) { + "24": function (n) { if ((isBetween(n, 3, 10) || isBetween(n, 13, 19))) return "few"; if (isIn(n, [2, 12])) @@ -380,8 +394,10 @@ const RULES = { */ exports.getRulesForLocale = function getRulesForLocale(locale) { let index = LOCALES_TO_RULES[locale]; - if (!(index in RULES)) - throw new Error('Plural form unknown for locale "' + locale + '"'); + if (!(index in RULES)) { + console.warn('Plural form unknown for locale "' + locale + '"'); + return function () { return "other"; }; + } return RULES[index]; } diff --git a/tools/addon-sdk-1.12/lib/sdk/l10n/prefs.js b/tools/addon-sdk-1.12/lib/sdk/l10n/prefs.js new file mode 100644 index 0000000..016077c --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/l10n/prefs.js @@ -0,0 +1,44 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const observers = require("../deprecated/observer-service"); +const core = require("./core"); +const { id: jetpackId} = require('../self'); + +const OPTIONS_DISPLAYED = "addon-options-displayed"; + +function onOptionsDisplayed(document, addonId) { + if (addonId !== jetpackId) + return; + let query = 'setting[data-jetpack-id="' + jetpackId + '"][pref-name], ' + + 'button[data-jetpack-id="' + jetpackId + '"][pref-name]'; + let nodes = document.querySelectorAll(query); + for (let node of nodes) { + let name = node.getAttribute("pref-name"); + if (node.tagName == "setting") { + let desc = core.get(name + "_description"); + if (desc) + node.setAttribute("desc", desc); + let title = core.get(name + "_title"); + if (title) + node.setAttribute("title", title); + + for (let item of node.querySelectorAll("menuitem, radio")) { + let key = name + "_options." + item.getAttribute("label"); + let label = core.get(key); + if (label) + item.setAttribute("label", label); + } + } + else if (node.tagName == "button") { + let label = core.get(name + "_label"); + if (label) + node.setAttribute("label", label); + } + } +} + +observers.add(OPTIONS_DISPLAYED, onOptionsDisplayed); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/functional.js b/tools/addon-sdk-1.12/lib/sdk/lang/functional.js index 61738d9..3595a27 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/functional.js +++ b/tools/addon-sdk-1.12/lib/sdk/lang/functional.js @@ -8,7 +8,11 @@ "use strict"; -const { setTimeout } = require("./timer"); +module.metadata = { + "stability": "unstable" +}; + +const { setTimeout } = require("../timers"); /** * Takes `lambda` function and returns a method. When returned method is diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/type.js b/tools/addon-sdk-1.12/lib/sdk/lang/type.js index 56df14e..a184edf 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/type.js +++ b/tools/addon-sdk-1.12/lib/sdk/lang/type.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + /** * Returns `true` if `value` is `undefined`. * @examples diff --git a/tools/addon-sdk-1.12/lib/sdk/loader/cuddlefish.js b/tools/addon-sdk-1.12/lib/sdk/loader/cuddlefish.js new file mode 100644 index 0000000..cac05a9 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/loader/cuddlefish.js @@ -0,0 +1,78 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +module.metadata = { + "stability": "unstable" +}; + +// This module is manually loaded by bootstrap.js in a sandbox and immediatly +// put in module cache so that it is never loaded in any other way. + +/* Workarounds to include dependencies in the manifest +require('chrome') // Otherwise CFX will complain about Components +require('toolkit/loader') // Otherwise CFX will stip out loader.js +require('sdk/addon/runner') // Otherwise CFX will stip out addon/runner.js +*/ + +const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; + +// `loadSandbox` is exposed by bootstrap.js +const loaderURI = module.uri.replace("sdk/loader/cuddlefish.js", + "toolkit/loader.js"); +// We need to keep a reference to the sandbox in order to unload it in +// bootstrap.js +const loaderSandbox = loadSandbox(loaderURI); +const loaderModule = loaderSandbox.exports; + +const { override } = loaderModule; + +function CuddlefishLoader(options) { + let { manifest } = options; + + options = override(options, { + // Put `api-utils/loader` and `api-utils/cuddlefish` loaded as JSM to module + // cache to avoid subsequent loads via `require`. + modules: override({ + 'toolkit/loader': loaderModule, + 'addon-sdk/sdk/loader/cuddlefish': exports + }, options.modules), + resolve: function resolve(id, requirer) { + let entry = requirer && requirer in manifest && manifest[requirer]; + let uri = null; + + // If manifest entry for this requirement is present we follow manifest. + // Note: Standard library modules like 'panel' will be present in + // manifest unless they were moved to platform. + if (entry) { + let requirement = entry.requirements[id]; + // If requirer entry is in manifest and it's requirement is not, than + // it has no authority to load since linker was not able to find it. + if (!requirement) + throw Error('Module: ' + requirer.id + ' located at ' + requirer.uri + + ' has no authority to load: ' + id, requirer.uri); + + uri = requirement; + } + // If requirer is off manifest than it's a system module and we allow it + // to go off manifest. + else { + uri = id; + } + return uri; + } + }); + + let loader = loaderModule.Loader(options); + // Hack to allow loading from `toolkit/loader`. + loader.modules[loaderURI] = loaderSandbox; + return loader; +} + +exports = override(loaderModule, { + Loader: CuddlefishLoader +}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/sandbox.js b/tools/addon-sdk-1.12/lib/sdk/loader/sandbox.js index 6130637..3c085aa 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/sandbox.js +++ b/tools/addon-sdk-1.12/lib/sdk/loader/sandbox.js @@ -5,6 +5,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +module.metadata = { + "stability": "experimental" +}; + const { Cc, Ci, CC, Cu } = require('chrome'); const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. diff --git a/tools/addon-sdk-1.12/lib/sdk/net/url.js b/tools/addon-sdk-1.12/lib/sdk/net/url.js new file mode 100644 index 0000000..5992e0d --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/net/url.js @@ -0,0 +1,108 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const { Cu, components } = require("chrome"); +const { defer } = require("../core/promise"); +const { merge } = require("../util/object"); + +const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {}); + +/** + * Open a channel synchronously for the URI given, with an optional charset, and + * returns a resolved promise if succeed; rejected promise otherwise. + */ +function readSync(uri, charset) { + let { promise, resolve, reject } = defer(); + + try { + resolve(readURISync(uri, charset)); + } + catch (e) { + reject("Failed to read: '" + uri + "' (Error Code: " + e.result + ")"); + } + + return promise; +} + +/** + * Open a channel synchronously for the URI given, with an optional charset, and + * returns a promise. + */ +function readAsync(uri, charset) { + let channel = NetUtil.newChannel(uri, charset, null); + + let { promise, resolve, reject } = defer(); + + NetUtil.asyncFetch(channel, function (stream, result) { + if (components.isSuccessCode(result)) { + let count = stream.available(); + let data = NetUtil.readInputStreamToString(stream, count, { charset : charset }); + + resolve(data); + } else { + reject("Failed to read: '" + uri + "' (Error Code: " + result + ")"); + } + }); + + return promise; +} + +/** + * Reads a URI and returns a promise. If the `sync` option is set to `true`, the + * promise will be resolved synchronously. + * + * @param uri {string} The URI to read + * @param [options] {object} This parameter can have any or all of the following + * fields: `sync`, `charset`. By default the `charset` is set to 'UTF-8'. + * + * @returns {promise} The promise that will be resolved with the content of the + * URL given. + * + * @example + * let promise = readURI('resource://gre/modules/NetUtil.jsm', { + * sync: true, + * charset: 'US-ASCII' + }); + */ +function readURI(uri, options) { + options = merge({ + charset: "UTF-8", + sync: false + }, options); + + return options.sync + ? readSync(uri, options.charset) + : readAsync(uri, options.charset); +} + +exports.readURI = readURI; + +/** + * Reads a URI synchronously. + * This function is intentionally undocumented to favorites the `readURI` usage. + * + * @param uri {string} The URI to read + * @param [charset] {string} The character set to use when read the content of + * the `uri` given. By default is set to 'UTF-8'. + * + * @returns {string} The content of the URI given. + * + * @example + * let data = readURISync('resource://gre/modules/NetUtil.jsm'); + */ +function readURISync(uri, charset) { + charset = typeof charset === "string" ? charset : "UTF-8"; + + let channel = NetUtil.newChannel(uri, charset, null); + let stream = channel.open(); + + let count = stream.available(); + let data = NetUtil.readInputStreamToString(stream, count, { charset : charset }); + + stream.close(); + + return data; +} + +exports.readURISync = readURISync; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/xhr.js b/tools/addon-sdk-1.12/lib/sdk/net/xhr.js index b7808dc..b4fc1ef 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/xhr.js +++ b/tools/addon-sdk-1.12/lib/sdk/net/xhr.js @@ -4,8 +4,13 @@ "use strict"; -const {Cc,Ci} = require("chrome"); -const memory = require('api-utils/memory'); +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci } = require("chrome"); +const memory = require('../deprecated/memory'); +const { when: unload } = require("../system/unload"); // ## Implementation Notes ## // @@ -144,7 +149,6 @@ DELEGATED_METHODS.forEach( }; }); -require("./unload").when( - function() { - requests.slice().forEach(function(request) { request._unload(); }); - }); +unload(function() { + requests.slice().forEach(function(request) { request._unload(); }); +}); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/notifications.js b/tools/addon-sdk-1.12/lib/sdk/notifications.js index 8e66355..909552f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/notifications.js +++ b/tools/addon-sdk-1.12/lib/sdk/notifications.js @@ -6,9 +6,13 @@ "use strict"; +module.metadata = { + "stability": "stable" +}; + const { Cc, Ci, Cr } = require("chrome"); -const apiUtils = require("api-utils/api-utils"); -const errors = require("api-utils/errors"); +const apiUtils = require("./deprecated/api-utils"); +const errors = require("./deprecated/errors"); try { let alertServ = Cc["@mozilla.org/alerts-service;1"]. diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/page-mod.js b/tools/addon-sdk-1.12/lib/sdk/page-mod.js index 2cc75f9..8bd4e5f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/page-mod.js +++ b/tools/addon-sdk-1.12/lib/sdk/page-mod.js @@ -5,33 +5,26 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const observers = require("api-utils/observer-service"); -const { Worker, Loader } = require('api-utils/content'); -const { EventEmitter } = require('api-utils/events'); -const { List } = require('api-utils/list'); -const { Registry } = require('api-utils/utils/registry'); -const xulApp = require("api-utils/xul-app"); -const { MatchPattern } = require('api-utils/match-pattern'); -const { validateOptions : validate } = require('api-utils/api-utils'); -const { validationAttributes } = require('api-utils/content/loader'); +module.metadata = { + "stability": "stable" +}; + +const observers = require('./deprecated/observer-service'); +const { Loader, validationAttributes } = require('./content/loader'); +const { Worker } = require('./content/worker'); +const { EventEmitter } = require('./deprecated/events'); +const { List } = require('./deprecated/list'); +const { Registry } = require('./util/registry'); +const { MatchPattern } = require('./page-mod/match-pattern'); +const { validateOptions : validate } = require('./deprecated/api-utils'); const { Cc, Ci } = require('chrome'); -const { merge } = require('api-utils/utils/object'); - -// Whether or not the host application dispatches a document-element-inserted -// notification when the document element is inserted into the DOM of a page. -// The notification was added in Gecko 2.0b6, it's a better time to attach -// scripts with contentScriptWhen "start" than content-document-global-created, -// since libraries like jQuery assume the presence of the document element. -const HAS_DOCUMENT_ELEMENT_INSERTED = - xulApp.versionInRange(xulApp.platformVersion, "2.0b6", "*"); -const ON_CONTENT = HAS_DOCUMENT_ELEMENT_INSERTED ? 'document-element-inserted' : - 'content-document-global-created'; - -// Workaround bug 642145: document-element-inserted is fired multiple times. -// This bug is fixed in Firefox 4.0.1, but we want to keep FF 4.0 compatibility -// Tracking bug 641457. To be removed when 4.0 has disappeared from earth. -const HAS_BUG_642145_FIXED = - xulApp.versionInRange(xulApp.platformVersion, "2.0.1", "*"); +const { merge } = require('./util/object'); +const { readURISync } = require('./net/url'); +const { windowIterator } = require('./deprecated/window-utils'); +const { isBrowser, getFrames } = require('./window/utils'); +const { getTabs, getTabContentWindow, getTabForContentWindow, + getURI: getTabURI } = require('./tabs/utils'); +const { has, hasAny } = require('./util/array'); const styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"]. getService(Ci.nsIStyleSheetService); @@ -41,6 +34,9 @@ const USER_SHEET = styleSheetService.USER_SHEET; const io = Cc['@mozilla.org/network/io-service;1']. getService(Ci.nsIIOService); +// Valid values for `attachTo` option +const VALID_ATTACHTO_OPTIONS = ['existing', 'top', 'frame']; + // contentStyle* / contentScript* are sharing the same validation constraints, // so they can be mostly reused, except for the messages. const validStyleOptions = { @@ -74,33 +70,17 @@ const Rules = EventEmitter.resolve({ toString: null }).compose(List, { }); /** - * Returns the content of the uri given - */ -function readURI(uri) { - let channel = io.newChannel(uri, null, null); - - let stream = Cc["@mozilla.org/scriptableinputstream;1"]. - createInstance(Ci.nsIScriptableInputStream); - - stream.init(channel.open()); - - let data = stream.read(stream.available()); - - stream.close(); - - return data; -} - -/** * PageMod constructor (exported below). * @constructor */ const PageMod = Loader.compose(EventEmitter, { on: EventEmitter.required, _listeners: EventEmitter.required, + attachTo: [], contentScript: Loader.required, contentScriptFile: Loader.required, contentScriptWhen: Loader.required, + contentScriptOptions: Loader.required, include: null, constructor: function PageMod(options) { this._onContent = this._onContent.bind(this); @@ -112,12 +92,37 @@ const PageMod = Loader.compose(EventEmitter, { this.contentScript = options.contentScript; if ('contentScriptFile' in options) this.contentScriptFile = options.contentScriptFile; + if ('contentScriptOptions' in options) + this.contentScriptOptions = options.contentScriptOptions; if ('contentScriptWhen' in options) this.contentScriptWhen = options.contentScriptWhen; if ('onAttach' in options) this.on('attach', options.onAttach); if ('onError' in options) this.on('error', options.onError); + if ('attachTo' in options) { + if (typeof options.attachTo == 'string') + this.attachTo = [options.attachTo]; + else if (Array.isArray(options.attachTo)) + this.attachTo = options.attachTo; + else + throw new Error('The `attachTo` option must be a string or an array ' + + 'of strings.'); + + let isValidAttachToItem = function isValidAttachToItem(item) { + return typeof item === 'string' && + VALID_ATTACHTO_OPTIONS.indexOf(item) !== -1; + } + if (!this.attachTo.every(isValidAttachToItem)) + throw new Error('The `attachTo` option valid accept only following ' + + 'values: '+ VALID_ATTACHTO_OPTIONS.join(', ')); + if (!hasAny(this.attachTo, ["top", "frame"])) + throw new Error('The `attachTo` option must always contain at least' + + ' `top` or `frame` value'); + } + else { + this.attachTo = ["top", "frame"]; + } let include = options.include; let rules = this.include = Rules(); @@ -132,7 +137,7 @@ const PageMod = Loader.compose(EventEmitter, { let styleRules = ""; if (contentStyleFile) - styleRules = [].concat(contentStyleFile).map(readURI).join(""); + styleRules = [].concat(contentStyleFile).map(readURISync).join(""); if (contentStyle) styleRules += [].concat(contentStyle).join(""); @@ -151,6 +156,11 @@ const PageMod = Loader.compose(EventEmitter, { pageModManager.add(this._public); this._loadingWindows = []; + + // `_applyOnExistingDocuments` has to be called after `pageModManager.add()` + // otherwise its calls to `_onContent` method won't do anything. + if ('attachTo' in options && has(options.attachTo, 'existing')) + this._applyOnExistingDocuments(); }, destroy: function destroy() { @@ -169,18 +179,50 @@ const PageMod = Loader.compose(EventEmitter, { _loadingWindows: [], + _applyOnExistingDocuments: function _applyOnExistingDocuments() { + let mod = this; + // Returns true if the tab match one rule + function isMatchingURI(uri) { + // Use Array.some as `include` isn't a native array + return Array.some(mod.include, function (rule) { + return RULES[rule].test(uri); + }); + } + let tabs = getAllTabs().filter(function (tab) { + return isMatchingURI(getTabURI(tab)); + }); + + tabs.forEach(function (tab) { + // Fake a newly created document + let window = getTabContentWindow(tab); + if (has(mod.attachTo, "top")) + mod._onContent(window); + if (has(mod.attachTo, "frame")) + getFrames(window).forEach(mod._onContent); + }); + }, + _onContent: function _onContent(window) { // not registered yet if (!pageModManager.has(this)) return; - if (!HAS_BUG_642145_FIXED) { - if (this._loadingWindows.indexOf(window) != -1) - return; - this._loadingWindows.push(window); - } + let isTopDocument = window.top === window; + // Is a top level document and `top` is not set, ignore + if (isTopDocument && !has(this.attachTo, "top")) + return; + // Is a frame document and `frame` is not set, ignore + if (!isTopDocument && !has(this.attachTo, "frame")) + return; - if ('start' == this.contentScriptWhen) { + // Immediatly evaluate content script if the document state is already + // matching contentScriptWhen expectations + let state = window.document.readyState; + if ('start' === this.contentScriptWhen || + // Is `load` event already dispatched? + 'complete' === state || + // Is DOMContentLoaded already dispatched and waiting for it? + ('ready' === this.contentScriptWhen && state === 'interactive') ) { this._createWorker(window); return; } @@ -200,18 +242,13 @@ const PageMod = Loader.compose(EventEmitter, { window: window, contentScript: this.contentScript, contentScriptFile: this.contentScriptFile, + contentScriptOptions: this.contentScriptOptions, onError: this._onUncaughtError }); this._emit('attach', worker); let self = this; worker.once('detach', function detach() { worker.destroy(); - - if (!HAS_BUG_642145_FIXED) { - let idx = self._loadingWindows.indexOf(window); - if (idx != -1) - self._loadingWindows.splice(idx, 1); - } }); }, _onRuleAdd: function _onRuleAdd(url) { @@ -243,20 +280,20 @@ const PageMod = Loader.compose(EventEmitter, { continue; if (pattern.regexp) - documentRules.push("regexp(\"" + pattern.regexp.source + "\")") + documentRules.push("regexp(\"" + pattern.regexp.source + "\")"); else if (pattern.exactURL) - documentRules.push("url(" + pattern.exactURL + ")") + documentRules.push("url(" + pattern.exactURL + ")"); else if (pattern.domain) - documentRules.push("domain(" + pattern.domain + ")") + documentRules.push("domain(" + pattern.domain + ")"); else if (pattern.urlPrefix) - documentRules.push("url-prefix(" + pattern.urlPrefix + ")") + documentRules.push("url-prefix(" + pattern.urlPrefix + ")"); else if (pattern.anyWebPage) { - documentRules.length = 0; + documentRules.push("regexp(\"^(https?|ftp)://.*?\")"); break; } } - let uri = "data:text/css,"; + let uri = "data:text/css;charset=utf-8,"; if (documentRules.length > 0) uri += encodeURIComponent("@-moz-document " + documentRules.join(",") + " {" + styleRules + "}"); @@ -290,24 +327,36 @@ const PageModManager = Registry.resolve({ constructor: function PageModRegistry(constructor) { this._init(PageMod); observers.add( - ON_CONTENT, this._onContentWindow = this._onContentWindow.bind(this) + 'document-element-inserted', + this._onContentWindow = this._onContentWindow.bind(this) ); }, _destructor: function _destructor() { - observers.remove(ON_CONTENT, this._onContentWindow); + observers.remove('document-element-inserted', this._onContentWindow); this._removeAllListeners(); for (let rule in RULES) { delete RULES[rule]; } + + // We need to do some cleaning er PageMods, like unregistering any + // `contentStyle*` + this._registry.forEach(function(pageMod) { + pageMod.destroy(); + }); + this._registryDestructor(); }, - _onContentWindow: function _onContentWindow(domObj) { - let window = HAS_DOCUMENT_ELEMENT_INSERTED ? domObj.defaultView : domObj; + _onContentWindow: function _onContentWindow(document) { + let window = document.defaultView; // XML documents don't have windows, and we don't yet support them. if (!window) return; + // We apply only on documents in tabs of Firefox + if (!getTabForContentWindow(window)) + return; + for (let rule in RULES) - if (RULES[rule].test(window.document.URL)) + if (RULES[rule].test(document.URL)) this._emit(rule, window); }, off: function off(topic, listener) { @@ -316,4 +365,16 @@ const PageModManager = Registry.resolve({ delete RULES[topic]; } }); -const pageModManager = PageModManager();
\ No newline at end of file +const pageModManager = PageModManager(); + +// Returns all tabs on all currently opened windows +function getAllTabs() { + let tabs = []; + // Iterate over all chrome windows + for (let window in windowIterator()) { + if (!isBrowser(window)) + continue; + tabs = tabs.concat(getTabs(window)); + } + return tabs; +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/match-pattern.js b/tools/addon-sdk-1.12/lib/sdk/page-mod/match-pattern.js index 60753d2..5c42e66 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/match-pattern.js +++ b/tools/addon-sdk-1.12/lib/sdk/page-mod/match-pattern.js @@ -5,7 +5,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { URL } = require("./url"); + +module.metadata = { + "stability": "unstable" +}; + +const { URL } = require("../url"); exports.MatchPattern = MatchPattern; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/page-worker.js b/tools/addon-sdk-1.12/lib/sdk/page-worker.js index 7e7b73e..f667e4d 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/page-worker.js +++ b/tools/addon-sdk-1.12/lib/sdk/page-worker.js @@ -5,10 +5,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Symbiont } = require("api-utils/content"); -const { Trait } = require("api-utils/traits"); +module.metadata = { + "stability": "stable" +}; -if (!require("api-utils/xul-app").isOneOf(["Firefox", "Thunderbird"])) { +const { Symbiont } = require("./content/symbiont"); +const { Trait } = require("./deprecated/traits"); + +if (!require("./system/xul-app").isOneOf(["Firefox", "Thunderbird"])) { throw new Error([ "The page-worker module currently supports only Firefox and Thunderbird. ", "In the future, we would like it to support other applications, however. ", @@ -37,6 +41,8 @@ const Page = Trait.compose( this.contentScriptWhen = options.contentScriptWhen; if ('contentScriptFile' in options) this.contentScriptFile = options.contentScriptFile; + if ('contentScriptOptions' in options) + this.contentScriptOptions = options.contentScriptOptions; if ('contentScript' in options) this.contentScript = options.contentScript; if ('allow' in options) diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/panel.js b/tools/addon-sdk-1.12/lib/sdk/panel.js index 5593276..3ce6284 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/panel.js +++ b/tools/addon-sdk-1.12/lib/sdk/panel.js @@ -4,7 +4,11 @@ "use strict"; -if (!require("api-utils/xul-app").is("Firefox")) { +module.metadata = { + "stability": "stable" +}; + +if (!require("./system/xul-app").is("Firefox")) { throw new Error([ "The panel module currently supports only Firefox. In the future ", "we would like it to support other applications, however. Please see ", @@ -15,11 +19,12 @@ if (!require("api-utils/xul-app").is("Firefox")) { const { Cc, Ci } = require("chrome"); -const { validateOptions: valid } = require("api-utils/api-utils"); -const { Symbiont } = require("api-utils/content"); -const { EventEmitter } = require('api-utils/events'); -const timer = require("api-utils/timer"); -const runtime = require("api-utils/runtime"); +const { validateOptions: valid } = require('./deprecated/api-utils'); +const { Symbiont } = require('./content/content'); +const { EventEmitter } = require('./deprecated/events'); +const timer = require('./timers'); +const runtime = require('./system/runtime'); +const { getMostRecentBrowserWindow } = require('./window/utils'); const windowMediator = Cc['@mozilla.org/appshell/window-mediator;1']. getService(Ci.nsIWindowMediator); @@ -118,25 +123,25 @@ const Panel = Symbiont.resolve({ if (!xulPanel) { xulPanel = this._xulPanel = document.createElementNS(XUL_NS, 'panel'); xulPanel.setAttribute("type", "arrow"); - - // One anonymous node has a big padding that doesn't work well with - // Jetpack, as we would like to display an iframe that completely fills - // the panel. + + // One anonymous node has a big padding that doesn't work well with + // Jetpack, as we would like to display an iframe that completely fills + // the panel. // -> Use a XBL wrapper with inner stylesheet to remove this padding. let css = ".panel-inner-arrowcontent, .panel-arrowcontent {padding: 0;}"; let originalXBL = "chrome://global/content/bindings/popup.xml#arrowpanel"; - let binding = + let binding = '<bindings xmlns="http://www.mozilla.org/xbl">' + - '<binding id="id" extends="' + originalXBL + '">' + - '<resources>' + - '<stylesheet src="data:text/css,' + + '<binding id="id" extends="' + originalXBL + '">' + + '<resources>' + + '<stylesheet src="data:text/css;charset=utf-8,' + document.defaultView.encodeURIComponent(css) + '"/>' + '</resources>' + '</binding>' + '</bindings>'; - xulPanel.style.MozBinding = 'url("data:text/xml,' + + xulPanel.style.MozBinding = 'url("data:text/xml;charset=utf-8,' + document.defaultView.encodeURIComponent(binding) + '")'; - + let frame = document.createElementNS(XUL_NS, 'iframe'); frame.setAttribute('type', 'content'); frame.setAttribute('flex', '1'); @@ -145,32 +150,32 @@ const Panel = Symbiont.resolve({ frame.style.borderRadius = "6px"; frame.style.padding = "1px"; } - - // Load an empty document in order to have an immediatly loaded iframe, + + // Load an empty document in order to have an immediatly loaded iframe, // so swapFrameLoaders is going to work without having to wait for load. - frame.setAttribute("src","data:,"); - + frame.setAttribute("src","data:;charset=utf-8,"); + xulPanel.appendChild(frame); document.getElementById("mainPopupSet").appendChild(xulPanel); } let { width, height } = this, x, y, position; - + if (!anchor) { // Open the popup in the middle of the window. x = document.documentElement.clientWidth / 2 - width / 2; y = document.documentElement.clientHeight / 2 - height / 2; position = null; - } + } else { // Open the popup by the anchor. let rect = anchor.getBoundingClientRect(); - + let window = anchor.ownerDocument.defaultView; - + let zoom = window.mozScreenPixelsPerCSSPixel; let screenX = rect.left + window.mozInnerScreenX * zoom; let screenY = rect.top + window.mozInnerScreenY * zoom; - + // Set up the vertical position of the popup relative to the anchor // (always display the arrow on anchor center) let horizontal, vertical; @@ -178,26 +183,26 @@ const Panel = Symbiont.resolve({ vertical = "top"; else vertical = "bottom"; - + if (screenY > window.screen.availWidth / 2 + width) horizontal = "left"; else horizontal = "right"; - + let verticalInverse = vertical == "top" ? "bottom" : "top"; position = vertical + "center " + verticalInverse + horizontal; - + // Allow panel to flip itself if the panel can't be displayed at the - // specified position (useful if we compute a bad position or if the + // specified position (useful if we compute a bad position or if the // user moves the window and panel remains visible) xulPanel.setAttribute("flip","both"); } - + // Resize the iframe instead of using panel.sizeTo // because sizeTo doesn't work with arrow panels xulPanel.firstChild.style.width = width + "px"; xulPanel.firstChild.style.height = height + "px"; - + // Wait for the XBL binding to be constructed function waitForBinding() { if (!xulPanel.openPopup) { @@ -207,7 +212,7 @@ const Panel = Symbiont.resolve({ xulPanel.openPopup(anchor, position, x, y); } waitForBinding(); - + return this._public; }, /* Public API: Panel.hide */ @@ -256,7 +261,7 @@ const Panel = Symbiont.resolve({ this.__xulPanel = value; }, __xulPanel: null, - get _viewFrame() this.__xulPanel.children[0], + get _viewFrame() this.__xulPanel.children[0], /** * When the XUL panel becomes hidden, we swap frame loaders back to move * the content of the panel to the hidden frame & remove panel element. @@ -270,6 +275,40 @@ const Panel = Symbiont.resolve({ this._emit('error', e); } }, + + /** + * Retrieve computed text color style in order to apply to the iframe + * document. As MacOS background is dark gray, we need to use skin's + * text color. + */ + _applyStyleToDocument: function _applyStyleToDocument() { + try { + let win = this._xulPanel.ownerDocument.defaultView; + let node = win.document.getAnonymousElementByAttribute( + this._xulPanel, "class", "panel-arrowcontent"); + if (!node) { + // Before bug 764755, anonymous content was different: + // TODO: Remove this when targeting FF16+ + node = win.document.getAnonymousElementByAttribute( + this._xulPanel, "class", "panel-inner-arrowcontent"); + } + let textColor = win.getComputedStyle(node).getPropertyValue("color"); + let doc = this._xulPanel.firstChild.contentDocument; + let style = doc.createElement("style"); + style.textContent = "body { color: " + textColor + "; }"; + let container = doc.head ? doc.head : doc.documentElement; + + if (container.firstChild) + container.insertBefore(style, container.firstChild); + else + container.appendChild(style); + } + catch(e) { + console.error("Unable to apply panel style"); + console.exception(e); + } + }, + /** * When the XUL panel becomes shown, we swap frame loaders between panel * frame and hidden frame to preserve state of the content dom. @@ -280,24 +319,7 @@ const Panel = Symbiont.resolve({ this.on('inited', this._onShow.bind(this)); } else { this._frameLoadersSwapped = true; - - // Retrieve computed text color style in order to apply to the iframe - // document. As MacOS background is dark gray, we need to use skin's - // text color. - let win = this._xulPanel.ownerDocument.defaultView; - let node = win.document.getAnonymousElementByAttribute(this._xulPanel, - "class", "panel-inner-arrowcontent"); - let textColor = win.getComputedStyle(node).getPropertyValue("color"); - let doc = this._xulPanel.firstChild.contentDocument; - let style = doc.createElement("style"); - style.textContent = "body { color: " + textColor + "; }"; - let container = doc.head ? doc.head : doc.documentElement; - - if (container.firstChild) - container.insertBefore(style, container.firstChild); - else - container.appendChild(style); - + this._applyStyleToDocument(); this._emit('show'); } } catch(e) { @@ -374,7 +396,7 @@ function getWindow(anchor) { // If we didn't find the anchor's window (or we have no anchor), // return the most recent browser window. if (!window) - window = windowMediator.getMostRecentWindow("navigator:browser"); + window = getMostRecentBrowserWindow(); return window; } diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/passwords.js b/tools/addon-sdk-1.12/lib/sdk/passwords.js index 3da63ad..7aeb22a 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/passwords.js +++ b/tools/addon-sdk-1.12/lib/sdk/passwords.js @@ -2,11 +2,14 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -"use strict"; +module.metadata = { + "stability": "stable" +}; -const { search, remove, store } = require("api-utils/passwords/utils"); -const { defer, delay } = require("api-utils/functional"); +const { search, remove, store } = require("./passwords/utils"); +const { defer, delay } = require("./lang/functional"); /** * Utility function that returns `onComplete` and `onError` callbacks form the diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/passwords/utils.js b/tools/addon-sdk-1.12/lib/sdk/passwords/utils.js index 5dc6098..8cc2230 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/passwords/utils.js +++ b/tools/addon-sdk-1.12/lib/sdk/passwords/utils.js @@ -5,13 +5,17 @@ "use strict"; -const { Cc, Ci, components: { Constructor: CConstructor } } = require("chrome"); -const { uri: ADDON_URI } = require("self"); +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci, CC } = require("chrome"); +const { uri: ADDON_URI } = require("../self"); const loginManager = Cc["@mozilla.org/login-manager;1"]. getService(Ci.nsILoginManager); const { URL: parseURL } = require("../url"); -const LoginInfo = CConstructor("@mozilla.org/login-manager/loginInfo;1", - "nsILoginInfo", "init"); +const LoginInfo = CC("@mozilla.org/login-manager/loginInfo;1", + "nsILoginInfo", "init"); function filterMatchingLogins(loginInfo) Object.keys(this).every(function(key) loginInfo[key] === this[key], this); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/xpcom.js b/tools/addon-sdk-1.12/lib/sdk/platform/xpcom.js index efdf873..279d234 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/xpcom.js +++ b/tools/addon-sdk-1.12/lib/sdk/platform/xpcom.js @@ -4,60 +4,65 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci, Cr, Cm, components: { classesByID } } = require('chrome'); const { registerFactory, unregisterFactory, isCIDRegistered } = Cm.QueryInterface(Ci.nsIComponentRegistrar); -const { when: unload } = require('./unload'); -const { Base } = require('./base'); -const { uuid } = require('./uuid'); +const { merge } = require('../util/object'); +const { Class, extend, mix } = require('../core/heritage'); +const { uuid } = require('../util/uuid'); // This is a base prototype, that provides bare bones of XPCOM. JS based // components can be easily implement by extending it. -const Unknown = Base.extend({ - // Method `extend` is overridden so that resulting object will contain - // `interfaces` array property, containing elements from ancestor and all - // provided sources. - extend: function extend() { - let args = Array.slice(arguments); - return Base.extend.apply(this, args.concat([{ - interfaces: args.reduce(function(interfaces, source) { - // If given source has `interfaces` property concatenate it's elements - // them resulting `interfaces` array, otherwise return resulting - // `interfaces` array. - return 'interfaces' in source ? source.interfaces.concat(interfaces) - : interfaces; - }, this.interfaces) - }])); - }, - /** - * The `QueryInterface` method provides runtime type discovery used by XPCOM. - * This method return quired instance of `this` if given `iid` is listed in - * the `interfaces` property. - */ - QueryInterface: function QueryInterface(iid) { - // For some reason there are cases when `iid` is `null`. In such cases we - // just return `this`. Otherwise we verify that component implements given - // `iid` interface. - if (iid && !this.interfaces.some(function(id) iid.equals(Ci[id]))) - throw Cr.NS_ERROR_NO_INTERFACE; - return this; - }, - /** - * Array of `XPCOM` interfaces (as strings) implemented by this component. All - * components implement `nsISupports` by default which is default value here. - * Provide array of interfaces implemented by an object when extending, to - * append them to this list (Please note that there is no need to repeat - * interfaces implemented by super as they will be added automatically). - */ - interfaces: [ 'nsISupports' ] -}); +const Unknown = new function() { + function hasInterface(component, iid) { + return component && component.interfaces && + ( component.interfaces.some(function(id) iid.equals(Ci[id])) || + component.implements.some(function($) hasInterface($, iid)) || + hasInterface(Object.getPrototypeOf(component), iid)); + } + + return Class({ + /** + * The `QueryInterface` method provides runtime type discovery used by XPCOM. + * This method return queried instance of `this` if given `iid` is listed in + * the `interfaces` property or in equivalent properties of objects in it's + * prototype chain. In addition it will look up in the prototypes under + * `implements` array property, this ways compositions made via `Class` + * utility will carry interfaces implemented by composition components. + */ + QueryInterface: function QueryInterface(iid) { + // For some reason there are cases when `iid` is `null`. In such cases we + // just return `this`. Otherwise we verify that component implements given + // `iid` interface. This will be no longer necessary once Bug 748003 is + // fixed. + if (iid && !hasInterface(this, iid)) + throw Cr.NS_ERROR_NO_INTERFACE; + + return this; + }, + /** + * Array of `XPCOM` interfaces (as strings) implemented by this component. + * All components implement `nsISupports` by default which is default value + * here. Provide array of interfaces implemented by an object when + * extending, to append them to this list (Please note that there is no + * need to repeat interfaces implemented by super as they will be added + * automatically). + */ + interfaces: Object.freeze([ 'nsISupports' ]) + }); +} exports.Unknown = Unknown; // Base exemplar for creating instances implementing `nsIFactory` interface, // that maybe registered into runtime via `register` function. Instances of // this factory create instances of enclosed component on `createInstance`. -const Factory = Unknown.extend({ +const Factory = Class({ + extends: Unknown, interfaces: [ 'nsIFactory' ], /** * All the descendants will get auto generated `id` (also known as `classID` @@ -101,8 +106,13 @@ const Factory = Unknown.extend({ * be automatically unregistered on add-on unload. */ initialize: function initialize(options) { - options = options || {} - this.merge(options, { id: 'id' in options && options.id || uuid() }); + merge(this, { + id: 'id' in options ? options.id : uuid(), + register: 'register' in options ? options.register : this.register, + unregister: 'unregister' in options ? options.unregister : this.unregister, + contract: 'contract' in options ? options.contract : null, + Component: options.Component + }); // If service / factory has auto registration enabled then register. if (this.register) @@ -121,14 +131,19 @@ const Factory = Unknown.extend({ throw error instanceof Ci.nsIException ? error : Cr.NS_ERROR_FAILURE; } }, - create: function create() this.component.new() + create: function create() this.Component() }); exports.Factory = Factory; // Exemplar for creating services that implement `nsIFactory` interface, that // can be registered into runtime via call to `register`. This services return // enclosed `component` on `getService`. -const Service = Factory.extend({ +const Service = Class({ + extends: Factory, + initialize: function initialize(options) { + this.component = options.Component(); + Factory.prototype.initialize.call(this, options); + }, description: 'Jetpack generated service', /** * Creates an instance of the class associated with this factory. @@ -146,10 +161,17 @@ exports.isRegistered = isRegistered; * name and `component.contract` with the class. */ function register(factory) { + if (!(factory instanceof Factory)) { + throw new Error("xpcom.register() expect a Factory instance.\n" + + "Please refactor your code to new xpcom module if you" + + " are repacking an addon from SDK <= 1.5:\n" + + "https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/api-utils/xpcom.html"); + } + registerFactory(factory.id, factory.description, factory.contract, factory); if (factory.unregister) - unload(unregister.bind(null, factory)); + require('../system/unload').when(unregister.bind(null, factory)); } exports.register = register; @@ -172,9 +194,9 @@ function autoRegister(path) { // Gecko-specific binaries for a component (which will be the case // if only frozen interfaces are used). - var runtime = require("./runtime"); + var runtime = require("../system/runtime"); var osDirName = runtime.OS + "_" + runtime.XPCOMABI; - var platformVersion = require("./xul-app").platformVersion.substring(0, 5); + var platformVersion = require("../system/xul-app").platformVersion.substring(0, 5); var file = Cc['@mozilla.org/file/local;1'] .createInstance(Ci.nsILocalFile); diff --git a/tools/addon-sdk-1.12/lib/sdk/preferences/event-target.js b/tools/addon-sdk-1.12/lib/sdk/preferences/event-target.js new file mode 100644 index 0000000..fe9e07a --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/preferences/event-target.js @@ -0,0 +1,60 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci } = require('chrome'); +const { Class } = require('../core/heritage'); +const { EventTarget } = require('../event/target'); +const { Branch } = require('./service'); +const { emit, off } = require('../event/core'); +const { when: unload } = require('../system/unload'); + +const prefTargetNS = require('../core/namespace').ns(); + +const PrefsTarget = Class({ + extends: EventTarget, + initialize: function(options) { + options = options || {}; + EventTarget.prototype.initialize.call(this, options); + + let branchName = options.branchName || ''; + let branch = Cc["@mozilla.org/preferences-service;1"]. + getService(Ci.nsIPrefService). + getBranch(branchName). + QueryInterface(Ci.nsIPrefBranch2); + prefTargetNS(this).branch = branch; + + // provides easy access to preference values + this.prefs = Branch(branchName); + + // start listening to preference changes + let observer = prefTargetNS(this).observer = onChange.bind(this); + branch.addObserver('', observer, false); + + // Make sure to destroy this on unload + unload(destroy.bind(this)); + } +}); +exports.PrefsTarget = PrefsTarget; + +/* HELPERS */ + +function onChange(subject, topic, name) { + if (topic === 'nsPref:changed') + emit(this, name, name); + emit(this, '', name); +} + +function destroy() { + off(this); + + // stop listening to preference changes + let branch = prefTargetNS(this).branch; + branch.removeObserver('', prefTargetNS(this).observer, false); + prefTargetNS(this).observer = null; +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/preferences-service.js b/tools/addon-sdk-1.12/lib/sdk/preferences/service.js index c5ffb2a..4303fc1 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/preferences-service.js +++ b/tools/addon-sdk-1.12/lib/sdk/preferences/service.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + // The minimum and maximum integers that can be set as preferences. // The range of valid values is narrower than the range of valid JS values // because the native preferences code treats integers as NSPR PRInt32s, @@ -18,7 +22,38 @@ const prefService = Cc["@mozilla.org/preferences-service;1"]. const prefSvc = prefService.getBranch(null); const defaultBranch = prefService.getDefaultBranch(null); -var get = exports.get = function get(name, defaultValue) { +function Branch(branchName) { + function getPrefKeys() { + return keys(branchName).map(function(key) { + return key.replace(branchName, ""); + }); + } + + return Proxy.create({ + get: function(receiver, pref) { + return get(branchName + pref); + }, + set: function(receiver, pref, val) { + set(branchName + pref, val); + }, + delete: function(pref) { + reset(branchName + pref); + return true; + }, + has: function hasPrefKey(pref) { + return has(branchName + pref) + }, + getPropertyDescriptor: function(name) { + return { + value: get(branchName + name) + }; + }, + enumerate: getPrefKeys, + keys: getPrefKeys + }, Branch.prototype); +} + +function get(name, defaultValue) { switch (prefSvc.getPrefType(name)) { case Ci.nsIPrefBranch.PREF_STRING: return prefSvc.getComplexValue(name, Ci.nsISupportsString).data; @@ -40,9 +75,10 @@ var get = exports.get = function get(name, defaultValue) { ", which I don't know " + "how to handle."); } -}; +} +exports.get = get; -var set = exports.set = function set(name, value) { +function set(name, value) { var prefType; if (typeof value != "undefined" && value != null) prefType = value.constructor.name; @@ -80,17 +116,25 @@ var set = exports.set = function set(name, value) { throw new Error("can't set pref " + name + " to value '" + value + "'; it isn't a string, integer, or boolean"); } -}; +} +exports.set = set; -var has = exports.has = function has(name) { +function has(name) { return (prefSvc.getPrefType(name) != Ci.nsIPrefBranch.PREF_INVALID); -}; +} +exports.has = has; -var isSet = exports.isSet = function isSet(name) { +function keys(root) { + return prefSvc.getChildList(root); +} +exports.keys = keys; + +function isSet(name) { return (has(name) && prefSvc.prefHasUserValue(name)); -}; +} +exports.isSet = isSet; -var reset = exports.reset = function reset(name) { +function reset(name) { try { prefSvc.clearUserPref(name); } catch (e if e.result == Cr.NS_ERROR_UNEXPECTED) { @@ -102,9 +146,10 @@ var reset = exports.reset = function reset(name) { // other exceptions, however, so callers know about them, since we don't // know what other exceptions might be thrown and what they might mean. } -}; +} +exports.reset = reset; -exports.getLocalized = function getLocalized(name, defaultValue) { +function getLocalized(name, defaultValue) { let value = null; try { value = prefSvc.getComplexValue(name, Ci.nsIPrefLocalizedString).data; @@ -113,8 +158,9 @@ exports.getLocalized = function getLocalized(name, defaultValue) { return value || defaultValue; } } +exports.getLocalized = getLocalized; -exports.setLocalized = function setLocalized(name, value) { +function setLocalized(name, value) { // We can't use `prefs.set` here as we have to use `getDefaultBranch` // (instead of `getBranch`) in order to have `mIsDefault` set to true, here: // http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/nsPrefBranch.cpp#233 @@ -122,3 +168,7 @@ exports.setLocalized = function setLocalized(name, value) { // http://mxr.mozilla.org/mozilla-central/source/modules/libpref/src/nsPrefBranch.cpp#244 defaultBranch.setCharPref(name, value); } +exports.setLocalized = setLocalized; + +exports.Branch = Branch; + diff --git a/tools/addon-sdk-1.12/lib/sdk/private-browsing.js b/tools/addon-sdk-1.12/lib/sdk/private-browsing.js new file mode 100644 index 0000000..6d2a709 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/private-browsing.js @@ -0,0 +1,36 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + "stability": "stable" +}; + +const { setMode, getMode, on: onStateChange } = require('./private-browsing/utils'); +const { emit, on, once, off } = require('./event/core'); +const { when: unload } = require('./system/unload'); +const observers = require('./deprecated/observer-service'); + +onStateChange('start', function onStart() { + emit(exports, 'start'); +}); + +onStateChange('stop', function onStop() { + emit(exports, 'stop'); +}); + +// Make sure listeners are cleaned up. +unload(function() off(exports)); + +Object.defineProperty(exports, "isActive", { get: function() getMode() }); +exports.activate = function activate() setMode(true); +exports.deactivate = function deactivate() setMode(false); +exports.on = on.bind(null, exports); +exports.once = once.bind(null, exports); +exports.removeListener = function removeListener(type, listener) { + // Note: We can't just bind `off` as we do it for other methods cause skipping + // a listener argument will remove all listeners for the given event type + // causing misbehavior. This way we make sure all arguments are passed. + off(exports, type, listener); +}; diff --git a/tools/addon-sdk-1.12/lib/sdk/private-browsing/utils.js b/tools/addon-sdk-1.12/lib/sdk/private-browsing/utils.js new file mode 100644 index 0000000..1f57ca0 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/private-browsing/utils.js @@ -0,0 +1,74 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci } = require('chrome'); +const { defer } = require('../lang/functional'); +const observers = require('../deprecated/observer-service'); +const { emit, on, once, off } = require('../event/core'); +const { when: unload } = require('../system/unload'); +const { getWindowLoadingContext } = require('../window/utils'); +const { deprecateFunction } = require('../util/deprecate'); + +let deferredEmit = defer(emit); + +let pbService; + +// Currently, only Firefox implements the private browsing service. +if (require("../system/xul-app").is("Firefox")) { + pbService = Cc["@mozilla.org/privatebrowsing;1"]. + getService(Ci.nsIPrivateBrowsingService); + + // set up an observer for private browsing switches. + observers.add('private-browsing-transition-complete', function onChange() { + // Emit event with in next turn of event loop. + deferredEmit(exports, pbService.privateBrowsingEnabled ? 'start' : 'stop'); + }); +} + +// checks that per-window private browsing implemented +let isWindowPBEnabled = function isWindowPBEnabled(chromeWin) { + return !!(chromeWin && + 'gPrivateBrowsingUI' in chromeWin && + 'privateWindow' in chromeWin.gPrivateBrowsingUI); +} +exports.isWindowPBEnabled = isWindowPBEnabled; + +// We toggle private browsing mode asynchronously in order to work around +// bug 659629. Since private browsing transitions are asynchronous +// anyway, this doesn't significantly change the behavior of the API. +// Note: this method should not be used with `chromeWin` argument until +// the UI has been implemented. Bug 729865 +let setMode = defer(function setMode(value, chromeWin) { + value = !!value; // Cast to boolean. + + if (isWindowPBEnabled(chromeWin)) + return getWindowLoadingContext(chromeWin).usePrivateBrowsing = value; + + // default + return pbService && (pbService.privateBrowsingEnabled = value); +}); +exports.setMode = deprecateFunction( + setMode, + 'require("private-browsing").activate and require("private-browsing").deactivate ' + + 'is deprecated.' +); + +let getMode = function getMode(chromeWin) { + if (isWindowPBEnabled(chromeWin)) + return getWindowLoadingContext(chromeWin).usePrivateBrowsing; + + // default + return pbService ? pbService.privateBrowsingEnabled : false; +}; +exports.getMode = getMode; + +exports.on = on.bind(null, exports); + +// Make sure listeners are cleaned up. +unload(function() off(exports)); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/querystring.js b/tools/addon-sdk-1.12/lib/sdk/querystring.js index 9e29515..e0e2273 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/querystring.js +++ b/tools/addon-sdk-1.12/lib/sdk/querystring.js @@ -4,6 +4,10 @@ 'use strict'; +module.metadata = { + "stability": "unstable" +}; + let unescape = decodeURIComponent; exports.unescape = unescape; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/request.js b/tools/addon-sdk-1.12/lib/sdk/request.js index b213af8..da5be7f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/request.js +++ b/tools/addon-sdk-1.12/lib/sdk/request.js @@ -4,14 +4,18 @@ "use strict"; -const { Base, Class } = require("api-utils/base"); -const { ns } = require("api-utils/namespace"); -const { emit } = require("api-utils/event/core"); -const { merge } = require("api-utils/utils/object"); -const { stringify } = require("api-utils/querystring"); -const { EventTarget } = require("api-utils/event/target"); -const { XMLHttpRequest } = require("api-utils/xhr"); -const apiUtils = require("api-utils/api-utils"); +module.metadata = { + "stability": "stable" +}; + +const { ns } = require("./core/namespace"); +const { emit } = require("./event/core"); +const { merge } = require("./util/object"); +const { stringify } = require("./querystring"); +const { EventTarget } = require("./event/target"); +const { Class } = require("./core/heritage"); +const { XMLHttpRequest } = require("./net/xhr"); +const apiUtils = require("./deprecated/api-utils"); const response = ns(); const request = ns(); @@ -82,7 +86,7 @@ function runRequest(mode, target) { // handle the readystate, create the response, and call the callback xhr.onreadystatechange = function onreadystatechange() { if (xhr.readyState === 4) { - let response = Response.new(xhr); + let response = Response(xhr); source.response = response; emit(target, 'complete', response); } @@ -93,12 +97,13 @@ function runRequest(mode, target) { xhr.send(mode !== "GET" ? data : null); } -const Request = EventTarget.extend({ +const Request = Class({ + extends: EventTarget, initialize: function initialize(options) { // `EventTarget.initialize` will set event listeners that are named // like `onEvent` in this case `onComplete` listener will be set to // `complete` event. - EventTarget.initialize.call(this, options); + EventTarget.prototype.initialize.call(this, options); // Copy normalized options. merge(request(this), validateOptions(options)); @@ -131,9 +136,9 @@ const Request = EventTarget.extend({ return this; } }); -exports.Request = Class(Request); +exports.Request = Request; -const Response = Base.extend({ +const Response = Class({ initialize: function initialize(request) { response(this).request = request; }, diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/selection.js b/tools/addon-sdk-1.12/lib/sdk/selection.js index f10d890..da94efe 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/selection.js +++ b/tools/addon-sdk-1.12/lib/sdk/selection.js @@ -4,7 +4,11 @@ "use strict"; -if (!require("api-utils/xul-app").is("Firefox")) { +module.metadata = { + "stability": "stable" +}; + +if (!require("./system/xul-app").is("Firefox")) { throw new Error([ "The selection module currently supports only Firefox. In the future ", "we would like it to support other applications, however. Please see ", @@ -13,17 +17,60 @@ if (!require("api-utils/xul-app").is("Firefox")) { } let { Ci, Cc } = require("chrome"), - { setTimeout } = require("api-utils/timer"), - { emit, off } = require("api-utils/event/core"), - { Unknown } = require("api-utils/xpcom"), - { Base } = require("api-utils/base"), - { EventTarget } = require("api-utils/event/target"); - + { setTimeout } = require("./timers"), + { emit, off } = require("./event/core"), + { Unknown } = require("./platform/xpcom"), + { Class, obscure } = require("./core/heritage"), + { EventTarget } = require("./event/target"), + observers = require("./deprecated/observer-service"), + { ns } = require("./core/namespace"); + +// When a document is not visible anymore the selection object is detached, and +// a new selection object is created when it becomes visible again. +// That makes the previous selection's listeners added previously totally +// useless – the listeners are not notified anymore. +// To fix that we're listening for `document-shown` event in order to add +// the listeners to the new selection object created. +// +// See bug 665386 for further details. + +let selections = ns(); + +observers.add("document-shown", function (document) { + var window = document.defaultView; + + // We are not interested in documents without valid defaultView + if (!window) + return; + + let selection = selections(window).selection; + + // We want to handle only the windows where we added selection's listeners + if (selection) { + let currentSelection = window.getSelection(); + + // If the current selection for the window given is different from the one + // stored in the namespace, we need to add the listeners again, and replace + // the previous selection in our list with the new one. + // + // Notice that we don't have to remove the listeners from the old selection, + // because is detached. An attempt to remove the listener, will raise an + // error (see http://mxr.mozilla.org/mozilla-central/source/layout/generic/nsSelection.cpp#5343 ) + // + // We ensure that the current selection is an instance of + // `nsISelectionPrivate` before working on it, in case is `null`. + if (currentSelection instanceof Ci.nsISelectionPrivate && + currentSelection !== selection) { + + currentSelection.addSelectionListener(SelectionListenerManager); + selections(window).selection = currentSelection; + } + } +}); const windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]. getService(Ci.nsIWindowMediator); - // The selection type HTML const HTML = 0x01; @@ -38,7 +85,7 @@ const DOM = 0x03; const ERR_CANNOT_CHANGE_SELECTION = "It isn't possible to change the selection, as there isn't currently a selection"; -const Selection = Base.extend({ +const Selection = Class({ /** * Creates an object from which a selection can be set, get, etc. Each * object has an associated with a range number. Range numbers are the @@ -274,7 +321,8 @@ function onSelect() { SelectionListenerManager.onSelect(); } -let SelectionListenerManager = Unknown.extend({ +let SelectionListenerManager = Class({ + extends: Unknown, interfaces: [ 'nsISelectionListener' ], /** * This is the nsISelectionListener implementation. This function is called @@ -338,19 +386,27 @@ let SelectionListenerManager = Unknown.extend({ }, addSelectionListener: function addSelectionListener(window) { - if (window.jetpack_core_selection_listener) + // Don't add the selection's listener more than once to the same window. + if ("selection" in selections(window)) return; + let selection = window.getSelection(); - if (selection instanceof Ci.nsISelectionPrivate) + + // We ensure that the current selection is an instance of + // `nsISelectionPrivate` before working on it, in case is `null`. + if (selection instanceof Ci.nsISelectionPrivate) { selection.addSelectionListener(this); - // nsISelectionListener implementation seems not fire a notification if - // a selection is in a text field, therefore we need to add a listener to - // window.onselect, that is fired only for text fields. - // https://developer.mozilla.org/en/DOM/window.onselect - window.addEventListener("select", onSelect, true); + // nsISelectionListener implementation seems not fire a notification if + // a selection is in a text field, therefore we need to add a listener to + // window.onselect, that is fired only for text fields. + // For consistency, we add it only when the nsISelectionListener is added. + // + // https://developer.mozilla.org/en/DOM/window.onselect + window.addEventListener("select", onSelect, true); - window.jetpack_core_selection_listener = true; + selections(window).selection = selection; + } }, onUnload: function onUnload(event) { @@ -363,15 +419,21 @@ let SelectionListenerManager = Unknown.extend({ }, removeSelectionListener: function removeSelectionListener(window) { - if (!window.jetpack_core_selection_listener) + // Don't remove the selection's listener to a window that wasn't handled. + if (!("selection" in selections(window))) return; + let selection = window.getSelection(); - if (selection instanceof Ci.nsISelectionPrivate) + + // We ensure that the current selection is an instance of + // `nsISelectionPrivate` before working on it, in case is `null`. + if (selection instanceof Ci.nsISelectionPrivate) { selection.removeSelectionListener(this); - window.removeEventListener("select", onSelect); + window.removeEventListener("select", onSelect); - window.jetpack_core_selection_listener = false; + delete selections(window).selection; + } }, /** @@ -386,17 +448,15 @@ let SelectionListenerManager = Unknown.extend({ browser.removeEventListener("load", onLoad, true); browser.removeEventListener("unload", onUnload, true); } -}); +})(); /** * Install |SelectionListenerManager| as tab tracker in order to watch * tab opening/closing */ -require("api-utils/tab-browser").Tracker(SelectionListenerManager); +require("./deprecated/tab-browser").Tracker(SelectionListenerManager); -// Note: We use `Object.create` form just in order to define `__iterator__` -// as non-enumerable, to ensure that it won't be returned by an `Object.keys`. -var SelectionIterator = Object.create(Object.prototype, { +var SelectionIterator = Class(obscure({ /** * Exports an iterator so that discontiguous selections can be iterated. * @@ -404,18 +464,18 @@ var SelectionIterator = Object.create(Object.prototype, { * is returned because the text field selection APIs doesn't support * multiple selections. */ - __iterator__: { enumerable: false, value: function() { + __iterator__: function() { let selection = getSelection(DOM); let count = selection.rangeCount || (getElementWithSelection() ? 1 : 0); for (let i = 0; i < count; i++) - yield Selection.new(i); - }} -}); + yield Selection(i); + } +})); -var selection = EventTarget.extend(Selection, SelectionIterator).new(0); +var selection = Class({ + extends: EventTarget, + implements: [ Selection, SelectionIterator ] +})(0); -// This is workaround making sure that exports is wrapped before it's -// frozen, which needs to happen in order to workaround Bug 673468. -off(selection, 'workaround-bug-673468'); module.exports = selection; diff --git a/tools/addon-sdk-1.12/lib/sdk/self.js b/tools/addon-sdk-1.12/lib/sdk/self.js new file mode 100644 index 0000000..f9fca1e --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/self.js @@ -0,0 +1,36 @@ +/* vim:st=2:sts=2:sw=2: + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { CC } = require('chrome'); +const { id, name, prefixURI, rootURI, + version, loadReason } = require('@loader/options'); + +const { readURISync } = require('./net/url'); + +const addonDataURI = prefixURI + name + '/data/'; + +function uri(path) { + return addonDataURI + (path || ''); +} + + +// Some XPCOM APIs require valid URIs as an argument for certain operations +// (see `nsILoginManager` for example). This property represents add-on +// associated unique URI string that can be used for that. +exports.uri = 'addon:' + id; +exports.id = id; +exports.name = name; +exports.loadReason = loadReason; +exports.version = version; +// If `rootURI` is jar:file://...!/ than add-on is packed. +exports.packed = rootURI.indexOf('jar:') === 0 +exports.data = Object.freeze({ + url: uri, + load: function read(path) { + return readURISync(uri(path)); + } +}); diff --git a/tools/addon-sdk-1.12/lib/sdk/simple-prefs.js b/tools/addon-sdk-1.12/lib/sdk/simple-prefs.js new file mode 100644 index 0000000..5cbde49 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/simple-prefs.js @@ -0,0 +1,32 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + "stability": "experimental" +}; + +const { emit, off } = require("./event/core"); +const { when: unload } = require("./system/unload"); +const { PrefsTarget } = require("./preferences/event-target"); +const { id } = require("./self"); +const observers = require("./deprecated/observer-service"); + +const ADDON_BRANCH = "extensions." + id + "."; +const BUTTON_PRESSED = id + "-cmdPressed"; + +const target = PrefsTarget({ branchName: ADDON_BRANCH }); + +// Listen to clicks on buttons +function buttonClick(subject, data) { + emit(target, data); +} +observers.add(BUTTON_PRESSED, buttonClick); + +// Make sure we cleanup listeners on unload. +unload(function() { + observers.remove(BUTTON_PRESSED, buttonClick); +}); + +module.exports = target; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/simple-storage.js b/tools/addon-sdk-1.12/lib/sdk/simple-storage.js index 85395f8..2b88cc1 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/simple-storage.js +++ b/tools/addon-sdk-1.12/lib/sdk/simple-storage.js @@ -6,13 +6,17 @@ "use strict"; +module.metadata = { + "stability": "stable" +}; + const { Cc, Ci } = require("chrome"); -const file = require("api-utils/file"); -const prefs = require("api-utils/preferences-service"); -const jpSelf = require("self"); -const timer = require("api-utils/timer"); -const unload = require("api-utils/unload"); -const { emit, on, off } = require("api-utils/event/core"); +const file = require("./io/file"); +const prefs = require("./preferences/service"); +const jpSelf = require("./self"); +const timer = require("./timers"); +const unload = require("./system/unload"); +const { emit, on, off } = require("./event/core"); const WRITE_PERIOD_PREF = "extensions.addon-sdk.simple-storage.writePeriod"; const WRITE_PERIOD_DEFAULT = 300000; // 5 minutes @@ -227,10 +231,6 @@ let manager = ({ } }).new(); -// This is workaround making sure that exports is wrapped before it's -// frozen, which needs to happen in order to workaround Bug 673468. -off(exports, 'workaround-bug-673468'); - exports.on = on.bind(null, exports); exports.removeListener = function(type, listener) { off(exports, type, listener); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/system.js b/tools/addon-sdk-1.12/lib/sdk/system.js index 3986645..1e374d3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/system.js +++ b/tools/addon-sdk-1.12/lib/sdk/system.js @@ -5,10 +5,14 @@ 'use strict'; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci, CC } = require('chrome'); -const options = require('@packaging'); -const file = require('./file'); -const runtime = require("./runtime.js"); +const options = require('@loader/options'); +const file = require('./io/file'); +const runtime = require("./system/runtime"); const appStartup = Cc['@mozilla.org/toolkit/app-startup;1']. getService(Ci.nsIAppStartup); @@ -17,6 +21,20 @@ const appInfo = Cc["@mozilla.org/xre/app-info;1"]. const directoryService = Cc['@mozilla.org/file/directory_service;1']. getService(Ci.nsIProperties); +const PR_WRONLY = parseInt("0x02"); +const PR_CREATE_FILE = parseInt("0x08"); +const PR_APPEND = parseInt("0x10"); +const PR_TRUNCATE = parseInt("0x20"); + +function openFile(path, mode) { + let file = Cc["@mozilla.org/file/local;1"]. + createInstance(Ci.nsILocalFile); + file.initWithPath(path); + let stream = Cc["@mozilla.org/network/file-output-stream;1"]. + createInstance(Ci.nsIFileOutputStream); + stream.init(file, mode, -1, 0); + return stream +} const { eAttemptQuit: E_ATTEMPT, eForceQuit: E_FORCE } = appStartup; @@ -29,7 +47,7 @@ exports.staticArgs = options.staticArgs; * Environment variables. Environment variables are non-enumerable properties * of this object (key is name and value is value). */ -exports.env = require('./environment').env; +exports.env = require('./system/environment').env; /** * Ends the process with the specified `code`. If omitted, exit uses the @@ -38,15 +56,32 @@ exports.env = require('./environment').env; */ exports.exit = function exit(code) { // This is used by 'cfx' to find out exit code. - if ('resultFile' in options) { - let stream = file.open(options.resultFile, 'w'); - stream.write(code ? 'FAIL' : 'OK'); + if ('resultFile' in options && options.resultFile) { + let mode = PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE; + let stream = openFile(options.resultFile, mode); + let status = code ? 'FAIL' : 'OK'; + stream.write(status, status.length); + stream.flush(); stream.close(); } appStartup.quit(code ? E_ATTEMPT : E_FORCE); }; +exports.stdout = new function() { + let write = dump + if ('logFile' in options && options.logFile) { + let mode = PR_WRONLY | PR_CREATE_FILE | PR_APPEND; + let stream = openFile(options.logFile, mode); + write = function write(data) { + let text = String(data); + stream.write(text, text.length); + stream.flush(); + } + } + return Object.freeze({ write: write }); +}; + /** * Returns a path of the system's or application's special directory / file * associated with a given `id`. For list of possible `id`s please see: diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/environment.js b/tools/addon-sdk-1.12/lib/sdk/system/environment.js index fd95c67..045bab1 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/environment.js +++ b/tools/addon-sdk-1.12/lib/sdk/system/environment.js @@ -5,6 +5,10 @@ 'use strict'; +module.metadata = { + "stability": "stable" +}; + const { Cc, Ci } = require('chrome'); const { get, set, exists } = Cc['@mozilla.org/process/environment;1']. getService(Ci.nsIEnvironment); diff --git a/tools/addon-sdk-1.12/lib/sdk/system/events.js b/tools/addon-sdk-1.12/lib/sdk/system/events.js new file mode 100644 index 0000000..a75dddc --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/system/events.js @@ -0,0 +1,113 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "unstable" +}; + +const { Cc, Ci } = require('chrome'); +const { Unknown } = require('../platform/xpcom'); +const { Class } = require('../core/heritage'); +const { ns } = require('../core/namespace'); +const { addObserver, removeObserver, notifyObservers } = + Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService); + +const Subject = Class({ + extends: Unknown, + initialize: function initialize(object) { + // Double-wrap the object and set a property identifying the + // wrappedJSObject as one of our wrappers to distinguish between + // subjects that are one of our wrappers (which we should unwrap + // when notifying our observers) and those that are real JS XPCOM + // components (which we should pass through unaltered). + this.wrappedJSObject = { + observersModuleSubjectWrapper: true, + object: object + }; + }, + getHelperForLanguage: function() {}, + getInterfaces: function() {} +}); + +function emit(type, event) { + let subject = 'subject' in event ? Subject(event.subject) : null; + let data = 'data' in event ? event.data : null; + notifyObservers(subject, type, data); +} +exports.emit = emit; + +const Observer = Class({ + extends: Unknown, + initialize: function initialize(listener) { + this.listener = listener; + }, + interfaces: [ 'nsIObserver', 'nsISupportsWeakReference' ], + observe: function(subject, topic, data) { + // Extract the wrapped object for subjects that are one of our + // wrappers around a JS object. This way we support both wrapped + // subjects created using this module and those that are real + // XPCOM components. + if (subject && typeof(subject) == 'object' && + ('wrappedJSObject' in subject) && + ('observersModuleSubjectWrapper' in subject.wrappedJSObject)) + subject = subject.wrappedJSObject.object; + + try { + this.listener({ + type: topic, + subject: subject, + data: data + }); + } + catch (error) { + console.exception(error); + } + } +}); + +const subscribers = ns(); + +function on(type, listener, strong) { + // Unless last optional argument is `true` we use a weak reference to a + // listener. + let weak = !strong; + // Take list of observers associated with given `listener` function. + let observers = subscribers(listener); + // If `observer` for the given `type` is not registered yet, then + // associate an `observer` and register it. + if (!(type in observers)) { + let observer = Observer(listener); + observers[type] = observer; + addObserver(observer, type, weak); + } +} +exports.on = on; + +function once(type, listener) { + // Note: this code assumes order in which listeners are called, which is fine + // as long as dispatch happens in same order as listener registration which + // is the case now. That being said we should be aware that this may break + // in a future if order will change. + on(type, listener); + on(type, function cleanup() { + off(type, listener); + off(type, cleanup); + }, true); +} +exports.once = once; + +function off(type, listener) { + // Take list of observers as with the given `listener`. + let observers = subscribers(listener); + // If `observer` for the given `type` is registered, then + // remove it & unregister. + if (type in observers) { + let observer = observers[type]; + delete observers[type]; + removeObserver(observer, type); + } +} +exports.off = off; diff --git a/tools/addon-sdk-1.12/lib/sdk/system/globals.js b/tools/addon-sdk-1.12/lib/sdk/system/globals.js new file mode 100644 index 0000000..df77295 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/system/globals.js @@ -0,0 +1,54 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "unstable" +}; + +let { Cc, Ci, CC } = require('chrome'); +let { PlainTextConsole } = require('../console/plain-text'); +let { stdout } = require('../system'); +let ScriptError = CC('@mozilla.org/scripterror;1', 'nsIScriptError'); +let consoleService = Cc['@mozilla.org/consoleservice;1'].getService(). + QueryInterface(Ci.nsIConsoleService); + +// On windows dump does not writes into stdout so cfx can't read thous dumps. +// To workaround this issue we write to a special file from which cfx will +// read and print to the console. +// For more details see: bug-673383 +exports.dump = stdout.write; + +// Bug 718230: We need to send console messages to stdout and JS Console +function forsakenConsoleDump(msg, level) { + stdout.write(msg); + + if (level === 'error') { + let error = ScriptError(); + msg = msg.replace(/^error: /, ''); + error.init(msg, null, null, 0, 0, 0, 'Add-on SDK'); + consoleService.logMessage(error); + } + else + consoleService.logStringMessage(msg); +}; +exports.console = new PlainTextConsole(forsakenConsoleDump); + +// Provide CommonJS `define` to allow authoring modules in a format that can be +// loaded both into jetpack and into browser via AMD loaders. +Object.defineProperty(exports, 'define', { + // `define` is provided as a lazy getter that binds below defined `define` + // function to the module scope, so that require, exports and module + // variables remain accessible. + configurable: true, + get: function() { + let sandbox = this; + return function define(factory) { + factory = Array.slice(arguments).pop(); + factory.call(sandbox, sandbox.require, sandbox.exports, sandbox.module); + } + } +}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/runtime.js b/tools/addon-sdk-1.12/lib/sdk/system/runtime.js index 845d146..e64b663 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/runtime.js +++ b/tools/addon-sdk-1.12/lib/sdk/system/runtime.js @@ -5,6 +5,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci } = require("chrome"); const runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/unload.js b/tools/addon-sdk-1.12/lib/sdk/system/unload.js index aba5923..4d2575b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/unload.js +++ b/tools/addon-sdk-1.12/lib/sdk/system/unload.js @@ -6,8 +6,15 @@ // // http://narwhaljs.org -var observers = []; -var unloaders = []; +module.metadata = { + "stability": "experimental" +}; + +const { on, off } = require('./events'); +const unloadSubject = require('@loader/unload'); + +const observers = []; +const unloaders = []; var when = exports.when = function when(observer) { if (observers.indexOf(observer) != -1) @@ -15,17 +22,6 @@ var when = exports.when = function when(observer) { observers.unshift(observer); }; -var send = exports.send = function send(reason, onError) { - onError = onError || console.exception; - observers.forEach(function (observer) { - try { - observer(reason); - } catch (e) { - onError(e); - } - }); -}; - var ensure = exports.ensure = function ensure(obj, destructorName) { if (!destructorName) destructorName = "unload"; @@ -49,15 +45,38 @@ var ensure = exports.ensure = function ensure(obj, destructorName) { } }; + // TODO: Find out why the order is inverted here. It seems that + // it may be causing issues! unloaders.push(unloadWrapper); obj[destructorName] = unloadWrapper; }; -when( - function(reason) { - unloaders.slice().forEach( - function(unloadWrapper) { - unloadWrapper(reason); - }); +function unload(reason) { + observers.forEach(function(observer) { + try { + observer(reason); + } + catch (error) { + console.exception(error); + } + }); +} + +when(function(reason) { + unloaders.slice().forEach(function(unloadWrapper) { + unloadWrapper(reason); }); +}); + +on('sdk:loader:destroy', function onunload({ subject, data: reason }) { + // If this loader is unload then `subject.wrappedJSObject` will be + // `destructor`. + if (subject.wrappedJSObject === unloadSubject) { + off('sdk:loader:destroy', onunload); + unload(reason); + } +// Note that we use strong reference to listener here to make sure it's not +// GC-ed, which may happen otherwise since nothing keeps reference to `onunolad` +// function. +}, true); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/xul-app.js b/tools/addon-sdk-1.12/lib/sdk/system/xul-app.js index 9272d88..6e8b4e8 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/xul-app.js +++ b/tools/addon-sdk-1.12/lib/sdk/system/xul-app.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + const {Cc, Ci} = require("chrome"); var appInfo = Cc["@mozilla.org/xre/app-info;1"] diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-timers.js b/tools/addon-sdk-1.12/lib/sdk/tabs.js index 90b26bf..f006073 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-timers.js +++ b/tools/addon-sdk-1.12/lib/sdk/tabs.js @@ -1,12 +1,10 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const timers = require("timers"); +'use strict'; -exports.testTimeout = function (test) { - test.waitUntilDone(); - timers.setTimeout(function () { - test.pass("timers.setTimeout works"); - test.done(); - }, 0); -} +module.metadata = { + 'stability': 'stable' +}; + +module.exports = require('./tabs/tabs'); diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/common.js b/tools/addon-sdk-1.12/lib/sdk/tabs/common.js new file mode 100644 index 0000000..dd5bb22 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/common.js @@ -0,0 +1,23 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { validateOptions } = require('../deprecated/api-utils'); + +function Options(options) { + if ('string' === typeof options) + options = { url: options }; + + return validateOptions(options, { + url: { is: ["string"] }, + inBackground: { is: ["undefined", "boolean"] }, + isPinned: { is: ["undefined", "boolean"] }, + onOpen: { is: ["undefined", "function"] }, + onClose: { is: ["undefined", "function"] }, + onReady: { is: ["undefined", "function"] }, + onActivate: { is: ["undefined", "function"] }, + onDeactivate: { is: ["undefined", "function"] } + }); +} +exports.Options = Options; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/events.js b/tools/addon-sdk-1.12/lib/sdk/tabs/events.js index efb8b45..eb99f40 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/events.js +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/events.js @@ -3,6 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const ON_PREFIX = "on"; const TAB_PREFIX = "Tab"; diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/helpers.js b/tools/addon-sdk-1.12/lib/sdk/tabs/helpers.js new file mode 100644 index 0000000..aaff5cb --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/helpers.js @@ -0,0 +1,17 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { getTabForContentWindow } = require('./utils'); +const { Tab } = require('./tab'); + +function getTabForWindow(win) { + let tab = getTabForContentWindow(win); + // We were unable to find the related tab! + if (!tab) + return null; + + return Tab({ tab: tab }); +} +exports.getTabForWindow = getTabForWindow; diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/namespace.js b/tools/addon-sdk-1.12/lib/sdk/tabs/namespace.js new file mode 100644 index 0000000..d359cee --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/namespace.js @@ -0,0 +1,9 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +let { ns } = require('../core/namespace'); + +exports.tabsNS = ns(); +exports.tabNS = ns(); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/observer.js b/tools/addon-sdk-1.12/lib/sdk/tabs/observer.js index e3854cb..19a048c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/observer.js +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/observer.js @@ -2,14 +2,18 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -"use strict"; +module.metadata = { + "stability": "unstable" +}; -const { EventEmitterTrait: EventEmitter } = require("../events"); -const { DOMEventAssembler } = require("../events/assembler"); -const { Trait } = require("../light-traits"); -const { getActiveTab, getTabs, getTabContainers } = require("./utils"); -const { browserWindowIterator, isBrowser } = require("../window-utils"); +const { EventEmitterTrait: EventEmitter } = require("../deprecated/events"); +const { DOMEventAssembler } = require("../deprecated/events/assembler"); +const { Trait } = require("../deprecated/light-traits"); +const { getActiveTab, getTabs, getTabContainer } = require("./utils"); +const { browserWindowIterator } = require("../deprecated/window-utils"); +const { isBrowser } = require('../window/utils'); const { observer: windowObserver } = require("../windows/observer"); const EVENTS = { @@ -46,34 +50,36 @@ const observer = Trait.compose(DOMEventAssembler, EventEmitter).create({ } }); -// Currently gecko does not dispatches any event on the previously selected +// Currently Gecko does not dispatch any event on the previously selected // tab before / after "TabSelect" is dispatched. In order to work around this // limitation we keep track of selected tab and emit "deactivate" event with // that before emitting "activate" on selected tab. var selectedTab = null; function onTabSelect(tab) { if (selectedTab !== tab) { - if (selectedTab) observer._emit("deactivate", selectedTab); - if (tab) observer._emit("activate", selectedTab = tab); + if (selectedTab) observer._emit('deactivate', selectedTab); + if (tab) observer._emit('activate', selectedTab = tab); } }; -observer.on("select", onTabSelect); +observer.on('select', onTabSelect); // We also observe opening / closing windows in order to add / remove it's // containers to the observed list. function onWindowOpen(chromeWindow) { if (!isBrowser(chromeWindow)) return; // Ignore if it's not a browser window. - getTabContainers(chromeWindow).forEach(function (container) { - observer.observe(container); - }); + observer.observe(getTabContainer(chromeWindow)); } windowObserver.on("open", onWindowOpen); function onWindowClose(chromeWindow) { if (!isBrowser(chromeWindow)) return; // Ignore if it's not a browser window. - getTabContainers(chromeWindow).forEach(function (container) { - observer.ignore(container); - }); + // Bug 751546: Emit `deactivate` event on window close immediatly + // Otherwise we are going to face "dead object" exception on `select` event + if (getActiveTab(chromeWindow) == selectedTab) { + observer._emit("deactivate", selectedTab); + selectedTab = null; + } + observer.ignore(getTabContainer(chromeWindow)); } windowObserver.on("close", onWindowClose); diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/tab-fennec.js b/tools/addon-sdk-1.12/lib/sdk/tabs/tab-fennec.js new file mode 100644 index 0000000..42bf91b --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/tab-fennec.js @@ -0,0 +1,141 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Cc, Ci } = require('chrome'); +const { Class } = require('../core/heritage'); +const { tabNS } = require('./namespace'); +const { EventTarget } = require('../event/target'); +const { activateTab, getTabTitle, setTabTitle, closeTab, getTabURL, + setTabURL, getOwnerWindow, getTabContentType } = require('./utils'); +const { emit } = require('../event/core'); +const { when: unload } = require('../system/unload'); + +const { EVENTS } = require('./events'); +const ERR_FENNEC_MSG = 'This method is not yet supported by Fennec'; + +const Tab = Class({ + extends: EventTarget, + initialize: function initialize(options) { + options = options.tab ? options : { tab: options }; + + EventTarget.prototype.initialize.call(this, options); + let tabInternals = tabNS(this); + + tabInternals.window = options.window || getOwnerWindow(options.tab); + tabInternals.tab = options.tab; + }, + + /** + * The title of the page currently loaded in the tab. + * Changing this property changes an actual title. + * @type {String} + */ + get title() getTabTitle(tabNS(this).tab), + set title(title) setTabTitle(tabNS(this).tab, title), + + /** + * Location of the page currently loaded in this tab. + * Changing this property will loads page under under the specified location. + * @type {String} + */ + get url() getTabURL(tabNS(this).tab), + set url(url) setTabURL(tabNS(this).tab, url), + + /** + * URI of the favicon for the page currently loaded in this tab. + * @type {String} + */ + get favicon() { + // TODO: provide the real favicon when it is available + console.error(ERR_FENNEC_MSG); + + // return 16x16 blank default + return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAEklEQVQ4jWNgGAWjYBSMAggAAAQQAAF/TXiOAAAAAElFTkSuQmCC'; + }, + + getThumbnail: function() { + // TODO: implement! + console.error(ERR_FENNEC_MSG); + + // return 80x45 blank default + return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAAAtCAYAAAA5reyyAAAAJElEQVRoge3BAQEAAACCIP+vbkhAAQAAAAAAAAAAAAAAAADXBjhtAAGQ0AF/AAAAAElFTkSuQmCC'; + }, + + /** + * The index of the tab relative to other tabs in the application window. + * Changing this property will change order of the actual position of the tab. + * @type {Number} + */ + get index() { + let tabs = tabNS(this).window.BrowserApp.tabs; + let tab = tabNS(this).tab; + for (var i = tabs.length; i >= 0; i--) { + if (tabs[i] === tab) + return i; + } + return null; + }, + set index(value) { + console.error(ERR_FENNEC_MSG); // TODO + }, + + /** + * Whether or not tab is pinned (Is an app-tab). + * @type {Boolean} + */ + get isPinned() { + console.error(ERR_FENNEC_MSG); // TODO + return false; // TODO + }, + pin: function pin() { + console.error(ERR_FENNEC_MSG); // TODO + }, + unpin: function unpin() { + console.error(ERR_FENNEC_MSG); // TODO + }, + + /** + * Returns the MIME type that the document loaded in the tab is being + * rendered as. + * @type {String} + */ + get contentType() getTabContentType(tabNS(this).tab), + + /** + * Create a worker for this tab, first argument is options given to Worker. + * @type {Worker} + */ + attach: function attach(options) { + // BUG 792946 https://bugzilla.mozilla.org/show_bug.cgi?id=792946 + // TODO: fix this circular dependency + let { Worker } = require('./worker'); + return Worker(options, tabNS(this).tab.browser.contentWindow); + }, + + /** + * Make this tab active. + */ + activate: function activate() { + activateTab(tabNS(this).tab, tabNS(this).window); + }, + + /** + * Close the tab + */ + close: function close(callback) { + if (callback) + this.once(EVENTS.close.name, callback); + + closeTab(tabNS(this).tab); + }, + + /** + * Reload the tab + */ + reload: function reload() { + tabNS(this).tab.browser.reload(); + } +}); +exports.Tab = Tab; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/tab.js b/tools/addon-sdk-1.12/lib/sdk/tabs/tab-firefox.js index 246834f..5a36302 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/tab.js +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/tab-firefox.js @@ -1,18 +1,16 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; +'use strict'; -const { Ci } = require('chrome'); -const { Trait } = require("../traits"); -const { EventEmitter } = require("../events"); -const { validateOptions } = require("../api-utils"); -const { defer } = require("../functional"); +const { Trait } = require("../deprecated/traits"); +const { EventEmitter } = require("../deprecated/events"); +const { defer } = require("../lang/functional"); const { EVENTS } = require("./events"); -const { getThumbnailURIForWindow } = require("../utils/thumbnail"); -const { getFaviconURIForLocation } = require("../utils/data"); - - +const { getThumbnailURIForWindow } = require("../content/thumbnail"); +const { getFaviconURIForLocation } = require("../io/data"); +const { activateTab, getOwnerWindow, getBrowserForTab, getTabTitle, setTabTitle, + getTabURL, setTabURL, getTabContentType } = require('./utils'); // Array of the inner instances of all the wrapped tabs. const TABS = []; @@ -34,7 +32,8 @@ const TabTrait = Trait.compose(EventEmitter, { constructor: function Tab(options) { this._onReady = this._onReady.bind(this); this._tab = options.tab; - let window = this.window = options.window; + let window = this.window = options.window || getOwnerWindow(this._tab); + // Setting event listener if was passed. for each (let type in EVENTS) { let listener = options[type.listener]; @@ -57,8 +56,7 @@ const TabTrait = Trait.compose(EventEmitter, { }, destroy: function destroy() { this._removeAllListeners(); - this._browser.removeEventListener(EVENTS.ready.dom, this._onReady, - true); + this._browser.removeEventListener(EVENTS.ready.dom, this._onReady, true); }, /** @@ -82,11 +80,11 @@ const TabTrait = Trait.compose(EventEmitter, { /** * Browser DOM element where page of this tab is currently loaded. */ - get _browser() this._window.gBrowser.getBrowserForTab(this._tab), + get _browser() getBrowserForTab(this._tab), /** * Window DOM element containing this tab. */ - get _window() this._tab.ownerDocument.defaultView, + get _window() getOwnerWindow(this._tab), /** * Document object of the page that is currently loaded in this tab. */ @@ -101,20 +99,23 @@ const TabTrait = Trait.compose(EventEmitter, { * Changing this property changes an actual title. * @type {String} */ - get title() this._contentDocument.title, - set title(value) this._contentDocument.title = String(value), + get title() getTabTitle(this._tab), + set title(title) setTabTitle(this._tab, title), + + /** + * Returns the MIME type that the document loaded in the tab is being + * rendered as. + * @type {String} + */ + get contentType() getTabContentType(this._tab), + /** * Location of the page currently loaded in this tab. * Changing this property will loads page under under the specified location. * @type {String} */ - get url() String(this._browser.currentURI.spec), - set url(value) this._changeLocation(String(value)), - // "TabOpen" event is fired when it's still "about:blank" is loaded in the - // changing `location` property of the `contentDocument` has no effect since - // seems to be either ignored or overridden by internal listener, there for - // location change is enqueued for the next turn of event loop. - _changeLocation: defer(function(url) this._browser.loadURI(url)), + get url() getTabURL(this._tab), + set url(url) setTabURL(this._tab, url), /** * URI of the favicon for the page currently loaded in this tab. * @type {String} @@ -149,30 +150,26 @@ const TabTrait = Trait.compose(EventEmitter, { unpin: function unpin() { this._window.gBrowser.unpinTab(this._tab); }, - + /** * Create a worker for this tab, first argument is options given to Worker. * @type {Worker} */ attach: function attach(options) { - let { Worker } = require("../content/worker"); - options.window = this._contentWindow; - let worker = Worker(options); - worker.once("detach", function detach() { - worker.destroy(); - }); - return worker; + // BUG 792946 https://bugzilla.mozilla.org/show_bug.cgi?id=792946 + // TODO: fix this circular dependency + let { Worker } = require('./worker'); + return Worker(options, this._contentWindow); }, - + /** * Make this tab active. - * Please note: That this function is called synchronous since in E10S that + * Please note: That this function is called asynchronous since in E10S that * will be the case. Besides this function is called from a constructor where * we would like to return instance before firing a 'TabActivated' event. */ activate: defer(function activate() { - if (this._window) // Ignore if window is closed by the time this is invoked. - this._window.gBrowser.selectedTab = this._tab; + activateTab(this._tab); }), /** * Close the tab @@ -202,63 +199,3 @@ function Tab(options) { } Tab.prototype = TabTrait.prototype; exports.Tab = Tab; - -function Options(options) { - if ("string" === typeof options) - options = { url: options }; - - return validateOptions(options, { - url: { is: ["string"] }, - inBackground: { is: ["undefined", "boolean"] }, - isPinned: { is: ["undefined", "boolean"] }, - onOpen: { is: ["undefined", "function"] }, - onClose: { is: ["undefined", "function"] }, - onReady: { is: ["undefined", "function"] }, - onActivate: { is: ["undefined", "function"] }, - onDeactivate: { is: ["undefined", "function"] } - }); -} -exports.Options = Options; - - -exports.getTabForWindow = function (win) { - // Get browser window - let topWindow = win.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIWebNavigation) - .QueryInterface(Ci.nsIDocShellTreeItem) - .rootTreeItem - .QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindow); - if (!topWindow.gBrowser) return null; - - // Get top window object, in case we are in a content iframe - let topContentWindow; - try { - topContentWindow = win.top; - } catch(e) { - // It may throw if win is not a valid content window - return null; - } - - function getWindowID(obj) { - return obj.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils) - .currentInnerWindowID; - } - - // Search for related Tab - let topWindowId = getWindowID(topContentWindow); - for (let i = 0; i < topWindow.gBrowser.browsers.length; i++) { - let w = topWindow.gBrowser.browsers[i].contentWindow; - if (getWindowID(w) == topWindowId) { - return Tab({ - // TODO: api-utils should not depend on addon-kit! - window: require("addon-kit/windows").BrowserWindow({ window: topWindow }), - tab: topWindow.gBrowser.tabs[i] - }); - } - } - - // We were unable to find the related tab! - return null; -} diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/tab.js b/tools/addon-sdk-1.12/lib/sdk/tabs/tab.js new file mode 100644 index 0000000..420baee --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/tab.js @@ -0,0 +1,21 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'unstable' +}; + +if (require('../system/xul-app').is('Firefox')) { + module.exports = require('./tab-firefox'); +} +else if (require('../system/xul-app').is('Fennec')) { + module.exports = require('./tab-fennec'); +} +else { + throw new Error([ + 'The tabs module currently supports only Firefox & Fennec. In the future', + ' we would like it to support other applications, however.' + ].join('')); +} diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/tabs-firefox.js b/tools/addon-sdk-1.12/lib/sdk/tabs/tabs-firefox.js new file mode 100644 index 0000000..92834c2 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/tabs-firefox.js @@ -0,0 +1,26 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +// TODO: BUG 792670 - remove dependency below +const { browserWindows } = require('../windows'); +const { tabs } = require('../windows/tabs-firefox'); + +Object.defineProperties(tabs, { + open: { value: function open(options) { + if (options.inNewWindow) + // `tabs` option is under review and may be removed. + return browserWindows.open({ tabs: [ options ] }); + // Open in active window if new window was not required. + return browserWindows.activeWindow.tabs.open(options); + }} +}); + +// Workaround for bug 674195. Freezing objects from other compartments fail, +// so we use `Object.freeze` from the same component as objects +// `hasOwnProperty`. Since `hasOwnProperty` here will be from other component +// we override it to support our workaround. +module.exports = Object.create(tabs, { + isPrototypeOf: { value: Object.prototype.isPrototypeOf } +}); diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/tabs.js b/tools/addon-sdk-1.12/lib/sdk/tabs/tabs.js new file mode 100644 index 0000000..fcb3868 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/tabs.js @@ -0,0 +1,21 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'unstable' +}; + +if (require('../system/xul-app').is('Firefox')) { + module.exports = require('./tabs-firefox'); +} +else if (require('../system/xul-app').is('Fennec')) { + module.exports = require('../windows/tabs-fennec').tabs; +} +else { + throw new Error([ + 'The tabs module currently supports only Firefox & Fennec. In the future', + ' we would like it to support other applications, however.' + ].join('')); +} diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/utils.js b/tools/addon-sdk-1.12/lib/sdk/tabs/utils.js new file mode 100644 index 0000000..d923e4b --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/utils.js @@ -0,0 +1,222 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'unstable' +}; + +const { defer } = require("../lang/functional"); +const { windows } = require('../window/utils'); +const { Ci } = require('chrome'); + +function activateTab(tab, window) { + let gBrowser = getTabBrowserForTab(tab); + + // normal case + if (gBrowser) { + gBrowser.selectedTab = tab; + } + // fennec ? + else if (window && window.BrowserApp) { + window.BrowserApp.selectTab(tab); + } + return null; +} +exports.activateTab = activateTab; + +function getTabBrowser(window) { + return window.gBrowser; +} +exports.getTabBrowser = getTabBrowser; + +function getTabContainer(window) { + return getTabBrowser(window).tabContainer; +} +exports.getTabContainer = getTabContainer; + +function getTabs(window) { + // fennec + if (window.BrowserApp) + return window.BrowserApp.tabs; + + // firefox - default + return Array.slice(getTabContainer(window).children); +} +exports.getTabs = getTabs; + +function getActiveTab(window) { + return window.gBrowser.selectedTab; +} +exports.getActiveTab = getActiveTab; + +function getOwnerWindow(tab) { + // normal case + if (tab.ownerDocument) + return tab.ownerDocument.defaultView; + + // try fennec case + return getWindowHoldingTab(tab); +} +exports.getOwnerWindow = getOwnerWindow; + +// fennec +function getWindowHoldingTab(rawTab) { + for each (let window in windows()) { + // this function may be called when not using fennec + if (!window.BrowserApp) + continue; + + for each (let tab in window.BrowserApp.tabs) { + if (tab === rawTab) + return window; + } + } + + return null; +} + +function openTab(window, url, options) { + options = options || {}; + + // fennec? + if (window.BrowserApp) { + return window.BrowserApp.addTab(url, { + selected: options.inBackground ? false : true, + pinned: options.isPinned || false + }); + } + return window.gBrowser.addTab(url); +}; +exports.openTab = openTab; + +function isTabOpen(tab) { + // try normal case then fennec case + return !!((tab.linkedBrowser) || getWindowHoldingTab(tab)); +} +exports.isTabOpen = isTabOpen; + +function closeTab(tab) { + let gBrowser = getTabBrowserForTab(tab); + // normal case? + if (gBrowser) + return gBrowser.removeTab(tab); + + let window = getWindowHoldingTab(tab); + // fennec? + if (window && window.BrowserApp) + return window.BrowserApp.closeTab(tab); + return null; +} +exports.closeTab = closeTab; + +function getURI(tab) { + if (tab.browser) // fennec + return tab.browser.currentURI.spec; + return tab.linkedBrowser.currentURI.spec; +} +exports.getURI = getURI; + +function getTabBrowserForTab(tab) { + let outerWin = getOwnerWindow(tab); + if (outerWin) + return getOwnerWindow(tab).gBrowser; + return null; +} +exports.getTabBrowserForTab = getTabBrowserForTab; + +function getBrowserForTab(tab) { + if (tab.browser) // fennec + return tab.browser; + + return tab.linkedBrowser; +} +exports.getBrowserForTab = getBrowserForTab; + +function getTabTitle(tab) { + return getBrowserForTab(tab).contentDocument.title || tab.label || ""; +} +exports.getTabTitle = getTabTitle; + +function setTabTitle(tab, title) { + title = String(title); + if (tab.browser) + tab.browser.contentDocument.title = title; + tab.label = String(title); +} +exports.setTabTitle = setTabTitle; + +function getTabContentWindow(tab) { + return getBrowserForTab(tab).contentWindow; +} +exports.getTabContentWindow = getTabContentWindow; + +function getTabForContentWindow(window) { + // Retrieve the topmost frame container. It can be either <xul:browser>, + // <xul:iframe/> or <html:iframe/>. But in our case, it should be xul:browser. + let browser = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShell) + .chromeEventHandler; + // Is null for toplevel documents + if (!browser) + return false; + // Retrieve the owner window, should be browser.xul one + let chromeWindow = browser.ownerDocument.defaultView; + + // Ensure that it is top-level browser window. + // We need extra checks because of Mac hidden window that has a broken + // `gBrowser` global attribute. + if ('gBrowser' in chromeWindow && chromeWindow.gBrowser && + 'browsers' in chromeWindow.gBrowser) { + // Looks like we are on Firefox Desktop + // Then search for the position in tabbrowser in order to get the tab object + let browsers = chromeWindow.gBrowser.browsers; + let i = browsers.indexOf(browser); + if (i !== -1) + return chromeWindow.gBrowser.tabs[i]; + return null; + } + else if ('BrowserApp' in chromeWindow) { + // Looks like we are on Firefox Mobile + return chromeWindow.BrowserApp.getTabForWindow(window) + } + + return null; +} +exports.getTabForContentWindow = getTabForContentWindow; + +function getTabURL(tab) { + if (tab.browser) // fennec + return String(tab.browser.currentURI.spec); + return String(getBrowserForTab(tab).currentURI.spec); +} +exports.getTabURL = getTabURL; + +function setTabURL(tab, url) { + url = String(url); + if (tab.browser) + return tab.browser.loadURI(url); + return getBrowserForTab(tab).loadURI(url); +} +// "TabOpen" event is fired when it's still "about:blank" is loaded in the +// changing `location` property of the `contentDocument` has no effect since +// seems to be either ignored or overridden by internal listener, there for +// location change is enqueued for the next turn of event loop. +exports.setTabURL = defer(setTabURL); + +function getTabContentType(tab) { + return getBrowserForTab(tab).contentDocument.contentType; +} +exports.getTabContentType = getTabContentType; + +function getSelectedTab(window) { + if (window.BrowserApp) // fennec? + return window.BrowserApp.selectedTab; + if (window.gBrowser) + return window.gBrowser.selectedTab; + return null; +} +exports.getSelectedTab = getSelectedTab; diff --git a/tools/addon-sdk-1.12/lib/sdk/tabs/worker.js b/tools/addon-sdk-1.12/lib/sdk/tabs/worker.js new file mode 100644 index 0000000..d2ba336 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/tabs/worker.js @@ -0,0 +1,17 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const ContentWorker = require('../content/worker').Worker; + +function Worker(options, window) { + options.window = window; + + let worker = ContentWorker(options); + worker.once("detach", function detach() { + worker.destroy(); + }); + return worker; +} +exports.Worker = Worker;
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/test.js b/tools/addon-sdk-1.12/lib/sdk/test.js index e69a2f4..0a322d6 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/test.js +++ b/tools/addon-sdk-1.12/lib/sdk/test.js @@ -5,8 +5,12 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const BaseAssert = require("./test/assert").Assert; -const { isFunction, isObject } = require("./type"); +const { isFunction, isObject } = require("./lang/type"); function extend(target) { let descriptor = {} diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/test/assert.js b/tools/addon-sdk-1.12/lib/sdk/test/assert.js index fa40807..5eca7d4 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/test/assert.js +++ b/tools/addon-sdk-1.12/lib/sdk/test/assert.js @@ -4,8 +4,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { isFunction, isNull, isObject, isString, isRegExp, isArray, isDate, - isPrimitive, isUndefined, instanceOf, source } = require("../type"); +module.metadata = { + "stability": "unstable" +}; + +const { isFunction, isNull, isObject, isString, + isRegExp, isArray, isDate, isPrimitive, + isUndefined, instanceOf, source } = require("../lang/type"); /** * The `AssertionError` is defined in assert. @@ -59,7 +64,20 @@ function Assert(logger) { } Assert.prototype = { fail: function fail(e) { - this._log.fail(e.message); + if (!e || typeof(e) !== 'object') { + this._log.fail(e); + return; + } + let message = e.message; + if ('operator' in e) { + message += [ + " -", + source(e.expected), + e.operator, + source(e.actual) + ].join(" "); + } + this._log.fail(message); }, pass: function pass(message) { this._log.pass(message); diff --git a/tools/addon-sdk-1.7/packages/test-harness/lib/harness.js b/tools/addon-sdk-1.12/lib/sdk/test/harness.js index e1b1105..46584ca 100644 --- a/tools/addon-sdk-1.7/packages/test-harness/lib/harness.js +++ b/tools/addon-sdk-1.12/lib/sdk/test/harness.js @@ -5,15 +5,24 @@ "use strict"; const { Cc,Ci } = require("chrome"); -const { Loader } = require("@loader") -const memory = require('api-utils/memory'); +const { Loader } = require('./loader'); +const { setTimeout } = require('../timers'); +const memory = require('../deprecated/memory'); +const { PlainTextConsole } = require("../console/plain-text"); +const { when: unload } = require("../system/unload"); +const { format } = require("../console/traceback"); +const system = require("../system"); + +// Trick manifest builder to make it think we need these modules ? +const unit = require("../deprecated/unit-test"); +const test = require("../test"); +const url = require("../url"); var cService = Cc['@mozilla.org/consoleservice;1'].getService() .QueryInterface(Ci.nsIConsoleService); -// Cuddlefish loader for the sandbox in which we load and -// execute tests. -var sandbox; +// Cuddlefish loader in which we load and execute tests. +var loader; // Function to call when we're done running tests. var onDone; @@ -24,15 +33,15 @@ var print; // How many more times to run all tests. var iterationsLeft; -// Only tests in files whose names match this regexp filter will be run. -var filter; - // Whether to report memory profiling information. var profileMemory; // Whether we should stop as soon as a test reports a failure. var stopOnError; +// Function to call to retrieve a list of tests to execute +var findAndRunTests; + // Combined information from all test runs. var results = { passed: 0, @@ -164,27 +173,24 @@ function showResults() { ); } - print("\n"); - var total = results.passed + results.failed; - print(results.passed + " of " + total + " tests passed.\n"); onDone(results); } function cleanup() { try { - for (let name in sandbox.modules) - memory.track(sandbox.modules[name], + for (let name in loader.modules) + memory.track(loader.modules[name], "module global scope: " + name); - memory.track(sandbox, "Cuddlefish Loader"); + memory.track(loader, "Cuddlefish Loader"); if (profileMemory) { gWeakrefInfo = [{ weakref: info.weakref, bin: info.bin } for each (info in memory.getObjects())]; } - sandbox.unload(); + loader.unload(); - if (sandbox.globals.console.errorsLogged && !results.failed) { + if (loader.globals.console.errorsLogged && !results.failed) { results.failed++; console.error("warnings and/or errors were logged."); } @@ -198,7 +204,7 @@ function cleanup() { } consoleListener.errorsLogged = 0; - sandbox = null; + loader = null; memory.gc(); } catch (e) { @@ -207,7 +213,7 @@ function cleanup() { console.exception(e); }; - require("api-utils/timer").setTimeout(showResults, 1); + setTimeout(showResults, 1); } function nextIteration(tests) { @@ -232,23 +238,24 @@ function nextIteration(tests) { } if (iterationsLeft && (!stopOnError || results.failed == 0)) { - let require = Loader.require.bind(sandbox, module.path); - require("api-utils/unit-test").findAndRunTests({ - testOutOfProcess: require('@packaging').enableE10s, - testInProcess: true, - stopOnError: stopOnError, - filter: filter, - onDone: nextIteration - }); + // Pass the loader which has a hooked console that doesn't dispatch + // errors to the JS console and avoid firing false alarm in our + // console listener + findAndRunTests(loader, nextIteration); } else { - require("api-utils/timer").setTimeout(cleanup, 0); + setTimeout(cleanup, 0); } } var POINTLESS_ERRORS = [ - "Invalid chrome URI:", - "OpenGL LayerManager Initialized Succesfully." + 'Invalid chrome URI:', + 'OpenGL LayerManager Initialized Succesfully.', + '[JavaScript Error: "TelemetryStopwatch:', + '[JavaScript Warning: "ReferenceErrorL reference to undefined property', + '[Javascript Warning: "Error: Failed to preserve wrapper of wrapped ' + + 'native weak map key', + '[JavaScript Warning: "Duplicate resource declaration for' ]; var consoleListener = { @@ -289,36 +296,32 @@ function TestRunnerConsole(base, options) { var runTests = exports.runTests = function runTests(options) { iterationsLeft = options.iterations; - filter = options.filter; profileMemory = options.profileMemory; stopOnError = options.stopOnError; onDone = options.onDone; print = options.print; + findAndRunTests = options.findAndRunTests; try { cService.registerListener(consoleListener); - - var ptc = require("api-utils/plain-text-console"); - var url = require("api-utils/url"); - var system = require("api-utils/system"); - print("Running tests on " + system.name + " " + system.version + "/Gecko " + system.platformVersion + " (" + system.id + ") under " + system.platform + "/" + system.architecture + ".\n"); - sandbox = Loader.new(require("@packaging")); - Object.defineProperty(sandbox.globals, 'console', { - value: new TestRunnerConsole(new ptc.PlainTextConsole(print), options) + + loader = Loader(module, { + console: new TestRunnerConsole(new PlainTextConsole(print), options) }); nextIteration(); } catch (e) { - print(require("api-utils/traceback").format(e) + "\n" + e + "\n"); + print(format(e) + "\n" + e + "\n"); onDone({passed: 0, failed: 1}); } }; -require("api-utils/unload").when(function() { +unload(function() { cService.unregisterListener(consoleListener); }); + diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/httpd.js b/tools/addon-sdk-1.12/lib/sdk/test/httpd.js index 7f6a363..48d3516 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/httpd.js +++ b/tools/addon-sdk-1.12/lib/sdk/test/httpd.js @@ -10,11 +10,13 @@ * httpd.js. */ +module.metadata = { + "stability": "experimental" +}; -var {components,Cc,Ci,Cr,Cu} = require("chrome"); -components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +const { components, CC, Cc, Ci, Cr, Cu } = require("chrome"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -const CC = components.Constructor; const PR_UINT32_MAX = Math.pow(2, 32) - 1; @@ -483,12 +485,18 @@ nsHttpServer.prototype = this._host = host; // The listen queue needs to be long enough to handle - // network.http.max-connections-per-server concurrent connections, + // network.http.max-persistent-connections-per-server concurrent connections, // plus a safety margin in case some other process is talking to // the server as well. var prefs = getRootPrefBranch(); - var maxConnections = - prefs.getIntPref("network.http.max-connections-per-server") + 5; + var maxConnections; + try { + // Bug 776860: The original pref was removed in favor of this new one: + maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5; + } + catch(e) { + maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5; + } try { diff --git a/tools/addon-sdk-1.12/lib/sdk/test/loader.js b/tools/addon-sdk-1.12/lib/sdk/test/loader.js new file mode 100644 index 0000000..282cf5e --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/test/loader.js @@ -0,0 +1,28 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Loader, resolveURI, Require, + unload, override, descriptor } = require('../loader/cuddlefish'); + +exports.Loader = function(module, globals, packaging) { + let options = packaging || require("@loader/options"); + options = override(options, { + globals: override(require('../system/globals'), globals || {}) + }); + + let loader = Loader(options); + return Object.create(loader, descriptor({ + require: Require(loader, module), + sandbox: function(id) { + let requirement = loader.resolve(id, module.id); + let uri = resolveURI(requirement, loader.mapping); + return loader.sandboxes[uri]; + }, + unload: function(reason) { + unload(loader, reason); + } + })); +}; diff --git a/tools/addon-sdk-1.12/lib/sdk/test/runner.js b/tools/addon-sdk-1.12/lib/sdk/test/runner.js new file mode 100644 index 0000000..4db9aca --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/test/runner.js @@ -0,0 +1,150 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +var obsvc = require("../deprecated/observer-service"); +var { exit, stdout } = require("../system"); +var cfxArgs = require("@test/options"); +var { Cc, Ci} = require("chrome"); + +function runTests(findAndRunTests) { + var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"] + .getService(Ci.nsIWindowWatcher); + + let ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; + let msg = 'Running tests...'; + let markup = '<?xml version="1.0"?><window xmlns="' + ns + + '" windowtype="test:runner"><label>' + msg + '</label></window>'; + let url = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + escape(markup); + + + var window = ww.openWindow(null, url, "harness", "centerscreen", null); + + var harness = require("./harness"); + + function onDone(tests) { + stdout.write("\n"); + var total = tests.passed + tests.failed; + stdout.write(tests.passed + " of " + total + " tests passed.\n"); + + window.close(); + if (tests.failed == 0) { + if (tests.passed === 0) + stdout.write("No tests were run\n"); + exit(0); + } else { + printFailedTests(tests, cfxArgs.verbose, stdout.write); + exit(1); + } + }; + + // We have to wait for this window to be fully loaded *and* focused + // in order to avoid it to mess with our various window/focus tests. + // We are first waiting for our window to be fully loaded before ensuring + // that it will take the focus, and then we wait for it to be focused. + window.addEventListener("load", function onload() { + window.removeEventListener("load", onload, true); + + window.addEventListener("focus", function onfocus() { + window.removeEventListener("focus", onfocus, true); + // Finally, we have to run test on next cycle, otherwise XPCOM components + // are not correctly updated. + // For ex: nsIFocusManager.getFocusedElementForWindow may throw + // NS_ERROR_ILLEGAL_VALUE exception. + require("../timers").setTimeout(function () { + harness.runTests({ + findAndRunTests: findAndRunTests, + iterations: cfxArgs.iterations || 1, + filter: cfxArgs.filter, + profileMemory: cfxArgs.profileMemory, + stopOnError: cfxArgs.stopOnError, + verbose: cfxArgs.verbose, + print: stdout.write, + onDone: onDone + }); + }, 0); + }, true); + window.focus(); + }, true); +} + +function printFailedTests(tests, verbose, print) { + if (!verbose) + return; + + let iterationNumber = 0; + let singleIteration = tests.testRuns.length == 1; + let padding = singleIteration ? "" : " "; + + print("\nThe following tests failed:\n"); + + for each (let testRun in tests.testRuns) { + iterationNumber++; + + if (!singleIteration) + print(" Iteration " + iterationNumber + ":\n"); + + for each (let test in testRun) { + if (test.failed > 0) { + print(padding + " " + test.name + ": " + test.errors +"\n"); + } + } + print("\n"); + } +} + +function main() { + var testsStarted = false; + + if (!testsStarted) { + testsStarted = true; + runTests(function findAndRunTests(loader, nextIteration) { + loader.require("../deprecated/unit-test").findAndRunTests({ + testOutOfProcess: false, + testInProcess: true, + stopOnError: cfxArgs.stopOnError, + filter: cfxArgs.filter, + onDone: nextIteration + }); + }); + } +}; + +if (require.main === module) + main(); + +exports.runTestsFromModule = function runTestsFromModule(module) { + let id = module.id; + // Make a copy of exports as it may already be frozen by module loader + let exports = {}; + Object.keys(module.exports).forEach(function(key) { + exports[key] = module.exports[key]; + }); + + runTests(function findAndRunTests(loader, nextIteration) { + // Consider that all these tests are CommonJS ones + loader.require('../test').run(exports); + + // Reproduce what is done in unit-test-finder.findTests() + let tests = []; + for each (let name in Object.keys(exports).sort()) { + tests.push({ + setup: exports.setup, + teardown: exports.teardown, + testFunction: exports[name], + name: id + "." + name + }); + } + + // Reproduce what is done by unit-test.findAndRunTests() + var { TestRunner } = loader.require("../deprecated/unit-test"); + var runner = new TestRunner(); + runner.startMany({ + tests: tests, + stopOnError: cfxArgs.stopOnError, + onDone: nextIteration + }); + }); +} diff --git a/tools/addon-sdk-1.12/lib/sdk/test/tmp-file.js b/tools/addon-sdk-1.12/lib/sdk/test/tmp-file.js new file mode 100644 index 0000000..634d2f1 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/test/tmp-file.js @@ -0,0 +1,73 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const { Cc, Ci } = require("chrome"); + +const system = require("sdk/system"); +const file = require("sdk/io/file"); +const unload = require("sdk/system/unload"); + +// Retrieve the path to the OS temporary directory: +const tmpDir = require("sdk/system").pathFor("TmpD"); + +// List of all tmp file created +let files = []; + +// Remove all tmp files on addon disabling +unload.when(function () { + files.forEach(function (path){ + // Catch exception in order to avoid leaking following files + try { + if (file.exists(path)) + file.remove(path); + } + catch(e) { + console.exception(e); + } + }); +}); + +// Utility function that synchronously reads local resource from the given +// `uri` and returns content string. Read in binary mode. +function readBinaryURI(uri) { + let ioservice = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); + let channel = ioservice.newChannel(uri, "UTF-8", null); + let stream = Cc["@mozilla.org/binaryinputstream;1"]. + createInstance(Ci.nsIBinaryInputStream); + stream.setInputStream(channel.open()); + + let data = ""; + while (true) { + let available = stream.available(); + if (available <= 0) + break; + data += stream.readBytes(available); + } + stream.close(); + + return data; +} + +// Create a temporary file from a given string and returns its path +exports.createFromString = function createFromString(data, tmpName) { + let filename = (tmpName ? tmpName : "tmp-file") + "-" + (new Date().getTime()); + let path = file.join(tmpDir, filename); + + let tmpFile = file.open(path, "wb"); + tmpFile.write(data); + tmpFile.close(); + + // Register tmp file path + files.push(path); + + return path; +} + +// Create a temporary file from a given URL and returns its path +exports.createFromURL = function createFromURL(url, tmpName) { + let data = readBinaryURI(url); + return exports.createFromString(data, tmpName); +} + diff --git a/tools/addon-sdk-1.12/lib/sdk/timers.js b/tools/addon-sdk-1.12/lib/sdk/timers.js new file mode 100644 index 0000000..bc72717 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/timers.js @@ -0,0 +1,53 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + "stability": "deprecated" +}; + +const { CC, Ci } = require('chrome'); +const { when: unload } = require('./system/unload'); + +const { TYPE_ONE_SHOT, TYPE_REPEATING_SLACK } = Ci.nsITimer; +const Timer = CC('@mozilla.org/timer;1', 'nsITimer'); +const timers = Object.create(null); + +// Last timer id. +let lastID = 0; + +// Sets typer either by timeout or by interval +// depending on a given type. +function setTimer(type, callback, delay) { + let id = ++ lastID; + let timer = timers[id] = Timer(); + let args = Array.slice(arguments, 3); + timer.initWithCallback({ + notify: function notify() { + try { + if (type === TYPE_ONE_SHOT) + delete timers[id]; + callback.apply(null, args); + } + catch(error) { + console.exception(error); + } + } + }, delay || 0, type); + return id; +} + +function unsetTimer(id) { + let timer = timers[id]; + delete timers[id]; + if (timer) + timer.cancel(); +} + +exports.setTimeout = setTimer.bind(null, TYPE_ONE_SHOT); +exports.setInterval = setTimer.bind(null, TYPE_REPEATING_SLACK); +exports.clearTimeout = unsetTimer.bind(null); +exports.clearInterval = unsetTimer.bind(null); + +unload(function() { Object.keys(timers).forEach(unsetTimer) }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/url.js b/tools/addon-sdk-1.12/lib/sdk/url.js index 29fc12c..3581398 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/url.js +++ b/tools/addon-sdk-1.12/lib/sdk/url.js @@ -4,7 +4,14 @@ "use strict"; -const {Cc,Ci,Cr} = require("chrome"); +module.metadata = { + "stability": "experimental" +}; + +const { Cc, Ci, Cr } = require("chrome"); + +const { Class } = require("./core/heritage"); +const base64 = require("./base64"); var ios = Cc['@mozilla.org/network/io-service;1'] .getService(Ci.nsIIOService); @@ -111,3 +118,119 @@ function URL(url, base) { URL.prototype = Object.create(String.prototype); exports.URL = URL; + +/** + * Parse and serialize a Data URL. + * + * See: http://tools.ietf.org/html/rfc2397 + * + * Note: Could be extended in the future to decode / encode automatically binary + * data. + */ +const DataURL = Class({ + + get base64 () { + return "base64" in this.parameters; + }, + + set base64 (value) { + if (value) + this.parameters["base64"] = ""; + else + delete this.parameters["base64"]; + }, + /** + * Initialize the Data URL object. If a uri is given, it will be parsed. + * + * @param {String} [uri] The uri to parse + * + * @throws {URIError} if the Data URL is malformed + */ + initialize: function(uri) { + // Due to bug 751834 it is not possible document and define these + // properties in the prototype. + + /** + * An hashmap that contains the parameters of the Data URL. By default is + * empty, that accordingly to RFC is equivalent to {"charset" : "US-ASCII"} + */ + this.parameters = {}; + + /** + * The MIME type of the data. By default is empty, that accordingly to RFC + * is equivalent to "text/plain" + */ + this.mimeType = ""; + + /** + * The string that represent the data in the Data URL + */ + this.data = ""; + + if (typeof uri === "undefined") + return; + + uri = String(uri); + + let matches = uri.match(/^data:([^,]*),(.*)$/i); + + if (!matches) + throw new URIError("Malformed Data URL: " + uri); + + let mediaType = matches[1].trim(); + + this.data = decodeURIComponent(matches[2].trim()); + + if (!mediaType) + return; + + let parametersList = mediaType.split(";"); + + this.mimeType = parametersList.shift().trim(); + + for (let parameter, i = 0; parameter = parametersList[i++];) { + let pairs = parameter.split("="); + let name = pairs[0].trim(); + let value = pairs.length > 1 ? decodeURIComponent(pairs[1].trim()) : ""; + + this.parameters[name] = value; + } + + if (this.base64) + this.data = base64.decode(this.data); + + }, + + /** + * Returns the object as a valid Data URL string + * + * @returns {String} The Data URL + */ + toString : function() { + let parametersList = []; + + for (let name in this.parameters) { + let encodedParameter = encodeURIComponent(name); + let value = this.parameters[name]; + + if (value) + encodedParameter += "=" + encodeURIComponent(value); + + parametersList.push(encodedParameter); + } + + // If there is at least a parameter, add an empty string in order + // to start with a `;` on join call. + if (parametersList.length > 0) + parametersList.unshift(""); + + let data = this.base64 ? base64.encode(this.data) : this.data; + + return "data:" + + this.mimeType + + parametersList.join(";") + "," + + encodeURIComponent(data); + } +}); + +exports.DataURL = DataURL; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/array.js b/tools/addon-sdk-1.12/lib/sdk/util/array.js index dadcfa6..764eeca 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/array.js +++ b/tools/addon-sdk-1.12/lib/sdk/util/array.js @@ -2,9 +2,12 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - "use strict"; +module.metadata = { + "stability": "experimental" +}; + /** * Returns `true` if given `array` contain given `element` or `false` * otherwise. @@ -18,6 +21,15 @@ var has = exports.has = function has(array, element) { // shorter and faster equivalent of `array.indexOf(element) >= 0` return !!~array.indexOf(element); }; +var hasAny = exports.hasAny = function hasAny(array, elements) { + if (arguments.length < 2) + return false; + if (!Array.isArray(elements)) + elements = [ elements ]; + return array.some(function (element) { + return has(elements, element); + }); +}; /** * Adds given `element` to the given `array` if it does not contain it yet. @@ -67,3 +79,11 @@ exports.unique = function unique(array) { }); return value; }; + +exports.flatten = function flatten(array){ + var flat = []; + for (var i = 0, l = array.length; i < l; i++) { + flat = flat.concat(Array.isArray(array[i]) ? flatten(array[i]) : array[i]); + } + return flat; +}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/collection.js b/tools/addon-sdk-1.12/lib/sdk/util/collection.js index b9dd352..54e7313 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/collection.js +++ b/tools/addon-sdk-1.12/lib/sdk/util/collection.js @@ -6,6 +6,10 @@ "use strict"; +module.metadata = { + "stability": "experimental" +}; + exports.Collection = Collection; /** diff --git a/tools/addon-sdk-1.12/lib/sdk/util/deprecate.js b/tools/addon-sdk-1.12/lib/sdk/util/deprecate.js new file mode 100644 index 0000000..b38606a --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/util/deprecate.js @@ -0,0 +1,27 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.metadata = { + "stability": "experimental" +}; + +const traceback = require("../console/traceback"); + +function deprecateUsage(msg) { + // Print caller stacktrace in order to help figuring out which code + // does use deprecated thing + let stack = traceback.get().slice(0, -2); + console.error("DEPRECATED: " + msg + "\n" + traceback.format(stack)); +} +exports.deprecateUsage = deprecateUsage; + +function deprecateFunction(fun, msg) { + return function deprecated() { + deprecateUsage(msg); + return fun.apply(this, arguments); + }; +} +exports.deprecateFunction = deprecateFunction; diff --git a/tools/addon-sdk-1.12/lib/sdk/util/list.js b/tools/addon-sdk-1.12/lib/sdk/util/list.js new file mode 100644 index 0000000..0a143d9 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/util/list.js @@ -0,0 +1,78 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Class } = require('../core/heritage'); +const listNS = require('../core/namespace').ns(); + +const List = Class({ + /** + * List constructor can take any number of element to populate itself. + * @params {Object|String|Number} element + * @example + * List(1,2,3).length == 3 // true + */ + initialize: function List() { + listNS(this).keyValueMap = []; + + for (let i = 0, ii = arguments.length; i < ii; i++) + addListItem(this, arguments[i]); + }, + /** + * Number of elements in this list. + * @type {Number} + */ + get length() listNS(this).keyValueMap.length, + /** + * Returns a string representing this list. + * @returns {String} + */ + toString: function toString() 'List(' + listNS(this).keyValueMap + ')', + /** + * Custom iterator providing `List`s enumeration behavior. + * We cant reuse `_iterator` that is defined by `Iterable` since it provides + * iteration in an arbitrary order. + * @see https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in + * @param {Boolean} onKeys + */ + __iterator__: function __iterator__(onKeys, onKeyValue) { + let array = listNS(this).keyValueMap.slice(0), + i = -1; + for each(let element in array) + yield onKeyValue ? [++i, element] : onKeys ? ++i : element; + } +}); +exports.List = List; + +function addListItem(that, value) { + let list = listNS(that).keyValueMap, + index = list.indexOf(value); + + if (-1 === index) { + try { + that[that.length] = value; + } + catch (e) {} + list.push(value); + } +} +exports.addListItem = addListItem; + +function removeListItem(that, element) { + let list = listNS(that).keyValueMap, + index = list.indexOf(element); + + if (0 <= index) { + list.splice(index, 1); + try { + for (let length = list.length; index < length; index++) + that[index] = list[index]; + that[list.length] = undefined; + } + catch(e){} + } +} +exports.removeListItem = removeListItem; + +exports.listNS = listNS; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/object.js b/tools/addon-sdk-1.12/lib/sdk/util/object.js index 165aa0b..4b1a2d4 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/object.js +++ b/tools/addon-sdk-1.12/lib/sdk/util/object.js @@ -4,12 +4,20 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + /** * Merges all the properties of all arguments into first argument. If two or * more argument objects have own properties with the same name, the property * is overridden, with precedence from right to left, implying, that properties * of the object on the left are overridden by a same named property of the * object on the right. + * + * Any argument given with "falsy" value - commonly `null` and `undefined` in + * case of objects - are skipped. + * * @examples * var a = { bar: 0, a: 'a' } * var b = merge(a, { foo: 'foo', bar: 1 }, { foo: 'bar', name: 'b' }); @@ -21,7 +29,10 @@ */ function merge(source) { let descriptor = {}; - Array.slice(arguments, 1).forEach(function onEach(properties) { + // `Boolean` converts the first parameter to a boolean value. Any object is + // converted to `true` where `null` and `undefined` becames `false`. Therefore + // the `filter` method will keep only objects that are defined and not null. + Array.slice(arguments, 1).filter(Boolean).forEach(function onEach(properties) { Object.getOwnPropertyNames(properties).forEach(function(name) { descriptor[name] = Object.getOwnPropertyDescriptor(properties, name); }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/registry.js b/tools/addon-sdk-1.12/lib/sdk/util/registry.js index 2ce6a6e..7d385f0 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/utils/registry.js +++ b/tools/addon-sdk-1.12/lib/sdk/util/registry.js @@ -5,8 +5,12 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { EventEmitter } = require('../events'); -const unload = require('../unload'); +module.metadata = { + "stability": "unstable" +}; + +const { EventEmitter } = require('../deprecated/events'); +const unload = require('../system/unload'); const Registry = EventEmitter.compose({ _registry: null, diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/uuid.js b/tools/addon-sdk-1.12/lib/sdk/util/uuid.js index cd667ae..0ebf981 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/uuid.js +++ b/tools/addon-sdk-1.12/lib/sdk/util/uuid.js @@ -4,6 +4,10 @@ "use strict"; +module.metadata = { + "stability": "unstable" +}; + const { Cc, Ci, components: { ID: parseUUID } } = require('chrome'); const { generateUUID } = Cc['@mozilla.org/uuid-generator;1']. getService(Ci.nsIUUIDGenerator); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/widget.js b/tools/addon-sdk-1.12/lib/sdk/widget.js index e0bbfb6..f1236aa 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/widget.js +++ b/tools/addon-sdk-1.12/lib/sdk/widget.js @@ -6,6 +6,10 @@ "use strict"; +module.metadata = { + "stability": "stable" +}; + // Widget content types const CONTENT_TYPE_URI = 1; const CONTENT_TYPE_HTML = 2; @@ -26,7 +30,7 @@ const EVENTS = { "mouseout": "mouseout", }; -if (!require("api-utils/xul-app").is("Firefox")) { +if (!require("./system/xul-app").is("Firefox")) { throw new Error([ "The widget module currently supports only Firefox. In the future ", "it will support other applications. Please see ", @@ -34,17 +38,19 @@ if (!require("api-utils/xul-app").is("Firefox")) { ].join("")); } -const { validateOptions } = require("api-utils/api-utils"); +const { validateOptions } = require("./deprecated/api-utils"); const panels = require("./panel"); -const { EventEmitter, EventEmitterTrait } = require("api-utils/events"); -const { Trait } = require("api-utils/traits"); -const LightTrait = require('api-utils/light-traits').Trait; -const { Loader, Symbiont } = require("api-utils/content"); -const { Cortex } = require('api-utils/cortex'); +const { EventEmitter, EventEmitterTrait } = require("./deprecated/events"); +const { Trait } = require("./deprecated/traits"); +const LightTrait = require('./deprecated/light-traits').Trait; +const { Loader, Symbiont } = require("./content/content"); +const { Cortex } = require('./deprecated/cortex'); const windowsAPI = require("./windows"); -const { setTimeout } = require("api-utils/timer"); -const unload = require("api-utils/unload"); -const { uuid } = require("api-utils/uuid"); +const { WindowTracker } = require("./deprecated/window-utils"); +const { isBrowser } = require("./window/utils"); +const { setTimeout } = require("./timers"); +const unload = require("./system/unload"); +const { uuid } = require("./util/uuid"); // Data types definition const valid = { @@ -96,7 +102,7 @@ let widgetAttributes = { // Import data definitions from loader, but don't compose with it as Model // functions allow us to recreate easily all Loader code. -let loaderAttributes = require("api-utils/content/loader").validationAttributes; +let loaderAttributes = require("./content/loader").validationAttributes; for (let i in loaderAttributes) widgetAttributes[i] = loaderAttributes[i]; @@ -283,9 +289,6 @@ const WidgetTrait = LightTrait.compose(EventEmitterTrait, LightTrait({ // Keep a reference to it this._views.push(view); - // Emit an `attach` event with a WidgetView instance without private attrs - this._emit("attach", view._public); - return view; }, @@ -399,7 +402,14 @@ const WidgetViewTrait = LightTrait.compose(EventEmitterTrait, LightTrait({ this._public = Cortex(this); }, - + + // Called by WidgetChrome, when the related Worker is applied to the document, + // so that we can start sending events to it + _onWorkerReady: function () { + // Emit an `attach` event with a WidgetView instance without private attrs + this._baseWidget._emit("attach", this._public); + }, + _onChange: function WidgetView__onChange(name, value) { if (name == 'tooltip' && !value) { this.tooltip = this.label; @@ -487,13 +497,13 @@ let browserManager = { // that calling this method can cause onTrack to be called immediately if // there are open windows. init: function () { - let windowTracker = new (require("api-utils/window-utils").WindowTracker)(this); + let windowTracker = new WindowTracker(this); unload.ensure(windowTracker); }, // Registers a window with the manager. This is a WindowTracker callback. onTrack: function browserManager_onTrack(window) { - if (this._isBrowserWindow(window)) { + if (isBrowser(window)) { let win = new BrowserWindow(window); win.addItems(this.items); this.windows.push(win); @@ -507,7 +517,7 @@ let browserManager = { // unload itself, since unloading the browserManager means untracking all // currently opened windows. onUntrack: function browserManager_onUntrack(window) { - if (this._isBrowserWindow(window)) { + if (isBrowser(window)) { this.items.forEach(function(i) i._onWindowClosed(window)); for (let i = 0; i < this.windows.length; i++) { if (this.windows[i].window == window) { @@ -547,11 +557,6 @@ let browserManager = { let idx = this.items.indexOf(item); if (idx > -1) this.items.splice(idx, 1); - }, - - _isBrowserWindow: function browserManager__isBrowserWindow(win) { - let winType = win.document.documentElement.getAttribute("windowtype"); - return winType === "navigator:browser"; } }; @@ -703,7 +708,7 @@ WidgetChrome.prototype._createNode = function WC__createNode() { // Temporary work around require("self") failing on unit-test execution ... let jetpackID = "testID"; try { - jetpackID = require("self").id; + jetpackID = require("./self").id; } catch(e) {} // Compute an unique and stable widget id with jetpack id and widget.id @@ -768,14 +773,14 @@ WidgetChrome.prototype.setContent = function WC_setContent() { switch (type) { case CONTENT_TYPE_HTML: - contentURL = "data:text/html," + encodeURIComponent(this._widget.content); + contentURL = "data:text/html;charset=utf-8," + encodeURIComponent(this._widget.content); break; case CONTENT_TYPE_URI: contentURL = this._widget.contentURL; break; case CONTENT_TYPE_IMAGE: let imageURL = this._widget.contentURL; - contentURL = "data:text/html,<html><body><img src='" + + contentURL = "data:text/html;charset=utf-8,<html><body><img src='" + encodeURI(imageURL) + "'></body></html>"; break; default: @@ -790,8 +795,15 @@ WidgetChrome.prototype.setContent = function WC_setContent() { this._symbiont.destroy(); this._symbiont = Trait.compose(Symbiont.resolve({ - _onContentScriptEvent: "_onContentScriptEvent-not-used" + _onContentScriptEvent: "_onContentScriptEvent-not-used", + _onInit: "_initSymbiont" }), { + // Overload `Symbiont._onInit` in order to know when the related worker + // is ready. + _onInit: function () { + this._initSymbiont(); + self._widget._onWorkerReady(); + }, _onContentScriptEvent: function () { // Redirect events to WidgetView self._widget._onPortEvent(arguments); @@ -802,6 +814,7 @@ WidgetChrome.prototype.setContent = function WC_setContent() { contentScriptFile: this._widget.contentScriptFile, contentScript: this._widget.contentScript, contentScriptWhen: this._widget.contentScriptWhen, + contentScriptOptions: this._widget.contentScriptOptions, allow: this._widget.allow, onMessage: function(message) { setTimeout(function() { @@ -841,7 +854,7 @@ WidgetChrome.prototype.addEventHandlers = function WC_addEventHandlers() { this.eventListeners = {}; let iframe = this.node.firstElementChild; - for (let [type, method] in Iterator(EVENTS)) { + for (let type in EVENTS) { iframe.addEventListener(type, listener, true, true); // Store listeners for later removal @@ -905,8 +918,10 @@ WidgetChrome.prototype.addEventHandlers = function WC_addEventHandlers() { // Remove and unregister the widget from everything WidgetChrome.prototype.destroy = function WC_destroy(removedItems) { // remove event listeners - for (let [type, listener] in Iterator(this.eventListeners)) + for (let type in this.eventListeners) { + let listener = this.eventListeners[type]; this.node.firstElementChild.removeEventListener(type, listener, true); + } // remove dom node this.node.parentNode.removeChild(this.node); // cleanup symbiont diff --git a/tools/addon-sdk-1.12/lib/sdk/window/browser.js b/tools/addon-sdk-1.12/lib/sdk/window/browser.js new file mode 100644 index 0000000..2b63a83 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/window/browser.js @@ -0,0 +1,41 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Class } = require('../core/heritage'); +const { windowNS } = require('./namespace'); +const { on, off, once } = require('../event/core'); +const { method } = require('../lang/functional'); +const { getWindowTitle } = require('./utils'); +const unload = require('../system/unload'); +const { getMode } = require('../private-browsing/utils'); +const { EventTarget } = require('../event/target'); + +const ERR_FENNEC_MSG = 'This method is not yet supported by Fennec, consider using require("tabs") instead'; + +const BrowserWindow = Class({ + initialize: function initialize(options) { + EventTarget.prototype.initialize.call(this, options); + windowNS(this).window = options.window; + }, + activate: function activate() { + // TODO + return null; + }, + close: function() { + throw new Error(ERR_FENNEC_MSG); + return null; + }, + get title() getWindowTitle(windowNS(this).window), + // NOTE: Fennec only has one window, which is assumed below + // TODO: remove assumption below + // NOTE: tabs requires windows + get tabs() require('../tabs'), + get activeTab() require('../tabs').activeTab, + on: method(on), + removeListener: method(off), + once: method(once), + get isPrivateBrowsing() getMode(windowNS(this).window), +}); +exports.BrowserWindow = BrowserWindow; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/timers.js b/tools/addon-sdk-1.12/lib/sdk/window/namespace.js index 45fcf8d..b486f88 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/timers.js +++ b/tools/addon-sdk-1.12/lib/sdk/window/namespace.js @@ -1,8 +1,6 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - "use strict"; -// This module just proxies to the low level equivalent "timer" in "api-utils". -module.exports = require("api-utils/timer"); +exports.windowNS = require('../core/namespace').ns(); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/window/utils.js b/tools/addon-sdk-1.12/lib/sdk/window/utils.js index b4a8493..0bca8b1 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/window/utils.js +++ b/tools/addon-sdk-1.12/lib/sdk/window/utils.js @@ -1,16 +1,32 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - 'use strict'; +module.metadata = { + 'stability': 'unstable' +}; + const { Cc, Ci } = require('chrome'); +const array = require('../util/array'); const windowWatcher = Cc['@mozilla.org/embedcomp/window-watcher;1']. getService(Ci.nsIWindowWatcher); const appShellService = Cc['@mozilla.org/appshell/appShellService;1']. getService(Ci.nsIAppShellService); -const observers = require('api-utils/observer-service'); +const observers = require('../deprecated/observer-service'); +const WM = Cc['@mozilla.org/appshell/window-mediator;1']. + getService(Ci.nsIWindowMediator); + +const BROWSER = 'navigator:browser', + URI_BROWSER = 'chrome://browser/content/browser.xul', + NAME = '_blank', + FEATURES = 'chrome,all,dialog=no'; + +function getMostRecentBrowserWindow() { + return WM.getMostRecentWindow(BROWSER); +} +exports.getMostRecentBrowserWindow = getMostRecentBrowserWindow; /** * Returns the ID of the window's current inner window. @@ -55,6 +71,15 @@ function getBaseWindow(window) { } exports.getBaseWindow = getBaseWindow; +function getWindowDocShell(window) window.gBrowser.docShell; +exports.getWindowDocShell = getWindowDocShell; + +function getWindowLoadingContext(window) { + return getWindowDocShell(window). + QueryInterface(Ci.nsILoadContext); +} +exports.getWindowLoadingContext = getWindowLoadingContext; + /** * Removes given window from the application's window registry. Unless * `options.close` is `false` window is automatically closed on application @@ -105,6 +130,76 @@ function open(uri, options) { uri, options.name || null, serializeFeatures(options.features || {}), - null); + options.args || null); } exports.open = open; + +/** + * Opens a top level window and returns it's `nsIDOMWindow` representation. + * Same as `open` but with more features + * @param {Object} options + * + */ +function openDialog(options) { + options = options || {}; + + let browser = WM.getMostRecentWindow(BROWSER); + return browser.openDialog.apply( + browser, + array.flatten([ + options.url || URI_BROWSER, + options.name || '_blank', + options.features || 'chrome,all,dialog=no', + options.args || null + ]) + ); +} +exports.openDialog = openDialog; + +/** + * Returns an array of all currently opened windows. + * Note that these windows may still be loading. + */ +function windows() { + let list = []; + let winEnum = windowWatcher.getWindowEnumerator(); + while (winEnum.hasMoreElements()) { + let window = winEnum.getNext().QueryInterface(Ci.nsIDOMWindow); + list.push(window); + } + return list; +} +exports.windows = windows; + +/** + * Check if the given window is completely loaded. + * i.e. if its "load" event has already been fired and all possible DOM content + * is done loading (the whole DOM document, images content, ...) + * @params {nsIDOMWindow} window + */ +function isDocumentLoaded(window) { + return window.document.readyState == "complete"; +} +exports.isDocumentLoaded = isDocumentLoaded; + +function isBrowser(window) { + return window.document.documentElement.getAttribute("windowtype") === BROWSER; +}; +exports.isBrowser = isBrowser; + +function getWindowTitle(window) { + return window && window.document ? window.document.title : null; +} +exports.getWindowTitle = getWindowTitle; + +function isXULBrowser(window) { + return !!(isBrowser(window) && window.XULBrowserWindow); +} +exports.isXULBrowser = isXULBrowser; + +function getFrames(window) { + return Array.slice(window.frames).reduce(function(frames, frame) { + return frames.concat(frame, getFrames(frame)) + }, []) +} +exports.getFrames = getFrames; diff --git a/tools/addon-sdk-1.12/lib/sdk/windows.js b/tools/addon-sdk-1.12/lib/sdk/windows.js new file mode 100644 index 0000000..15399c9 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/windows.js @@ -0,0 +1,21 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +module.metadata = { + 'stability': 'stable' +}; + +if (require('./system/xul-app').is('Firefox')) { + module.exports = require('./windows/firefox'); +} +else if (require('./system/xul-app').is('Fennec')) { + module.exports = require('./windows/fennec'); +} +else { + throw new Error([ + 'The windows module currently supports only Firefox & Fennec. In the future', + ' we would like it to support other applications, however.' + ].join('')); +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/dom.js b/tools/addon-sdk-1.12/lib/sdk/windows/dom.js index 1ff966a..ac2b86b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/dom.js +++ b/tools/addon-sdk-1.12/lib/sdk/windows/dom.js @@ -1,16 +1,20 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - 'use strict'; -const { Trait } = require('../traits'); +const { Trait } = require('../deprecated/traits'); +const { getWindowTitle } = require('../window/utils'); +const { getMode } = require('../private-browsing/utils'); + +module.metadata = { + "stability": "unstable" +}; const WindowDom = Trait.compose({ _window: Trait.required, get title() { - let window = this._window; - return window && window.document ? window.document.title : null + return getWindowTitle(this._window); }, close: function close() { let window = this._window; @@ -21,7 +25,9 @@ const WindowDom = Trait.compose({ let window = this._window; if (window) window.focus(); return this._public; + }, + get isPrivateBrowsing() { + return getMode(this._window); } }); exports.WindowDom = WindowDom; - diff --git a/tools/addon-sdk-1.12/lib/sdk/windows/fennec.js b/tools/addon-sdk-1.12/lib/sdk/windows/fennec.js new file mode 100644 index 0000000..a497ea9 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/windows/fennec.js @@ -0,0 +1,84 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Class } = require('../core/heritage'); +const { BrowserWindow } = require('../window/browser'); +const windowUtils = require('../deprecated/window-utils'); +const { WindowTracker } = windowUtils; +const { isBrowser } = require('../window/utils'); +const { windowNS } = require('../window/namespace'); +const { on, off, once, emit } = require('../event/core'); +const { method } = require('../lang/functional'); +const { EventTarget } = require('../event/target'); +const { List, addListItem } = require('../util/list'); + +const ERR_FENNEC_MSG = 'This method is not yet supported by Fennec, consider using require("tabs") instead'; + +// NOTE: On Fennec there is only one window. + +let BrowserWindows = Class({ + implements: [ List ], + extends: EventTarget, + initialize: function() { + List.prototype.initialize.apply(this); + }, + get activeWindow() { + let window = windowUtils.activeBrowserWindow; + return window ? getBrowserWindow({window: window}) : null; + }, + open: function open(options) { + throw new Error(ERR_FENNEC_MSG); + return null; + } +}); +const browserWindows = exports.browserWindows = BrowserWindows(); + + +/** + * Gets a `BrowserWindow` for the given `chromeWindow` if previously + * registered, `null` otherwise. + */ +function getRegisteredWindow(chromeWindow) { + for each (let window in browserWindows) { + if (chromeWindow === windowNS(window).window) + return window; + } + + return null; +} + +/** + * Gets a `BrowserWindow` for the provided window options obj + * @params {Object} options + * Options that are passed to the the `BrowserWindowTrait` + * @returns {BrowserWindow} + */ +function getBrowserWindow(options) { + let window = null; + + // if we have a BrowserWindow already then use it + if ('window' in options) + window = getRegisteredWindow(options.window); + if (window) + return window; + + // we don't have a BrowserWindow yet, so create one + var window = BrowserWindow(options); + addListItem(browserWindows, window); + return window; +} + +WindowTracker({ + onTrack: function onTrack(chromeWindow) { + if (!isBrowser(chromeWindow)) return; + let window = getBrowserWindow({ window: chromeWindow }); + emit(browserWindows, 'open', window); + }, + onUntrack: function onUntrack(chromeWindow) { + if (!isBrowser(chromeWindow)) return; + let window = getBrowserWindow({ window: chromeWindow }); + emit(browserWindows, 'close', window); + } +}); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/windows.js b/tools/addon-sdk-1.12/lib/sdk/windows/firefox.js index 8f13e6c..9a55a08 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/windows.js +++ b/tools/addon-sdk-1.12/lib/sdk/windows/firefox.js @@ -1,32 +1,24 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; - -if (!require("api-utils/xul-app").is("Firefox")) { - throw new Error([ - "The windows module currently supports only Firefox. In the future", - " we would like it to support other applications, however. Please see ", - "https://bugzilla.mozilla.org/show_bug.cgi?id=571449 for more information." - ].join("")); -} - -const { Cc, Ci } = require('chrome'), - { Trait } = require('api-utils/traits'), - { List } = require('api-utils/list'), - { EventEmitter } = require('api-utils/events'), - { WindowTabs, WindowTabTracker } = require('api-utils/windows/tabs'), - { WindowDom } = require('api-utils/windows/dom'), - { WindowLoader } = require('api-utils/windows/loader'), - { WindowTrackerTrait } = require('api-utils/window-utils'), - { Options } = require('api-utils/tabs/tab'), - apiUtils = require('api-utils/api-utils'), - unload = require('api-utils/unload'), - - WM = Cc['@mozilla.org/appshell/window-mediator;1']. - getService(Ci.nsIWindowMediator), +'use strict'; - BROWSER = 'navigator:browser'; +const { Cc, Ci, Cr } = require('chrome'), + { Trait } = require('../deprecated/traits'), + { List } = require('../deprecated/list'), + { EventEmitter } = require('../deprecated/events'), + { WindowTabs, WindowTabTracker } = require('./tabs-firefox'), + { WindowDom } = require('./dom'), + { WindowLoader } = require('./loader'), + { isBrowser, getWindowDocShell } = require('../window/utils'), + { Options } = require('../tabs/common'), + apiUtils = require('../deprecated/api-utils'), + unload = require('../system/unload'), + windowUtils = require('../deprecated/window-utils'), + { WindowTrackerTrait } = windowUtils, + { ns } = require('../core/namespace'), + { observer: windowObserver } = require('./observer'), + { isWindowPBEnabled } = require('../private-browsing/utils'); /** * Window trait composes safe wrappers for browser window that are E10S @@ -51,7 +43,7 @@ const BrowserWindowTrait = Trait.compose( // Register this window ASAP, in order to avoid loop that would try // to create this window instance over and over (see bug 648244) windows.push(this); - + // make sure we don't have unhandled errors this.on('error', console.exception.bind(console)); @@ -59,8 +51,13 @@ const BrowserWindowTrait = Trait.compose( this.on('open', options.onOpen); if ('onClose' in options) this.on('close', options.onClose); + if ('onActivate' in options) + this.on('activate', options.onActivate); + if ('onDeactivate' in options) + this.on('deactivate', options.onDeactivate); if ('window' in options) this._window = options.window; + if ('tabs' in options) { this._tabOptions = Array.isArray(options.tabs) ? options.tabs.map(Options) : @@ -69,6 +66,7 @@ const BrowserWindowTrait = Trait.compose( else if ('url' in options) { this._tabOptions = [ Options(options.url) ]; } + this._load(); return this; }, @@ -77,9 +75,11 @@ const BrowserWindowTrait = Trait.compose( _onLoad: function() { try { this._initWindowTabTracker(); - } catch(e) { - this._emit('error', e) } + catch(e) { + this._emit('error', e); + } + this._emitOnObject(browserWindows, 'open', this._public); }, _onUnload: function() { @@ -99,6 +99,20 @@ const BrowserWindowTrait = Trait.compose( } }) ); + +/** + * Gets a `BrowserWindowTrait` for the given `chromeWindow` if previously + * registered, `null` otherwise. + */ +function getRegisteredWindow(chromeWindow) { + for each (let window in windows) { + if (chromeWindow === window._window) + return window; + } + + return null; +} + /** * Wrapper for `BrowserWindowTrait`. Creates new instance if wrapper for * window doesn't exists yet. If wrapper already exists then returns it @@ -109,19 +123,37 @@ const BrowserWindowTrait = Trait.compose( * @see BrowserWindowTrait */ function BrowserWindow(options) { - let chromeWindow = options.window; - for each (let window in windows) { - if (chromeWindow == window._window) - return window._public - } - let window = BrowserWindowTrait(options); - return window._public; + let window = null; + + if ("window" in options) + window = getRegisteredWindow(options.window); + + return (window || BrowserWindowTrait(options))._public; } // to have proper `instanceof` behavior will go away when #596248 is fixed. BrowserWindow.prototype = BrowserWindowTrait.prototype; -exports.BrowserWindow = BrowserWindow +exports.BrowserWindow = BrowserWindow; + const windows = []; +const browser = ns(); + +function onWindowActivation (chromeWindow, event) { + if (!isBrowser(chromeWindow)) return; // Ignore if it's not a browser window. + + let window = getRegisteredWindow(chromeWindow); + + if (window) + window._emit(event.type, window._public); + else + window = BrowserWindowTrait({ window: chromeWindow }); + + browser(browserWindows).internals._emit(event.type, window._public); +} + +windowObserver.on("activate", onWindowActivation); +windowObserver.on("deactivate", onWindowActivation); + /** * `BrowserWindows` trait is composed out of `List` trait and it represents * "live" list of currently open browser windows. Instance mutates itself @@ -144,6 +176,8 @@ const browserWindows = Trait.resolve({ toString: null }).compose( * windows. */ constructor: function BrowserWindows() { + browser(this._public).internals = this; + this._trackedWindows = []; this._initList(); this._initTracker(); @@ -152,7 +186,11 @@ const browserWindows = Trait.resolve({ toString: null }).compose( _destructor: function _destructor() { this._removeAllListeners('open'); this._removeAllListeners('close'); + this._removeAllListeners('activate'); + this._removeAllListeners('deactivate'); this._clear(); + + delete browser(this._public).internals; }, /** * This property represents currently active window. @@ -160,8 +198,8 @@ const browserWindows = Trait.resolve({ toString: null }).compose( * @type {Window|null} */ get activeWindow() { - let window = WM.getMostRecentWindow(BROWSER); - return this._isBrowser(window) ? BrowserWindow({ window: window }) : null; + let window = windowUtils.activeBrowserWindow; + return window ? BrowserWindow({window: window}) : null; }, open: function open(options) { if (typeof options === "string") @@ -169,21 +207,14 @@ const browserWindows = Trait.resolve({ toString: null }).compose( options = { tabs: [Options(options)] }; return BrowserWindow(options); }, - /** - * Returns true if specified window is a browser window. - * @param {nsIWindow} window - * @returns {Boolean} - */ - _isBrowser: function _isBrowser(window) - BROWSER === window.document.documentElement.getAttribute("windowtype") - , + /** * Internal listener which is called whenever new window gets open. * Creates wrapper and adds to this list. * @param {nsIWindow} chromeWindow */ _onTrack: function _onTrack(chromeWindow) { - if (!this._isBrowser(chromeWindow)) return; + if (!isBrowser(chromeWindow)) return; let window = BrowserWindow({ window: chromeWindow }); this._add(window); this._emit('open', window); @@ -194,7 +225,7 @@ const browserWindows = Trait.resolve({ toString: null }).compose( * @param {nsIWindow} window */ _onUntrack: function _onUntrack(chromeWindow) { - if (!this._isBrowser(chromeWindow)) return; + if (!isBrowser(chromeWindow)) return; let window = BrowserWindow({ window: chromeWindow }); this._remove(window); this._emit('close', window); @@ -206,5 +237,5 @@ const browserWindows = Trait.resolve({ toString: null }).compose( } }).resolve({ toString: null }) )(); -exports.browserWindows = browserWindows; +exports.browserWindows = browserWindows; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/loader.js b/tools/addon-sdk-1.12/lib/sdk/windows/loader.js index b596e73..be3d84c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/loader.js +++ b/tools/addon-sdk-1.12/lib/sdk/windows/loader.js @@ -1,23 +1,20 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; +'use strict'; -const { Cc, Ci } = require('chrome'), - { setTimeout } = require("../timer"), - { Trait } = require('../traits'), +module.metadata = { + "stability": "unstable" +}; - WM = Cc['@mozilla.org/appshell/window-mediator;1']. - getService(Ci.nsIWindowMediator), +const { Cc, Ci } = require('chrome'), + { setTimeout } = require('../timers'), + { Trait } = require('../deprecated/traits'), + { openDialog } = require('../window/utils'), - URI_BROWSER = 'chrome://browser/content/browser.xul', - NAME = '_blank', - FEATURES = 'chrome,all,dialog=no', - PARAMS = [ URI_BROWSER, NAME, FEATURES ], ON_LOAD = 'load', ON_UNLOAD = 'unload', - STATE_LOADED = 'complete', - BROWSER = 'navigator:browser'; + STATE_LOADED = 'complete'; /** * Trait provides private `_window` property and requires `_onLoad` property @@ -43,10 +40,9 @@ const WindowLoader = Trait.compose({ _onUnload: Trait.required, _load: function _load() { if (this.__window) return; - let params = PARAMS.slice() - params.push(this._tabOptions.map(function(options) options.url).join("|")) - let browser = WM.getMostRecentWindow(BROWSER); - this._window = browser.openDialog.apply(browser, params); + this._window = openDialog({ + args: this._tabOptions.map(function(options) options.url).join("|") + }); }, /** * Private window who's load event is being tracked. Once window is loaded @@ -57,11 +53,13 @@ const WindowLoader = Trait.compose({ set _window(window) { let _window = this.__window; if (!window) window = null; + if (window !== _window) { if (_window) { _window.removeEventListener(ON_UNLOAD, this.__unloadListener, false); _window.removeEventListener(ON_LOAD, this.__loadListener, false); } + if (window) { window.addEventListener( ON_UNLOAD, @@ -70,7 +68,9 @@ const WindowLoader = Trait.compose({ , false ); + this.__window = window; + // If window is not loaded yet setting up a listener. if (STATE_LOADED != window.document.readyState) { window.addEventListener( diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/observer.js b/tools/addon-sdk-1.12/lib/sdk/windows/observer.js index 45191b7..1097bf3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/observer.js +++ b/tools/addon-sdk-1.12/lib/sdk/windows/observer.js @@ -2,13 +2,16 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - "use strict"; -const { EventEmitterTrait: EventEmitter } = require("../events"); -const { WindowTracker, windowIterator } = require("../window-utils"); -const { DOMEventAssembler } = require("../events/assembler"); -const { Trait } = require("../light-traits"); +module.metadata = { + "stability": "unstable" +}; + +const { EventEmitterTrait: EventEmitter } = require("../deprecated/events"); +const { WindowTracker, windowIterator } = require("../deprecated/window-utils"); +const { DOMEventAssembler } = require("../deprecated/events/assembler"); +const { Trait } = require("../deprecated/light-traits"); // Event emitter objects used to register listeners and emit events on them // when they occur. @@ -46,8 +49,4 @@ WindowTracker({ } }); -// Making observer aware of already opened windows. -for each (let window in windowIterator()) - observer.observe(window); - exports.observer = observer; diff --git a/tools/addon-sdk-1.12/lib/sdk/windows/tabs-fennec.js b/tools/addon-sdk-1.12/lib/sdk/windows/tabs-fennec.js new file mode 100644 index 0000000..ddf4aeb --- /dev/null +++ b/tools/addon-sdk-1.12/lib/sdk/windows/tabs-fennec.js @@ -0,0 +1,190 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Class } = require('../core/heritage'); +const { Tab } = require('../tabs/tab'); +const { browserWindows } = require('./fennec'); +const { windowNS } = require('../window/namespace'); +const { tabsNS, tabNS } = require('../tabs/namespace'); +const { openTab, getTabs, getSelectedTab } = require('../tabs/utils'); +const { Options } = require('../tabs/common'); +const { on, once, off, emit } = require('../event/core'); +const { method } = require('../lang/functional'); +const { EVENTS } = require('../tabs/events'); +const { EventTarget } = require('../event/target'); +const { when: unload } = require('../system/unload'); +const { windowIterator } = require('../deprecated/window-utils'); +const { List, addListItem, removeListItem } = require('../util/list'); + +const mainWindow = windowNS(browserWindows.activeWindow).window; + +const ERR_FENNEC_MSG = 'This method is not yet supported by Fennec'; + +const Tabs = Class({ + implements: [ List ], + extends: EventTarget, + initialize: function initialize(options) { + let tabsInternals = tabsNS(this); + let window = tabsNS(this).window = options.window || mainWindow; + + EventTarget.prototype.initialize.call(this, options); + List.prototype.initialize.apply(this, getTabs(window).map(Tab)); + + // TabOpen event + window.BrowserApp.deck.addEventListener(EVENTS.open.dom, onTabOpen, false); + + // TabSelect + window.BrowserApp.deck.addEventListener(EVENTS.activate.dom, onTabSelect, false); + + // TabClose + window.BrowserApp.deck.addEventListener(EVENTS.close.dom, onTabClose, false); + }, + get activeTab() { + return getTabForRawTab(getSelectedTab(tabsNS(this).window)); + }, + open: function(options) { + options = Options(options); + let activeWin = browserWindows.activeWindow; + + if (options.isPinned) { + console.error(ERR_FENNEC_MSG); // TODO + } + + let rawTab = openTab(windowNS(activeWin).window, options.url, { + inBackground: options.inBackground + }); + + // by now the tab has been created + let tab = getTabForRawTab(rawTab); + + if (options.onClose) + tab.on('close', options.onClose); + + if (options.onOpen) { + // NOTE: on Fennec this will be true + if (tabNS(tab).opened) + options.onOpen(tab); + + tab.on('open', options.onOpen); + } + + if (options.onReady) + tab.on('ready', options.onReady); + + if (options.onActivate) + tab.on('activate', options.onActivate); + + return tab; + } +}); +let gTabs = exports.tabs = Tabs(mainWindow); + +function tabsUnloader(event, window) { + window = window || (event && event.target); + if (!(window && window.BrowserApp)) + return; + window.BrowserApp.deck.removeEventListener(EVENTS.open.dom, onTabOpen, false); + window.BrowserApp.deck.removeEventListener(EVENTS.activate.dom, onTabSelect, false); + window.BrowserApp.deck.removeEventListener(EVENTS.close.dom, onTabClose, false); +} + +// unload handler +unload(function() { + for (let window in windowIterator()) { + tabsUnloader(null, window); + } +}); + +function addTab(tab) { + addListItem(gTabs, tab); + return tab; +} + +function removeTab(tab) { + removeListItem(gTabs, tab); + return tab; +} + +function getTabForBrowser(browser) { + return getTabForRawTab(getRawTabForBrowser(browser)); +} + +function getRawTabForBrowser(browser) { + let tabs = mainWindow.BrowserApp.tabs; + for (let i = 0; i < tabs.length; i++) { + let tab = tabs[i]; + if (tab.browser === browser) + return tab + } + return null; +} + +// TabOpen +function onTabOpen(event) { + let browser = event.target; + + let tab = getTabForBrowser(browser); + if (tab === null) { + let rawTab = getRawTabForBrowser(browser); + + // create a Tab instance for this new tab + tab = addTab(Tab(rawTab)); + } + + tabNS(tab).opened = true; + + // TabReady + let onReady = tabNS(tab).onReady = onTabReady.bind(tab); + browser.addEventListener(EVENTS.ready.dom, onReady, false); + + emit(tab, 'open', tab); + emit(gTabs, 'open', tab); +}; + +function onTabReady() { + emit(this, 'ready', this); + emit(gTabs, 'ready', this); +} + +// TabSelect +function onTabSelect(event) { + // Set value whenever new tab becomes active. + let tab = getTabForBrowser(event.target); + emit(tab, 'activate', tab); + emit(gTabs, 'activate', tab); + + for each (let t in gTabs) { + if (t === tab) continue; + emit(t, 'deactivate', t); + emit(gTabs, 'deactivate', t); + } +}; + +// TabClose +function onTabClose(event) { + let tab = getTabForBrowser(event.target); + removeTab(tab); + + emit(gTabs, 'close', tab); + emit(tab, 'close', tab); +}; + +function getTabForRawTab(rawTab) { + for each (let tab in gTabs) { + if (tabNS(tab).tab === rawTab) + return tab; + } + return null; +} + +unload(function() { + for each (let tab in gTabs) { + let tabInternals = tabNS(tab); + tabInternals.tab.browser.removeEventListener(EVENTS.ready.dom, tabInternals.onReady, false); + tabInternals.onReady = null; + tabInternals.tab = null; + tabInternals.window = null; + } +}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/tabs.js b/tools/addon-sdk-1.12/lib/sdk/windows/tabs-firefox.js index 231a22e..f41e752 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/windows/tabs.js +++ b/tools/addon-sdk-1.12/lib/sdk/windows/tabs-firefox.js @@ -3,13 +3,18 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Trait } = require("../traits"); -const { List } = require("../list"); -const { Tab, Options } = require("../tabs/tab"); -const { EventEmitter } = require("../events"); +module.metadata = { + "stability": "unstable" +}; + +const { Trait } = require("../deprecated/traits"); +const { List } = require("../deprecated/list"); +const { Tab } = require("../tabs/tab"); +const { EventEmitter } = require("../deprecated/events"); const { EVENTS } = require("../tabs/events"); const { getOwnerWindow, getActiveTab, getTabs, openTab, activateTab } = require("../tabs/utils"); +const { Options } = require("../tabs/common"); const { observer: tabsObserver } = require("../tabs/observer"); const TAB_BROWSER = "tabbrowser"; @@ -43,6 +48,7 @@ const WindowTabTracker = Trait.compose({ // point it is necessary to invoke lazy `tabs` getter on the windows object // which creates a `TabList` instance. this.tabs; + // Binding all methods used as event listeners to the instance. this._onTabReady = this._emitEvent.bind(this, "ready"); this._onTabOpen = this._onTabEvent.bind(this, "open"); @@ -58,6 +64,7 @@ const WindowTabTracker = Trait.compose({ // necessary to synchronize tabs lists with an actual state. this._onTabOpen(tab); } + // We also emulate "activate" event so that it's picked up by a tab list. this._onTabActivate(getActiveTab(this._window)); @@ -87,6 +94,7 @@ const WindowTabTracker = Trait.compose({ let options = this._tabOptions.shift() || {}; options.tab = tab; options.window = this._public; + // creating tab wrapper and adding listener to "ready" events. let wrappedTab = Tab(options); @@ -125,6 +133,7 @@ const TabList = List.resolve({ constructor: "_init" }).compose( this._window = options.window; // Add new items to the list this.on(EVENTS.open.name, this._add.bind(this)); + // Remove closed items from the list this.on(EVENTS.close.name, this._remove.bind(this)); @@ -132,6 +141,7 @@ const TabList = List.resolve({ constructor: "_init" }).compose( this.on("activate", function onTabActivate(tab) { this._activeTab = tab; }.bind(this)); + // Initialize list. this._init(); // This list is not going to emit any events, object holding this list diff --git a/tools/addon-sdk-1.12/lib/toolkit/loader.js b/tools/addon-sdk-1.12/lib/toolkit/loader.js new file mode 100644 index 0000000..09a9889 --- /dev/null +++ b/tools/addon-sdk-1.12/lib/toolkit/loader.js @@ -0,0 +1,400 @@ +/* vim:set ts=2 sw=2 sts=2 expandtab */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +;(function(id, factory) { // Module boilerplate :( + if (typeof(define) === 'function') { // RequireJS + define(factory); + } else if (typeof(require) === 'function') { // CommonJS + factory.call(this, require, exports, module); + } else if (~String(this).indexOf('BackstagePass')) { // JSM + factory(function require(uri) { + var imports = {}; + this['Components'].utils.import(uri, imports); + return imports; + }, this, { uri: __URI__, id: id }); + this.EXPORTED_SYMBOLS = Object.keys(this); + } else if (~String(this).indexOf('Sandbox')) { // Sandbox + factory(function require(uri) {}, this, { uri: __URI__, id: id }); + } else { // Browser or alike + var globals = this + factory(function require(id) { + return globals[id]; + }, (globals[id] = {}), { uri: document.location.href + '#' + id, id: id }); + } +}).call(this, 'loader', function(require, exports, module) { + +'use strict'; + +module.metadata = { + "stability": "unstable" +}; + +const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, + results: Cr, manager: Cm } = Components; +const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); +const { loadSubScript } = Cc['@mozilla.org/moz/jssubscript-loader;1']. + getService(Ci.mozIJSSubScriptLoader); +const { notifyObservers } = Cc['@mozilla.org/observer-service;1']. + getService(Ci.nsIObserverService); + +// Define some shortcuts. +const bind = Function.call.bind(Function.bind); +const getOwnPropertyNames = Object.getOwnPropertyNames; +const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +const define = Object.defineProperties; +const prototypeOf = Object.getPrototypeOf; +const create = Object.create; +const keys = Object.keys; + +// Workaround for bug 674195. Freezing objects from other compartments fail, +// so we use `Object.freeze` from the same component instead. +function freeze(object) { + if (prototypeOf(object) === null) { + Object.freeze(object); + } + else { + prototypeOf(prototypeOf(object.isPrototypeOf)). + constructor. // `Object` from the owner compartment. + freeze(object); + } + return object; +} + +// Returns map of given `object`-s own property descriptors. +const descriptor = iced(function descriptor(object) { + let value = {}; + getOwnPropertyNames(object).forEach(function(name) { + value[name] = getOwnPropertyDescriptor(object, name) + }); + return value; +}); +exports.descriptor = descriptor; + +// Freeze important built-ins so they can't be used by untrusted code as a +// message passing channel. +freeze(Object); +freeze(Object.prototype); +freeze(Function); +freeze(Function.prototype); +freeze(Array); +freeze(Array.prototype); +freeze(String); +freeze(String.prototype); + +// This function takes `f` function sets it's `prototype` to undefined and +// freezes it. We need to do this kind of deep freeze with all the exposed +// functions so that untrusted code won't be able to use them a message +// passing channel. +function iced(f) { + f.prototype = undefined; + return freeze(f); +} + +// Defines own properties of given `properties` object on the given +// target object overriding any existing property with a conflicting name. +// Returns `target` object. Note we only export this function because it's +// useful during loader bootstrap when other util modules can't be used & +// thats only case where this export should be used. +const override = iced(function override(target, source) { + let properties = descriptor(target) + let extension = descriptor(source || {}) + getOwnPropertyNames(extension).forEach(function(name) { + properties[name] = extension[name]; + }); + return define({}, properties); +}); +exports.override = override; + +// Function takes set of options and returns a JS sandbox. Function may be +// passed set of options: +// - `name`: A string value which identifies the sandbox in about:memory. Will +// throw exception if omitted. +// - `principal`: String URI or `nsIPrincipal` for the sandbox. Defaults to +// system principal. +// - `prototype`: Ancestor for the sandbox that will be created. Defaults to +// `{}`. +// - `wantXrays`: A Boolean value indicating whether code outside the sandbox +// wants X-ray vision with respect to objects inside the sandbox. Defaults +// to `true`. +// - `sandbox`: A sandbox to share JS compartment with. If omitted new +// compartment will be created. +// For more details see: +// https://developer.mozilla.org/en/Components.utils.Sandbox +const Sandbox = iced(function Sandbox(options) { + // Normalize options and rename to match `Cu.Sandbox` expectations. + options = { + // Do not expose `Components` if you really need them (bad idea!) you + // still can expose via prototype. + wantComponents: false, + sandboxName: options.name, + principal: 'principal' in options ? options.principal : systemPrincipal, + wantXrays: 'wantXrays' in options ? options.wantXrays : true, + sandboxPrototype: 'prototype' in options ? options.prototype : {}, + sameGroupAs: 'sandbox' in options ? options.sandbox : null + }; + + // Make `options.sameGroupAs` only if `sandbox` property is passed, + // otherwise `Cu.Sandbox` will throw. + if (!options.sameGroupAs) + delete options.sameGroupAs; + + let sandbox = Cu.Sandbox(options.principal, options); + + // Each sandbox at creation gets set of own properties that will be shadowing + // ones from it's prototype. We override delete such `sandbox` properties + // to avoid shadowing. + delete sandbox.Iterator; + delete sandbox.Components; + delete sandbox.importFunction; + delete sandbox.debug; + + return sandbox; +}); +exports.Sandbox = Sandbox; + +// Evaluates code from the given `uri` into given `sandbox`. If +// `options.source` is passed, then that code is evaluated instead. +// Optionally following options may be given: +// - `options.encoding`: Source encoding, defaults to 'UTF-8'. +// - `options.line`: Line number to start count from for stack traces. +// Defaults to 1. +// - `options.version`: Version of JS used, defaults to '1.8'. +const evaluate = iced(function evaluate(sandbox, uri, options) { + let { source, line, version, encoding } = override({ + encoding: 'UTF-8', + line: 1, + version: '1.8', + source: null + }, options); + + + return source ? Cu.evalInSandbox(source, sandbox, version, uri, line) + : loadSubScript(uri, sandbox, encoding); +}); +exports.evaluate = evaluate; + +// Populates `exports` of the given CommonJS `module` object, in the context +// of the given `loader` by evaluating code associated with it. +const load = iced(function load(loader, module) { + let { sandboxes, globals } = loader; + let require = Require(loader, module); + + let sandbox = sandboxes[module.uri] = Sandbox({ + name: module.uri, + // Get an existing module sandbox, if any, so we can reuse its compartment + // when creating the new one to reduce memory consumption. + sandbox: sandboxes[keys(sandboxes).shift()], + // We expose set of properties defined by `CommonJS` specification via + // prototype of the sandbox. Also globals are deeper in the prototype + // chain so that each module has access to them as well. + prototype: create(globals, descriptor({ + require: require, + module: module, + exports: module.exports + })), + wantXrays: false + }); + + evaluate(sandbox, module.uri); + + if (module.exports && typeof(module.exports) === 'object') + freeze(module.exports); + + return module; +}); +exports.load = load; + +// Utility function to check if id is relative. +function isRelative(id) { return id[0] === '.'; } +// Utility function to normalize module `uri`s so they have `.js` extension. +function normalize(uri) { return uri.substr(-3) === '.js' ? uri : uri + '.js'; } +// Utility function to join paths. In common case `base` is a +// `requirer.uri` but in some cases it may be `baseURI`. In order to +// avoid complexity we require `baseURI` with a trailing `/`. +const resolve = iced(function resolve(id, base) { + let paths = id.split('/'); + let result = base.split('/'); + result.pop(); + while (paths.length) { + let path = paths.shift(); + if (path === '..') + result.pop(); + else if (path !== '.') + result.push(path); + } + return result.join('/'); +}); +exports.resolve = resolve; + +const resolveURI = iced(function resolveURI(id, mapping) { + let count = mapping.length, index = 0; + while (index < count) { + let [ path, uri ] = mapping[index ++]; + if (id.indexOf(path) === 0) + return normalize(id.replace(path, uri)); + } +}); +exports.resolveURI = resolveURI; + +// Creates version of `require` that will be exposed to the given `module` +// in the context of the given `loader`. Each module gets own limited copy +// of `require` that is allowed to load only a modules that are associated +// with it during link time. +const Require = iced(function Require(loader, requirer) { + let { modules, mapping, resolve } = loader; + + function require(id) { + if (!id) // Throw if `id` is not passed. + throw Error('you must provide a module name when calling require() from ' + + requirer.id, requirer.uri); + + // Resolve `id` to its requirer if it's relative. + let requirement = requirer ? resolve(id, requirer.id) : id; + + + // Resolves `uri` of module using loaders resolve function. + let uri = resolveURI(requirement, mapping); + + if (!uri) // Throw if `uri` can not be resolved. + throw Error('Module: Can not resolve "' + id + '" module required by ' + + requirer.id + ' located at ' + requirer.uri, requirer.uri); + + let module = null; + // If module is already cached by loader then just use it. + if (uri in modules) { + module = modules[uri]; + } + // Otherwise load and cache it. We also freeze module to prevent it from + // further changes at runtime. + else { + module = modules[uri] = Module(requirement, uri); + freeze(load(loader, module)); + } + + return module.exports; + } + // Make `require.main === module` evaluate to true in main module scope. + require.main = loader.main === requirer ? requirer : undefined; + return iced(require); +}); +exports.Require = Require; + +const main = iced(function main(loader, id) { + let uri = resolveURI(id, loader.mapping) + let module = loader.main = loader.modules[uri] = Module(id, uri); + return load(loader, module).exports; +}); +exports.main = main; + +// Makes module object that is made available to CommonJS modules when they +// are evaluated, along with `exports` and `require`. +const Module = iced(function Module(id, uri) { + return create(null, { + id: { enumerable: true, value: id }, + exports: { enumerable: true, writable: true, value: create(null) }, + uri: { value: uri } + }); +}); +exports.Module = Module; + +// Takes `loader`, and unload `reason` string and notifies all observers that +// they should cleanup after them-self. +const unload = iced(function unload(loader, reason) { + // subject is a unique object created per loader instance. + // This allows any code to cleanup on loader unload regardless of how + // it was loaded. To handle unload for specific loader subject may be + // asserted against loader.destructor or require('@loader/unload') + // Note: We don not destroy loader's module cache or sandboxes map as + // some modules may do cleanup in subsequent turns of event loop. Destroying + // cache may cause module identity problems in such cases. + let subject = { wrappedJSObject: loader.destructor }; + notifyObservers(subject, 'sdk:loader:destroy', reason); +}); +exports.unload = unload; + +// Function makes new loader that can be used to load CommonJS modules +// described by a given `options.manifest`. Loader takes following options: +// - `globals`: Optional map of globals, that all module scopes will inherit +// from. Map is also exposed under `globals` property of the returned loader +// so it can be extended further later. Defaults to `{}`. +// - `modules` Optional map of built-in module exports mapped by module id. +// These modules will incorporated into module cache. Each module will be +// frozen. +// - `resolve` Optional module `id` resolution function. If given it will be +// used to resolve module URIs, by calling it with require term, requirer +// module object (that has `uri` property) and `baseURI` of the loader. +// If `resolve` does not returns `uri` string exception will be thrown by +// an associated `require` call. +const Loader = iced(function Loader(options) { + let { modules, globals, resolve, paths } = override({ + paths: {}, + modules: {}, + globals: {}, + resolve: exports.resolve + }, options); + + // We create an identity object that will be dispatched on an unload + // event as subject. This way unload listeners will be able to assert + // which loader is unloaded. Please note that we intentionally don't + // use `loader` as subject to prevent a loader access leakage through + // observer notifications. + let destructor = freeze(create(null)); + + // Make mapping array that is sorted from longest path to shortest path + // to allow overlays. + let mapping = keys(paths). + sort(function(a, b) { return b.length - a.length }). + map(function(path) { return [ path, paths[path] ] }); + + // Define pseudo modules. + modules = override({ + '@loader/unload': destructor, + '@loader/options': options, + 'chrome': { Cc: Cc, Ci: Ci, Cu: Cu, Cr: Cr, Cm: Cm, + CC: bind(CC, Components), components: Components, + // `ChromeWorker` has to be inject in loader global scope. + // It is done by bootstrap.js:loadSandbox for the SDK. + ChromeWorker: ChromeWorker + } + }, modules); + + modules = keys(modules).reduce(function(result, id) { + // We resolve `uri` from `id` since modules are cached by `uri`. + let uri = resolveURI(id, mapping); + let module = Module(id, uri); + module.exports = freeze(modules[id]); + result[uri] = freeze(module); + return result; + }, {}); + + // Loader object is just a representation of a environment + // state. We freeze it and mark make it's properties non-enumerable + // as they are pure implementation detail that no one should rely upon. + return freeze(create(null, { + destructor: { enumerable: false, value: destructor }, + globals: { enumerable: false, value: globals }, + mapping: { enumerable: false, value: mapping }, + // Map of module objects indexed by module URIs. + modules: { enumerable: false, value: modules }, + // Map of module sandboxes indexed by module URIs. + sandboxes: { enumerable: false, value: {} }, + resolve: { enumerable: false, value: resolve }, + // Main (entry point) module, it can be set only once, since loader + // instance can have only one main module. + main: new function() { + let main; + return { + enumerable: false, + get: function() { return main; }, + // Only set main if it has not being set yet! + set: function(module) { main = main || module; } + } + } + })); +}); +exports.Loader = Loader; + +}); + diff --git a/tools/addon-sdk-1.12/mapping.json b/tools/addon-sdk-1.12/mapping.json new file mode 100644 index 0000000..dd6d423 --- /dev/null +++ b/tools/addon-sdk-1.12/mapping.json @@ -0,0 +1,81 @@ +{ + "api-utils": "sdk/deprecated/api-utils", + "base64": "sdk/base64", + "content": "sdk/content/content", + "deprecate": "sdk/util/deprecate", + "event/core": "sdk/event/core", + "events": "sdk/deprecated/events", + "functional": "sdk/core/functional", + "l10n/core": "sdk/l10n/core", + "l10n/html": "sdk/l10n/html", + "l10n/loader": "sdk/l10n/loader", + "l10n/locale": "sdk/l10n/locale", + "l10n/prefs": "sdk/l10n/prefs", + "list": "sdk/util/list", + "loader": "sdk/loader/loader", + "memory": "sdk/deprecated/memory", + "namespace": "sdk/core/namespace", + "observer-service": "sdk/deprecated/observer-service", + "preferences-service": "sdk/preferences/service", + "promise": "sdk/core/promise", + "system": "sdk/system", + "system/events": "sdk/system/events", + "tabs/tab": "sdk/tabs/tab", + "tabs/utils": "sdk/tabs/utils", + "timer": "sdk/timers", + "traits": "sdk/deprecated/traits", + "unload": "sdk/system/unload", + "window-utils": "sdk/deprecated/window-utils", + "window/utils": "sdk/window/utils", + "windows/dom": "sdk/windows/dom", + "windows/loader": "sdk/windows/loader", + "xul-app": "sdk/system/xul-app", + "url": "sdk/url", + "traceback": "sdk/console/traceback", + "xhr": "sdk/net/xhr", + "match-pattern": "sdk/page-mod/match-pattern", + "tab-browser": "sdk/deprecated/tab-browser", + "file": "sdk/io/file", + "runtime": "sdk/system/runtime", + "xpcom": "sdk/platform/xpcom", + "querystring": "sdk/querystring", + "text-streams": "sdk/io/text-streams", + "app-strings": "sdk/deprecated/app-strings", + "light-traits": "sdk/deprecated/light-traits", + "environment": "sdk/system/environment", + "keyboard/utils": "sdk/keyboard/utils", + "dom/events": "sdk/dom/events", + "utils/data": "sdk/io/data", + "test/assert": "sdk/test/assert", + "hidden-frame": "sdk/frame/hidden-frame", + "collection": "sdk/util/collection", + "array": "sdk/util/array", + "cortex": "sdk/deprecated/cortex", + + + "addon-page": "sdk/addon-page", + "clipboard": "sdk/clipboard", + "context-menu": "sdk/context-menu", + "hotkeys": "sdk/hotkeys", + "indexed-db": "sdk/indexed-db", + "l10n": "sdk/l10n", + "notifications": "sdk/notifications", + "page-mod": "sdk/page-mod", + "page-worker": "sdk/page-worker", + "panel": "sdk/panel", + "passwords": "sdk/passwords", + "private-browsing": "sdk/private-browsing", + "request": "sdk/request", + "selection": "sdk/selection", + "self": "sdk/self", + "simple-prefs": "sdk/simple-prefs", + "simple-storage": "sdk/simple-storage", + "tabs": "sdk/tabs", + "timers": "sdk/timers", + "widget": "sdk/widget", + "windows": "sdk/windows", + + "harness": "sdk/test/harness", + "run-tests": "sdk/test/runner", + "test": "sdk/test" +} diff --git a/tools/addon-sdk-1.12/package.json b/tools/addon-sdk-1.12/package.json new file mode 100644 index 0000000..7519eb6 --- /dev/null +++ b/tools/addon-sdk-1.12/package.json @@ -0,0 +1,10 @@ +{ + "name": "addon-sdk", + "description": "Add-on development made easy.", + "keywords": [ + "javascript", "engine", "addon", "extension", + "xulrunner", "firefox", "browser" + ], + "loader": "lib/sdk/loader/cuddlefish.js", + "license": "MPL 2.0" +} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/__init__.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/__init__.py index 9792eb9..f5a3ed6 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/__init__.py @@ -119,9 +119,9 @@ parser_groups = ( (("", "--extra-packages",), dict(dest="extra_packages", help=("extra packages to include, " "comma-separated. Default is " - "'addon-kit'."), + "'addon-sdk'."), metavar=None, - default="addon-kit", + default="addon-sdk", cmds=['run', 'xpi', 'test', 'testex', 'testpkgs', 'testall', 'testcfx'])), @@ -194,6 +194,11 @@ parser_groups = ( metavar=None, default=False, cmds=['test', 'testex', 'testpkgs'])), + (("", "--override-version",), dict(dest="override_version", + help="Pass in a version string to use in generated docs", + metavar=None, + default=False, + cmds=['sdocs'])), ] ), @@ -216,7 +221,7 @@ parser_groups = ( "containing test runner " "program (default is " "test-harness)"), - default="test-harness", + default="addon-sdk", cmds=['test', 'testex', 'testpkgs', 'testall'])), # --keydir was removed in 1.0b5, but we keep it around in the options @@ -323,11 +328,12 @@ def parse_args(arguments, global_options, usage, version, parser_groups, def test_all(env_root, defaults): fail = False - print >>sys.stderr, "Testing cfx..." - sys.stderr.flush() - result = test_cfx(env_root, defaults['verbose']) - if result.failures or result.errors: - fail = True + if not defaults['filter']: + print >>sys.stderr, "Testing cfx..." + sys.stderr.flush() + result = test_cfx(env_root, defaults['verbose']) + if result.failures or result.errors: + fail = True if not fail or not defaults.get("stopOnError"): print >>sys.stderr, "Testing all examples..." @@ -339,6 +345,15 @@ def test_all(env_root, defaults): fail = (e.code != 0) or fail if not fail or not defaults.get("stopOnError"): + print >>sys.stderr, "Testing all unit-test addons..." + sys.stderr.flush() + + try: + test_all_testaddons(env_root, defaults) + except SystemExit, e: + fail = (e.code != 0) or fail + + if not fail or not defaults.get("stopOnError"): print >>sys.stderr, "Testing all packages..." sys.stderr.flush() try: @@ -365,6 +380,30 @@ def test_cfx(env_root, verbose): sys.stdout.flush(); sys.stderr.flush() return retval +def test_all_testaddons(env_root, defaults): + addons_dir = os.path.join(env_root, "test", "addons") + addons = [dirname for dirname in os.listdir(addons_dir) + if os.path.isdir(os.path.join(addons_dir, dirname))] + addons.sort() + fail = False + for dirname in addons: + print >>sys.stderr, "Testing %s..." % dirname + sys.stderr.flush() + try: + run(arguments=["run", + "--pkgdir", + os.path.join(addons_dir, dirname)], + defaults=defaults, + env_root=env_root) + except SystemExit, e: + fail = (e.code != 0) or fail + if fail and defaults.get("stopOnError"): + break + + if fail: + print >>sys.stderr, "Some test addons tests were unsuccessful." + sys.exit(-1) + def test_all_examples(env_root, defaults): examples_dir = os.path.join(env_root, "examples") examples = [dirname for dirname in os.listdir(examples_dir) @@ -391,8 +430,12 @@ def test_all_examples(env_root, defaults): def test_all_packages(env_root, defaults): packages_dir = os.path.join(env_root, "packages") - packages = [dirname for dirname in os.listdir(packages_dir) - if os.path.isdir(os.path.join(packages_dir, dirname))] + if os.path.isdir(packages_dir): + packages = [dirname for dirname in os.listdir(packages_dir) + if os.path.isdir(os.path.join(packages_dir, dirname))] + else: + packages = [] + packages.append(env_root) packages.sort() print >>sys.stderr, "Testing all available packages: %s." % (", ".join(packages)) sys.stderr.flush() @@ -440,13 +483,20 @@ def get_config_args(name, env_root): return config def initializer(env_root, args, out=sys.stdout, err=sys.stderr): - from templates import MAIN_JS, PACKAGE_JSON, README_DOC, MAIN_JS_DOC, TEST_MAIN_JS + from templates import PACKAGE_JSON, TEST_MAIN_JS path = os.getcwd() addon = os.path.basename(path) - # if more than one argument - if len(args) > 1: + # if more than two arguments + if len(args) > 2: print >>err, 'Too many arguments.' return 1 + if len(args) == 2: + path = os.path.join(path,args[1]) + try: + os.mkdir(path) + print >>out, '*', args[1], 'package directory created' + except OSError: + print >>out, '*', args[1], 'already exists, testing if directory is empty' # avoid clobbering existing files, but we tolerate things like .git existing = [fn for fn in os.listdir(path) if not fn.startswith(".")] if existing: @@ -455,19 +505,23 @@ def initializer(env_root, args, out=sys.stdout, err=sys.stderr): for d in ['lib','data','test','doc']: os.mkdir(os.path.join(path,d)) print >>out, '*', d, 'directory created' - open('README.md','w').write(README_DOC % {'name':addon}) + open(os.path.join(path,'README.md'),'w').write('') print >>out, '* README.md written' - open('package.json','w').write(PACKAGE_JSON % {'name':addon.lower(), + open(os.path.join(path,'package.json'),'w').write(PACKAGE_JSON % {'name':addon.lower(), 'fullName':addon }) print >>out, '* package.json written' open(os.path.join(path,'test','test-main.js'),'w').write(TEST_MAIN_JS) print >>out, '* test/test-main.js written' - open(os.path.join(path,'lib','main.js'),'w').write(MAIN_JS) + open(os.path.join(path,'lib','main.js'),'w').write('') print >>out, '* lib/main.js written' - open(os.path.join(path,'doc','main.md'),'w').write(MAIN_JS_DOC) + open(os.path.join(path,'doc','main.md'),'w').write('') print >>out, '* doc/main.md written' - print >>out, '\nYour sample add-on is now ready.' - print >>out, 'Do "cfx test" to test it and "cfx run" to try it. Have fun!' + if len(args) == 1: + print >>out, '\nYour sample add-on is now ready.' + print >>out, 'Do "cfx test" to test it and "cfx run" to try it. Have fun!' + else: + print >>out, '\nYour sample add-on is now ready in the \'' + args[1] + '\' directory.' + print >>out, 'Change to that directory, then do "cfx test" to test it, \nand "cfx run" to try it. Have fun!' return 0 def buildJID(target_cfg): @@ -510,6 +564,9 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, if command == "testpkgs": test_all_packages(env_root, defaults=options.__dict__) return + elif command == "testaddons": + test_all_testaddons(env_root, defaults=options.__dict__) + return elif command == "testex": test_all_examples(env_root, defaults=options.__dict__) return @@ -517,19 +574,26 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, test_all(env_root, defaults=options.__dict__) return elif command == "testcfx": + if options.filter: + print >>sys.stderr, "The filter option is not valid with the testcfx command" + return test_cfx(env_root, options.verbose) return elif command == "docs": from cuddlefish.docs import generate if len(args) > 1: - docs_home = generate.generate_named_file(env_root, filename=args[1]) + docs_home = generate.generate_named_file(env_root, filename_and_path=args[1]) else: docs_home = generate.generate_local_docs(env_root) webbrowser.open(docs_home) return elif command == "sdocs": from cuddlefish.docs import generate - filename = generate.generate_static_docs(env_root) + filename="" + if options.override_version: + filename = generate.generate_static_docs(env_root, override_version=options.override_version) + else: + filename = generate.generate_static_docs(env_root) print >>stdout, "Wrote %s." % filename return elif command not in ["xpi", "test", "run"]: @@ -625,7 +689,8 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, deps = packaging.get_deps_for_targets(pkg_cfg, targets) - from cuddlefish.manifest import build_manifest, ModuleNotFoundError + from cuddlefish.manifest import build_manifest, ModuleNotFoundError, \ + BadChromeMarkerError # Figure out what loader files should be scanned. This is normally # computed inside packaging.generate_build_for_target(), by the first # dependent package that defines a "loader" property in its package.json. @@ -638,11 +703,11 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, # the choice of loader for manifest-generation purposes. In practice, # this means that alternative loaders probably won't work with # --strip-xpi. - assert packaging.DEFAULT_LOADER == "api-utils" - assert pkg_cfg.packages["api-utils"].loader == "lib/cuddlefish.js" - cuddlefish_js_path = os.path.join(pkg_cfg.packages["api-utils"].root_dir, - "lib", "cuddlefish.js") - loader_modules = [("api-utils", "lib", "cuddlefish", cuddlefish_js_path)] + assert packaging.DEFAULT_LOADER == "addon-sdk" + assert pkg_cfg.packages["addon-sdk"].loader == "lib/sdk/loader/cuddlefish.js" + cuddlefish_js_path = os.path.join(pkg_cfg.packages["addon-sdk"].root_dir, + "lib", "sdk", "loader", "cuddlefish.js") + loader_modules = [("addon-sdk", "lib", "sdk/loader/cuddlefish", cuddlefish_js_path)] scan_tests = command == "test" test_filter_re = None if scan_tests and options.filter: @@ -656,6 +721,9 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, except ModuleNotFoundError, e: print str(e) sys.exit(1) + except BadChromeMarkerError, e: + # An error had already been displayed on stderr in manifest code + sys.exit(1) used_deps = manifest.get_used_packages() if command == "test": # The test runner doesn't appear to link against any actual packages, @@ -669,7 +737,8 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, build = packaging.generate_build_for_target( pkg_cfg, target, used_deps, - include_dep_tests=options.dep_tests + include_dep_tests=options.dep_tests, + is_running_tests=(command == "test") ) harness_options = { @@ -684,8 +753,8 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, if command == "test": # This should be contained in the test runner package. # maybe just do: target_cfg.main = 'test-harness/run-tests' - harness_options['main'] = 'test-harness/run-tests' - harness_options['mainPath'] = manifest.get_manifest_entry("test-harness", "lib", "run-tests").get_path() + harness_options['main'] = 'sdk/test/runner' + harness_options['mainPath'] = manifest.get_manifest_entry("addon-sdk", "lib", "sdk/test/runner").get_path() else: harness_options['main'] = target_cfg.get('main') harness_options['mainPath'] = manifest.top_path @@ -706,7 +775,7 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, app_extension_dir = os.path.abspath(options.templatedir) else: mydir = os.path.dirname(os.path.abspath(__file__)) - app_extension_dir = os.path.join(mydir, "app-extension") + app_extension_dir = os.path.join(mydir, "../../app-extension") if target_cfg.get('preferences'): @@ -714,6 +783,8 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, harness_options['manifest'] = manifest.get_harness_options_manifest() harness_options['allTestModules'] = manifest.get_all_test_modules() + if len(harness_options['allTestModules']) == 0 and command == "test": + sys.exit(0) from cuddlefish.rdf import gen_manifest, RDFUpdate @@ -725,6 +796,8 @@ def run(arguments=sys.argv[1:], target_cfg=None, pkg_cfg=None, enable_mobile=options.enable_mobile) if command == "xpi" and options.update_link: + if not options.update_link.startswith("https"): + raise optparse.OptionValueError("--update-link must start with 'https': %s" % options.update_link) rdf_name = UPDATE_RDF_FILENAME % target_cfg.name print >>stdout, "Exporting update description to %s." % rdf_name update = RDFUpdate() diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/_version.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/_version.py index 61e7178..be1ee60 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/_version.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/_version.py @@ -9,8 +9,8 @@ # (https://github.com/warner/python-versioneer) # these strings will be replaced by git during git-archive -git_refnames = " (HEAD, 1.7rc2, 1.7, origin/stabilization, stabilization)" -git_full = "075becdd649500d845fa15aea09129e6aef02bef" +git_refnames = " (HEAD, 1.12rc3, 1.12, origin/stabilization, stabilization)" +git_full = "9c31911385c15801523dd6ca27bcc2a5748ff476" import subprocess diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/bunch.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/bunch.py index 5efa79f..5efa79f 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/bunch.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/bunch.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/__init__.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/__init__.py index 5501cd4..5501cd4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apiparser.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apiparser.py index b6ccf22..b6ccf22 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apiparser.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apiparser.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apirenderer.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apirenderer.py index 36e46ef..36e46ef 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/apirenderer.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/apirenderer.py diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/documentationitem.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/documentationitem.py new file mode 100755 index 0000000..c72133a --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/documentationitem.py @@ -0,0 +1,124 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import sys, os, re + +class DocumentationItemInfo(object): + def __init__(self, env_root, md_path, filename): + self.env_root = env_root + # full path to MD file, without filename + self.source_path = md_path + # MD filename + self.source_filename = filename + + def env_root(self): + return self.env_root + + def source_path(self): + return self.source_path + + def source_filename(self): + return self.source_filename + + def base_filename(self): + return self.source_filename[:-len(".md")] + + def source_path_and_filename(self): + return os.sep.join([self.source_path, self.source_filename]) + + def source_path_relative_from_env_root(self): + return self.source_path[len(self.env_root) + 1:] + +class DevGuideItemInfo(DocumentationItemInfo): + def __init__(self, env_root, devguide_root, md_path, filename): + DocumentationItemInfo.__init__(self, env_root, md_path, filename) + self.devguide_root = devguide_root + + def source_path_relative_from_devguide_root(self): + return self.source_path[len(self.devguide_root) + 1:] + + def destination_path(self): + root_pieces = self.devguide_root.split(os.sep) + root_pieces[-1] = "dev-guide" + return os.sep.join([os.sep.join(root_pieces), self.source_path_relative_from_devguide_root()]) + +class ModuleInfo(DocumentationItemInfo): + def __init__(self, env_root, module_root, md_path, filename): + DocumentationItemInfo.__init__(self, env_root, md_path, filename) + self.module_root = module_root + + def js_module_path(self): + return os.path.join(self.env_root, "lib", self.source_path_relative_from_module_root(), self.source_filename[:-len(".md")] + ".js") + + def source_path_relative_from_module_root(self): + return self.source_path[len(self.module_root) + 1:] + + def destination_path(self): + if self.level() == "third-party": + return os.sep.join([self.env_root, "doc", "modules", "packages"]) + root_pieces = self.module_root.split(os.sep) + root_pieces[-1] = "modules" + relative_pieces = self.source_path_relative_from_module_root().split(os.sep) + return os.sep.join(root_pieces + relative_pieces) + + def relative_url(self): + if self.level() == "third-party": + relative_pieces = ["packages"] + else: + relative_pieces = self.source_path_relative_from_module_root().split(os.sep) + return "/".join(relative_pieces) + "/" + self.base_filename() + ".html" + + def name(self): + if os.sep.join([self.module_root, "sdk"]) == self.source_path or self.level() == "third-party": + return self.source_filename[:-3] + else: + path_from_root_pieces = self.source_path_relative_from_module_root().split(os.sep) + return "/".join(["/".join(path_from_root_pieces[1:]), self.source_filename[:-len(".md")]]) + + def level(self): + if self.source_path_relative_from_env_root().startswith("packages"): + return "third-party" + else: + if os.sep.join([self.module_root, "sdk"]) == self.source_path: + return "high" + else: + return "low" + +def get_modules_in_package(env_root, package_docs_dir, module_list, ignore_files_in_root): + for (dirpath, dirnames, filenames) in os.walk(package_docs_dir): + for filename in filenames: + # ignore files in the root + if ignore_files_in_root and package_docs_dir == dirpath: + continue + if filename.endswith(".md"): + module_list.append(ModuleInfo(env_root, package_docs_dir, dirpath, filename)) + +def get_module_list(env_root): + module_list = [] + # get the built-in modules + module_root = os.sep.join([env_root, "doc", "module-source"]) + get_modules_in_package(env_root, module_root, module_list, True) + # get the third-party modules + packages_root = os.sep.join([env_root, "packages"]) + if os.path.exists(packages_root): + for entry in os.listdir(packages_root): + if os.path.isdir(os.sep.join([packages_root, entry])): + package_docs = os.sep.join([packages_root, entry, "docs"]) + if os.path.exists(package_docs): + get_modules_in_package(env_root, package_docs, module_list, False) + module_list.sort(key=lambda x: x.name()) + return module_list + +def get_devguide_list(env_root): + devguide_list = [] + devguide_root = os.sep.join([env_root, "doc", "dev-guide-source"]) + for (dirpath, dirnames, filenames) in os.walk(devguide_root): + for filename in filenames: + if filename.endswith(".md"): + devguide_list.append(DevGuideItemInfo(env_root, devguide_root, dirpath, filename)) + return devguide_list + +if __name__ == "__main__": + module_list = get_module_list(sys.argv[1]) + print [module_info.name for module_info in module_list] diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/generate.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/generate.py new file mode 100755 index 0000000..b498f00 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/generate.py @@ -0,0 +1,199 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import os +import sys +import shutil +import hashlib +import tarfile +import StringIO + +from cuddlefish._version import get_versions +from cuddlefish.docs import apiparser +from cuddlefish.docs import apirenderer +from cuddlefish.docs import webdocs +from documentationitem import get_module_list +from documentationitem import get_devguide_list +from documentationitem import ModuleInfo +from documentationitem import DevGuideItemInfo +from linkrewriter import rewrite_links +import simplejson as json + +DIGEST = "status.md5" +TGZ_FILENAME = "addon-sdk-docs.tgz" + +def get_sdk_docs_path(env_root): + return os.path.join(env_root, "doc") + +def get_base_url(env_root): + sdk_docs_path = get_sdk_docs_path(env_root).lstrip("/") + return "file://"+"/"+"/".join(sdk_docs_path.split(os.sep))+"/" + +def clean_generated_docs(docs_dir): + status_file = os.path.join(docs_dir, "status.md5") + if os.path.exists(status_file): + os.remove(status_file) + index_file = os.path.join(docs_dir, "index.html") + if os.path.exists(index_file): + os.remove(index_file) + dev_guide_dir = os.path.join(docs_dir, "dev-guide") + if os.path.exists(dev_guide_dir): + shutil.rmtree(dev_guide_dir) + api_doc_dir = os.path.join(docs_dir, "modules") + if os.path.exists(api_doc_dir): + shutil.rmtree(api_doc_dir) + +def generate_static_docs(env_root, override_version=get_versions()["version"]): + clean_generated_docs(get_sdk_docs_path(env_root)) + generate_docs(env_root, override_version, stdout=StringIO.StringIO()) + tgz = tarfile.open(TGZ_FILENAME, 'w:gz') + tgz.add(get_sdk_docs_path(env_root), "doc") + tgz.close() + return TGZ_FILENAME + +def generate_local_docs(env_root): + return generate_docs(env_root, get_versions()["version"], get_base_url(env_root)) + +def generate_named_file(env_root, filename_and_path): + web_docs = webdocs.WebDocs(env_root, get_versions()["version"], get_base_url(env_root)) + abs_path = os.path.abspath(filename_and_path) + path, filename = os.path.split(abs_path) + if abs_path.startswith(os.path.join(env_root, 'doc', 'module-source')): + module_root = os.sep.join([env_root, "doc", "module-source"]) + module_info = ModuleInfo(module_root, path, filename) + write_module_doc(env_root, web_docs, module_info, False) + elif abs_path.startswith(os.path.join(get_sdk_docs_path(env_root), 'dev-guide-source')): + devguide_root = os.sep.join([env_root, "doc", "dev-guide-source"]) + devguideitem_info = DevGuideItemInfo(devguide_root, path, filename) + write_devguide_doc(env_root, web_docs, devguideitem_info, False) + else: + raise ValueError("Not a valid path to a documentation file") + +def generate_docs(env_root, version=get_versions()["version"], base_url=None, stdout=sys.stdout): + docs_dir = get_sdk_docs_path(env_root) + # if the generated docs don't exist, generate everything + if not os.path.exists(os.path.join(docs_dir, "dev-guide")): + print >>stdout, "Generating documentation..." + generate_docs_from_scratch(env_root, version, base_url) + current_status = calculate_current_status(env_root) + open(os.path.join(docs_dir, DIGEST), "w").write(current_status) + else: + current_status = calculate_current_status(env_root) + previous_status_file = os.path.join(docs_dir, DIGEST) + docs_are_up_to_date = False + if os.path.exists(previous_status_file): + docs_are_up_to_date = current_status == open(previous_status_file, "r").read() + # if the docs are not up to date, generate everything + if not docs_are_up_to_date: + print >>stdout, "Regenerating documentation..." + generate_docs_from_scratch(env_root, version, base_url) + open(os.path.join(docs_dir, DIGEST), "w").write(current_status) + return get_base_url(env_root) + "index.html" + +# this function builds a hash of the name and last modification date of: +# * every file in "doc/sdk" which ends in ".md" +# * every file in "doc/dev-guide-source" which ends in ".md" +# * every file in "doc/static-files" which does not start with "." +def calculate_current_status(env_root): + docs_dir = get_sdk_docs_path(env_root) + current_status = hashlib.md5() + module_src_dir = os.path.join(env_root, "doc", "module-source") + for (dirpath, dirnames, filenames) in os.walk(module_src_dir): + for filename in filenames: + if filename.endswith(".md"): + current_status.update(filename) + current_status.update(str(os.path.getmtime(os.path.join(dirpath, filename)))) + guide_src_dir = os.path.join(docs_dir, "dev-guide-source") + for (dirpath, dirnames, filenames) in os.walk(guide_src_dir): + for filename in filenames: + if filename.endswith(".md"): + current_status.update(filename) + current_status.update(str(os.path.getmtime(os.path.join(dirpath, filename)))) + package_dir = os.path.join(env_root, "packages") + for (dirpath, dirnames, filenames) in os.walk(package_dir): + for filename in filenames: + if filename.endswith(".md"): + current_status.update(filename) + current_status.update(str(os.path.getmtime(os.path.join(dirpath, filename)))) + base_html_file = os.path.join(docs_dir, "static-files", "base.html") + current_status.update(base_html_file) + current_status.update(str(os.path.getmtime(os.path.join(dirpath, base_html_file)))) + return current_status.digest() + +def generate_docs_from_scratch(env_root, version, base_url): + docs_dir = get_sdk_docs_path(env_root) + web_docs = webdocs.WebDocs(env_root, version, base_url) + must_rewrite_links = True + if base_url: + must_rewrite_links = False + clean_generated_docs(docs_dir) + + # py2.5 doesn't have ignore=, so we delete tempfiles afterwards. If we + # required >=py2.6, we could use ignore=shutil.ignore_patterns("*~") + for (dirpath, dirnames, filenames) in os.walk(docs_dir): + for n in filenames: + if n.endswith("~"): + os.unlink(os.path.join(dirpath, n)) + + # generate api docs for all modules + if not os.path.exists(os.path.join(docs_dir, "modules")): + os.mkdir(os.path.join(docs_dir, "modules")) + module_root = os.sep.join([env_root, "doc", "module-source"]) + module_list = get_module_list(env_root) + [write_module_doc(env_root, web_docs, module_info, must_rewrite_links) for module_info in module_list] + + # generate third-party module index + third_party_index_file = os.sep.join([env_root, "doc", "module-source", "third-party-modules.md"]) + third_party_module_list = [module_info for module_info in module_list if module_info.level() == "third-party"] + write_module_index(env_root, web_docs, third_party_index_file, third_party_module_list, must_rewrite_links) + + + # generate high-level module index + high_level_index_file = os.sep.join([env_root, "doc", "module-source", "high-level-modules.md"]) + high_level_module_list = [module_info for module_info in module_list if module_info.level() == "high"] + write_module_index(env_root, web_docs, high_level_index_file, high_level_module_list, must_rewrite_links) + + # generate low-level module index + low_level_index_file = os.sep.join([env_root, "doc", "module-source", "low-level-modules.md"]) + low_level_module_list = [module_info for module_info in module_list if module_info.level() == "low"] + write_module_index(env_root, web_docs, low_level_index_file, low_level_module_list, must_rewrite_links) + + # generate dev-guide docs + devguide_list = get_devguide_list(env_root) + [write_devguide_doc(env_root, web_docs, devguide_info, must_rewrite_links) for devguide_info in devguide_list] + + # make /md/dev-guide/welcome.html the top level index file + doc_html = web_docs.create_guide_page(os.path.join(docs_dir, 'dev-guide-source', 'index.md')) + write_file(env_root, doc_html, docs_dir, 'index', False) + +def write_module_index(env_root, web_docs, source_file, module_list, must_rewrite_links): + doc_html = web_docs.create_module_index(source_file, module_list) + base_filename, extension = os.path.splitext(os.path.basename(source_file)) + destination_path = os.sep.join([env_root, "doc", "modules"]) + write_file(env_root, doc_html, destination_path, base_filename, must_rewrite_links) + +def write_module_doc(env_root, web_docs, module_info, must_rewrite_links): + doc_html = web_docs.create_module_page(module_info.source_path_and_filename()) + write_file(env_root, doc_html, module_info.destination_path(), module_info.base_filename(), must_rewrite_links) + +def write_devguide_doc(env_root, web_docs, devguide_info, must_rewrite_links): + doc_html = web_docs.create_guide_page(devguide_info.source_path_and_filename()) + write_file(env_root, doc_html, devguide_info.destination_path(), devguide_info.base_filename(), must_rewrite_links) + +def write_file(env_root, doc_html, dest_dir, filename, must_rewrite_links): + if not os.path.exists(dest_dir): + os.makedirs(dest_dir) + dest_path_html = os.path.join(dest_dir, filename) + ".html" + replace_file(env_root, dest_path_html, doc_html, must_rewrite_links) + return dest_path_html + +def replace_file(env_root, dest_path, file_contents, must_rewrite_links): + if os.path.exists(dest_path): + os.remove(dest_path) + # before we copy the final version, we'll rewrite the links + # I'll do this last, just because we know definitely what the dest_path is at this point + if must_rewrite_links and dest_path.endswith(".html"): + file_contents = rewrite_links(env_root, get_sdk_docs_path(env_root), file_contents, dest_path) + open(dest_path, "w").write(file_contents) + diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/linkrewriter.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/linkrewriter.py new file mode 100644 index 0000000..11b0f11 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/linkrewriter.py @@ -0,0 +1,78 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import os +import sys +import HTMLParser +import urlparse + +def rewrite_links(env_root, sdk_docs_path, page, dest_path): + dest_path_depth = len(dest_path.split(os.sep)) -1 # because dest_path includes filename + docs_root_depth = len(sdk_docs_path.split(os.sep)) + relative_depth = dest_path_depth - docs_root_depth + linkRewriter = LinkRewriter("../" * relative_depth) + return linkRewriter.rewrite_links(page) + +class LinkRewriter(HTMLParser.HTMLParser): + def __init__(self, link_prefix): + HTMLParser.HTMLParser.__init__(self) + self.stack = [] + self.link_prefix = link_prefix + + def rewrite_links(self, page): + self.feed(page) + self.close() + page = ''.join(self.stack) + self.stack = [] + return page + + def handle_decl(self, decl): + self.stack.append("<!" + decl + ">") + + def handle_comment(self, decl): + self.stack.append("<!--" + decl + "-->") + + def handle_starttag(self, tag, attrs): + self.stack.append(self.__html_start_tag(tag, self._rewrite_link(attrs))) + + def handle_entityref(self, name): + self.stack.append("&" + name + ";") + + def handle_endtag(self, tag): + self.stack.append(self.__html_end_tag(tag)) + + def handle_startendtag(self, tag, attrs): + self.stack.append(self.__html_startend_tag(tag, self._rewrite_link(attrs))) + + def _update_attribute(self, attr_name, attrs): + attr_value = attrs.get(attr_name, '') + if attr_value: + parsed = urlparse.urlparse(attr_value) + if not parsed.scheme: + attrs[attr_name] = self.link_prefix + attr_value + + def _rewrite_link(self, attrs): + attrs = dict(attrs) + self._update_attribute('href', attrs) + self._update_attribute('src', attrs) + self._update_attribute('action', attrs) + return attrs + + def handle_data(self, data): + self.stack.append(data) + + def __html_start_tag(self, tag, attrs): + return '<%s%s>' % (tag, self.__html_attrs(attrs)) + + def __html_startend_tag(self, tag, attrs): + return '<%s%s/>' % (tag, self.__html_attrs(attrs)) + + def __html_end_tag(self, tag): + return '</%s>' % (tag) + + def __html_attrs(self, attrs): + _attrs = '' + if attrs: + _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in dict(attrs).iteritems()])) + return _attrs diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/renderapi.readme.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/renderapi.readme.md index 627c2a6..627c2a6 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/renderapi.readme.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/renderapi.readme.md diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/webdocs.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/webdocs.py new file mode 100755 index 0000000..f761282 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/docs/webdocs.py @@ -0,0 +1,106 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import os, re, errno +import markdown +import cgi + +from cuddlefish import packaging +from cuddlefish.docs import apirenderer +from cuddlefish._version import get_versions +from documentationitem import get_module_list + +INDEX_PAGE = '/doc/static-files/base.html' +BASE_URL_INSERTION_POINT = '<base ' +VERSION_INSERTION_POINT = '<div id="version">' +MODULE_INDEX_INSERTION_POINT = '<ul id="module-index">' +THIRD_PARTY_MODULE_SUMMARIES = '<ul id="third-party-module-summaries">' +HIGH_LEVEL_MODULE_SUMMARIES = '<ul id="high-level-module-summaries">' +LOW_LEVEL_MODULE_SUMMARIES = '<ul id="low-level-module-summaries">' +CONTENT_ID = '<div id="main-content">' +TITLE_ID = '<title>' +DEFAULT_TITLE = 'Add-on SDK Documentation' + +def tag_wrap(text, tag, attributes={}): + result = '\n<' + tag + for name in attributes.keys(): + result += ' ' + name + '=' + '"' + attributes[name] + '"' + result +='>' + text + '</'+ tag + '>\n' + return result + +def insert_after(target, insertion_point_id, text_to_insert): + insertion_point = target.find(insertion_point_id) + len(insertion_point_id) + return target[:insertion_point] + text_to_insert + target[insertion_point:] + +class WebDocs(object): + def __init__(self, root, version=get_versions()["version"], base_url = None): + self.root = root + self.version = version + self.pkg_cfg = packaging.build_pkg_cfg(root) + self.packages_json = packaging.build_pkg_index(self.pkg_cfg) + self.base_page = self._create_base_page(root, base_url) + + def create_guide_page(self, path): + md_content = unicode(open(path, 'r').read(), 'utf8') + guide_content = markdown.markdown(md_content) + return self._create_page(guide_content) + + def create_module_index(self, path, module_list): + md_content = unicode(open(path, 'r').read(), 'utf8') + index_content = markdown.markdown(md_content) + module_list_content = self._make_module_text(module_list) + index_content = insert_after(index_content, MODULE_INDEX_INSERTION_POINT, module_list_content) + return self._create_page(index_content) + + def create_module_page(self, path): + module_content = apirenderer.md_to_div(path) + return self._create_page(module_content) + + def _create_page(self, page_content): + page = self._insert_title(self.base_page, page_content) + page = insert_after(page, CONTENT_ID, page_content) + return page.encode('utf8') + + def _make_module_text(self, module_list): + module_text = '' + for module in module_list: + module_link = tag_wrap(module.name(), 'a', \ + {'href': "/".join(["modules", module.relative_url()])}) + module_list_item = tag_wrap(module_link, "li") + module_text += module_list_item + return module_text + + def _create_base_page(self, root, base_url): + base_page = unicode(open(root + INDEX_PAGE, 'r').read(), 'utf8') + if base_url: + base_tag = 'href="' + base_url + '"' + base_page = insert_after(base_page, BASE_URL_INSERTION_POINT, base_tag) + base_page = insert_after(base_page, VERSION_INSERTION_POINT, "Version " + self.version) + module_list = get_module_list(root) + + third_party_module_list = [module_info for module_info in module_list if module_info.level() == "third-party"] + third_party_module_text = self._make_module_text(third_party_module_list) + base_page = insert_after(base_page, \ + THIRD_PARTY_MODULE_SUMMARIES, third_party_module_text) + + high_level_module_list = [module_info for module_info in module_list if module_info.level() == "high"] + high_level_module_text = self._make_module_text(high_level_module_list) + base_page = insert_after(base_page, \ + HIGH_LEVEL_MODULE_SUMMARIES, high_level_module_text) + + low_level_module_list = [module_info for module_info in module_list if module_info.level() == "low"] + low_level_module_text = self._make_module_text(low_level_module_list) + base_page = insert_after(base_page, \ + LOW_LEVEL_MODULE_SUMMARIES, low_level_module_text) + return base_page + + def _insert_title(self, target, content): + match = re.search('<h1>.*</h1>', content) + if match: + title = match.group(0)[len('<h1>'):-len('</h1>')] + ' - ' + \ + DEFAULT_TITLE + else: + title = DEFAULT_TITLE + target = insert_after(target, TITLE_ID, title) + return target diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/manifest.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/manifest.py index 7309db5..b1f9367 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/manifest.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/manifest.py @@ -8,6 +8,11 @@ import simplejson as json SEP = os.path.sep from cuddlefish.util import filter_filenames, filter_dirnames +# Load new layout mapping hashtable +path = os.path.join(os.environ.get('CUDDLEFISH_ROOT'), "mapping.json") +data = open(path, 'r').read() +NEW_LAYOUT_MAPPING = json.loads(data) + def js_zipname(packagename, modulename): return "%s-lib/%s.js" % (packagename, modulename) def docs_zipname(packagename, modulename): @@ -77,13 +82,6 @@ class ManifestEntry: # allowed to require() it entry["requirements"][req] = self.requirements[req] assert isinstance(entry["requirements"][req], dict) - if self.datamap: - entry["requirements"]["self"] = { - "path": "self", - "mapSHA256": self.datamap.data_manifest_hash, - "mapName": self.packageName+"-data", - "dataURIPrefix": "%s/data/" % (self.packageName), - } return entry def add_js(self, js_filename): @@ -187,10 +185,12 @@ class ManifestBuilder: # process the top module, which recurses to process everything it # reaches if "main" in self.target_cfg: - top_me = self.process_module(self.find_top(self.target_cfg)) + top_mi = self.find_top(self.target_cfg) + top_me = self.process_module(top_mi) self.top_path = top_me.get_path() + self.datamaps[self.target_cfg.name] = DataMap(self.target_cfg) if scan_tests: - mi = self._find_module_in_package("test-harness", "lib", "run-tests", []) + mi = self._find_module_in_package("addon-sdk", "lib", "sdk/test/runner", []) self.process_module(mi) # also scan all test files in all packages that we use. By making # a copy of self.used_packagenames first, we refrain from @@ -218,8 +218,8 @@ class ManifestBuilder: test_modules.append( (testname, tme) ) # also add it as an artificial dependency of unit-test-finder, so # the runtime dynamic load can work. - test_finder = self.get_manifest_entry("api-utils", "lib", - "unit-test-finder") + test_finder = self.get_manifest_entry("addon-sdk", "lib", + "sdk/deprecated/unit-test-finder") for (testname,tme) in test_modules: test_finder.add_requirement(testname, tme) # finally, tell the runtime about it, so they won't have to @@ -252,11 +252,12 @@ class ManifestBuilder: # returns all .js files that we reference, plus data/ files. You will # need to add the loader, off-manifest files that it needs, and # generated metadata. + for datamap in self.datamaps.values(): + for (zipname, absname) in datamap.files_to_copy: + yield absname + for me in self.get_module_entries(): yield me.js_filename - if me.datamap: - for (zipname, absname) in me.datamap.files_to_copy: - yield absname def get_all_test_modules(self): return self.test_modules @@ -374,16 +375,10 @@ class ManifestBuilder: # traversal of the module graph for reqname in sorted(requires.keys()): - if reqname in ("chrome", "@packaging", "@loader"): + # If requirement is chrome or a pseudo-module (starts with @) make + # path a requirement name. + if reqname == "chrome" or reqname.startswith("@"): me.add_requirement(reqname, {"path": reqname}) - elif reqname == "self": - # this might reference bundled data, so: - # 1: hash that data, add the hash as a dependency - # 2: arrange for the data to be copied into the XPI later - if pkg.name not in self.datamaps: - self.datamaps[pkg.name] = DataMap(pkg) - dm = self.datamaps[pkg.name] - me.add_data(dm) # 'self' is implicit else: # when two modules require() the same name, do they get a # shared instance? This is a deep question. For now say yes. @@ -437,12 +432,12 @@ class ManifestBuilder: modulename = from_module.name #print " %s require(%s))" % (from_module, reqname) - bits = reqname.split("/") if reqname.startswith("./") or reqname.startswith("../"): # 1: they want something relative to themselves, always from # their own package them = modulename.split("/")[:-1] + bits = reqname.split("/") while bits[0] in (".", ".."): if not bits: raise BAD("no actual modulename") @@ -461,8 +456,21 @@ class ManifestBuilder: # non-relative import. Might be a short name (requiring a search # through "library" packages), or a fully-qualified one. + # Search for a module in new layout. + # First normalize require argument in order to easily find a mapping + normalized = reqname + if normalized.endswith(".js"): + normalized = normalized[:-len(".js")] + if normalized.startswith("addon-kit/"): + normalized = normalized[len("addon-kit/"):] + if normalized.startswith("api-utils/"): + normalized = normalized[len("api-utils/"):] + if normalized in NEW_LAYOUT_MAPPING: + reqname = NEW_LAYOUT_MAPPING[normalized] + if "/" in reqname: # 2: PKG/MOD: find PKG, look inside for MOD + bits = reqname.split("/") lookfor_pkg = bits[0] lookfor_mod = "/".join(bits[1:]) mi = self._get_module_from_package(lookfor_pkg, @@ -611,8 +619,8 @@ def build_manifest(target_cfg, pkg_cfg, deps, scan_tests, COMMENT_PREFIXES = ["//", "/*", "*", "dump("] -#REQUIRE_RE = r"(?<![\'\"])require\s*\(\s*[\'\"]([^\'\"]+?)[\'\"]\s*\)" REQUIRE_RE = r"(?<!goog[.])(?<![\'\"])\brequire\s*\(\s*[\'\"]([^\'\"]+?)[\'\"]\s*\)" +#REQUIRE_RE = r"(?<![\'\"])require\s*\(\s*[\'\"]([^\'\"]+?)[\'\"]\s*\)" # detect the define idiom of the form: # define("module name", ["dep1", "dep2", "dep3"], function() {}) @@ -705,16 +713,10 @@ line somewhat like the following: const {%(needs)s} = require("chrome"); -Then you can use 'Components' as well as any shortcuts to its properties -that you import from the 'chrome' module ('Cc', 'Ci', 'Cm', 'Cr', and -'Cu' for the 'classes', 'interfaces', 'manager', 'results', and 'utils' -properties, respectively). - -(Note: once bug 636145 is fixed, to access 'Components' directly you'll -need to retrieve it from the 'chrome' module by adding it to the list of -symbols you import from the module. To avoid having to make this change -in the future, replace all occurrences of 'Components' in your code with -the equivalent shortcuts now.) +Then you can use any shortcuts to its properties that you import from the +'chrome' module ('Cc', 'Ci', 'Cm', 'Cr', and 'Cu' for the 'classes', +'interfaces', 'manager', 'results', and 'utils' properties, respectively. And +`components` for `Components` object itself). """ % { "fn": fn, "needs": ",".join(sorted(old_chrome)), "lines": "\n".join([" %3d: %s" % (lineno,line) for (lineno, line) in old_chrome_lines]), @@ -728,10 +730,6 @@ def scan_module(fn, lines, stderr=sys.stderr): if filename == "cuddlefish.js": # this is the loader: don't scan for chrome problems = False - elif "chrome" in requires: - # if they declare require("chrome"), we tolerate the use of - # Components (see bug 663541 for rationale) - problems = False else: problems = scan_for_bad_chrome(fn, lines, stderr) return requires, problems, locations diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/bootstrap.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/bootstrap.js new file mode 100644 index 0000000..752c962 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/bootstrap.js @@ -0,0 +1,55 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cu = Components.utils; +const Cr = Components.results; + +Components.utils.import("resource://gre/modules/Services.jsm"); + +const DEBUG = false; + +let log = DEBUG ? dump : function (){}; + + +function startup(data, reason) { + // This code allow to make all stdIO work + try { + Components.utils.import("resource://gre/modules/ctypes.jsm"); + let libdvm = ctypes.open("libdvm.so"); + let dvmStdioConverterStartup; + // Starting with Android ICS, dalvik uses C++. + // So that the symbol isn't a simple C one + try { + dvmStdioConverterStartup = libdvm.declare("_Z24dvmStdioConverterStartupv", ctypes.default_abi, ctypes.bool); + } + catch(e) { + // Otherwise, before ICS, it was a pure C library + dvmStdioConverterStartup = libdvm.declare("dvmStdioConverterStartup", ctypes.default_abi, ctypes.void_t); + } + dvmStdioConverterStartup(); + log("MU: console redirected to adb logcat.\n"); + } catch(e) { + Cu.reportError("MU: unable to execute jsctype hack: "+e); + } + + try { + let QuitObserver = { + observe: function (aSubject, aTopic, aData) { + Services.obs.removeObserver(QuitObserver, "quit-application", false); + dump("MU: APPLICATION-QUIT\n"); + } + }; + Services.obs.addObserver(QuitObserver, "quit-application", false); + log("MU: ready to watch firefox exit.\n"); + } catch(e) { + log("MU: unable to register quit-application observer: " + e + "\n"); + } +} + +function install() {} +function shutdown() {} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/install.rdf b/tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/install.rdf index 0b81a0e..0b81a0e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/install.rdf +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/mobile-utils/install.rdf diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/options_defaults.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/options_defaults.py index 5931a26..5931a26 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/options_defaults.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/options_defaults.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/options_xul.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/options_xul.py index 6f11311..99fa1a4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/options_xul.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/options_xul.py @@ -5,7 +5,7 @@ from xml.dom.minidom import Document VALID_PREF_TYPES = ['bool', 'boolint', 'integer', 'string', 'color', 'file', - 'directory', 'control'] + 'directory', 'control', 'menulist', 'radio'] class Error(Exception): pass @@ -31,6 +31,18 @@ def validate_prefs(options): if ("label" not in pref): raise MissingPrefAttr("The 'control' inline pref type requires a 'label'") + # Make sure the 'menulist' type has a 'menulist' + if (pref["type"] == "menulist" or pref["type"] == "radio"): + if ("options" not in pref): + raise MissingPrefAttr("The 'menulist' and the 'radio' inline pref types requires a 'options'") + + # Make sure each option has a 'value' and a 'label' + for item in pref["options"]: + if ("value" not in item): + raise MissingPrefAttr("'options' requires a 'value'") + if ("label" not in item): + raise MissingPrefAttr("'options' requires a 'label'") + # TODO: Check that pref["type"] matches default value type def parse_options(options, jetpack_id): @@ -41,6 +53,8 @@ def parse_options(options, jetpack_id): for pref in options: setting = doc.createElement("setting") + setting.setAttribute("pref-name", pref["name"]) + setting.setAttribute("data-jetpack-id", jetpack_id) setting.setAttribute("pref", "extensions." + jetpack_id + "." + pref["name"]) setting.setAttribute("type", pref["type"]) setting.setAttribute("title", pref["title"]) @@ -50,6 +64,8 @@ def parse_options(options, jetpack_id): if (pref["type"] == "control"): button = doc.createElement("button") + button.setAttribute("pref-name", pref["name"]) + button.setAttribute("data-jetpack-id", jetpack_id) button.setAttribute("label", pref["label"]) button.setAttribute("oncommand", "Services.obs.notifyObservers(null, '" + jetpack_id + "-cmdPressed', '" + @@ -58,6 +74,24 @@ def parse_options(options, jetpack_id): elif (pref["type"] == "boolint"): setting.setAttribute("on", pref["on"]) setting.setAttribute("off", pref["off"]) + elif (pref["type"] == "menulist"): + menulist = doc.createElement("menulist") + menupopup = doc.createElement("menupopup") + for item in pref["options"]: + menuitem = doc.createElement("menuitem") + menuitem.setAttribute("value", item["value"]) + menuitem.setAttribute("label", item["label"]) + menupopup.appendChild(menuitem) + menulist.appendChild(menupopup) + setting.appendChild(menulist) + elif (pref["type"] == "radio"): + radiogroup = doc.createElement("radiogroup") + for item in pref["options"]: + radio = doc.createElement("radio") + radio.setAttribute("value", item["value"]) + radio.setAttribute("label", item["label"]) + radiogroup.appendChild(radio) + setting.appendChild(radiogroup) root.appendChild(setting) diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/packaging.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/packaging.py index 757d5ac..9e08b66 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/packaging.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/packaging.py @@ -11,8 +11,10 @@ import simplejson as json from cuddlefish.bunch import Bunch MANIFEST_NAME = 'package.json' +DEFAULT_LOADER = 'addon-sdk' -DEFAULT_LOADER = 'api-utils' +# Is different from root_dir when running tests +env_root = os.environ.get('CUDDLEFISH_ROOT') DEFAULT_PROGRAM_MODULE = 'main' @@ -213,6 +215,12 @@ def get_config_in_dir(path): base_json.root_dir = path + if "dependencies" in base_json: + deps = base_json["dependencies"] + deps = [x for x in deps if x not in ["addon-kit", "api-utils"]] + deps.append("addon-sdk") + base_json["dependencies"] = deps + return base_json def _is_same_file(a, b): @@ -221,7 +229,7 @@ def _is_same_file(a, b): return a == b def build_config(root_dir, target_cfg, packagepath=[]): - dirs_to_scan = [] + dirs_to_scan = [env_root] # root is addon-sdk dir, diff from root_dir in tests def add_packages_from_config(pkgconfig): if 'packages' in pkgconfig: @@ -282,6 +290,7 @@ def get_deps_for_targets(pkg_cfg, targets): def generate_build_for_target(pkg_cfg, target, deps, include_tests=True, include_dep_tests=False, + is_running_tests=False, default_loader=DEFAULT_LOADER): build = Bunch(# Contains section directories for all packages: @@ -316,6 +325,10 @@ def generate_build_for_target(pkg_cfg, target, deps, build.packages[cfg.name][section] = dirname def add_locale_to_build(cfg): + # Bug 730776: Ignore locales for addon-kit, that are only for unit tests + if not is_running_tests and cfg.name == "addon-sdk": + return + path = resolve_dir(cfg, cfg['locale']) files = os.listdir(path) for filename in files: diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/preflight.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/preflight.py index 8b500ec..8b500ec 100755 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/preflight.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/preflight.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/prefs.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/prefs.py index 8d20039..f3a82fe 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/prefs.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/prefs.py @@ -29,6 +29,9 @@ DEFAULT_COMMON_PREFS = { # Allow installing extensions dropped into the profile folder 'extensions.autoDisableScopes' : 10, + # Disable app update + 'app.update.enabled' : False, + # Point update checks to a nonexistent local URL for fast failures. 'extensions.update.url' : 'http://localhost/extensions-dummy/updateURL', 'extensions.blocklist.url' : 'http://localhost/extensions-dummy/blocklistURL', diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/property_parser.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/property_parser.py index b3f554d..5d75717 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/property_parser.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/property_parser.py @@ -91,13 +91,17 @@ def normalize_plural(path, pairs): continue main_key = m.group(1) plural_form = m.group(2) + # Allows not specifying a generic key (i.e a key without [form]) if not main_key in pairs: - raise MalformedLocaleFileError( - 'Following locale file is not a valid UTF-8 file: %s\n' - 'This plural form doesn\'t have a matching generic form:\n' - '%s\n' - 'You have to defined following key:\n%s' - % (path, key, main_key)) + pairs[main_key] = {} + # Ensure that we always have the [other] form + if not main_key + "[other]" in pairs: + raise MalformedLocaleFileError( + 'Following locale file is not a valid UTF-8 file: %s\n' + 'This plural form doesn\'t have a matching `%s[other]` form:\n' + '%s\n' + 'You have to defined following key:\n%s' + % (path, main_key, key, main_key)) # convert generic form into an object if it is still a string if isinstance(pairs[main_key], unicode): pairs[main_key] = {"other": pairs[main_key]} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/rdf.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/rdf.py index 389f512..3f58d88 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/rdf.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/rdf.py @@ -160,11 +160,11 @@ def gen_manifest(template_root_dir, target_cfg, jid, ta_desc.appendChild(elem) elem = dom.createElement("em:minVersion") - elem.appendChild(dom.createTextNode("10.0")) + elem.appendChild(dom.createTextNode("17.0")) ta_desc.appendChild(elem) elem = dom.createElement("em:maxVersion") - elem.appendChild(dom.createTextNode("13.0a1")) + elem.appendChild(dom.createTextNode("18.*")) ta_desc.appendChild(elem) if target_cfg.get("homepage"): @@ -176,7 +176,7 @@ def gen_manifest(template_root_dir, target_cfg, jid, if __name__ == "__main__": print "Running smoke test." - root = os.path.join(os.path.dirname(__file__), 'app-extension') + root = os.path.join(os.path.dirname(__file__), '../../app-extension') manifest = gen_manifest(root, {'name': 'test extension'}, 'fakeid', 'http://foo.com/update.rdf') update = RDFUpdate() diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/runner.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/runner.py index 76be215..337a998 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/runner.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/runner.py @@ -20,7 +20,7 @@ from cuddlefish.prefs import DEFAULT_FENNEC_PREFS # Used to remove noise from ADB output CLEANUP_ADB = re.compile(r'^(I|E)/(stdout|stderr|GeckoConsole)\s*\(\s*\d+\):\s*(.*)$') # Used to filter only messages send by `console` module -FILTER_ONLY_CONSOLE_FROM_ADB = re.compile(r'^I/(stderr)\s*\(\s*\d+\):\s*((info|warning|error|debug): .*)$') +FILTER_ONLY_CONSOLE_FROM_ADB = re.compile(r'^I/(stdout|stderr)\s*\(\s*\d+\):\s*((info|warning|error|debug): .*)$') # Maximum time we'll wait for tests to finish, in seconds. # The purpose of this timeout is to recover from infinite loops. It should be @@ -186,14 +186,14 @@ class RemoteFennecRunner(mozrunner.Runner): # First try to kill firefox if it is already running pid = self.getProcessPID(self._intent_name) if pid != None: - # Send a key "up" signal to mobile-utils addon - # in order to kill running firefox instance - # KEYCODE_DPAD_UP = 19 - # http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_DPAD_UP print "Killing running Firefox instance ..." - subprocess.call([self._adb_path, "shell", "input keyevent 19"]) - subprocess.Popen(self.command, stdout=subprocess.PIPE).wait() + subprocess.call([self._adb_path, "shell", + "am force-stop " + self._intent_name]) time.sleep(2) + if self.getProcessPID(self._intent_name) != None: + raise Exception("Unable to automatically kill running Firefox" + + " instance. Please close it manually before " + + "executing cfx.") print "Pushing the addon to your device" @@ -590,7 +590,7 @@ def run_app(harness_root_dir, manifest_rdf, harness_options, # Note: this regex doesn't handle all valid versions in the Toolkit Version # Format <https://developer.mozilla.org/en/Toolkit_version_format>, just the # common subset that we expect Mozilla apps to use. - mo = re.search(r"Mozilla (Firefox|Iceweasel|Fennec) ((\d+)\.\S*)", + mo = re.search(r"Mozilla (Firefox|Iceweasel|Fennec)\b[^ ]* ((\d+)\.\S*)", version_output) if not mo: # cfx may be used with Thunderbird, SeaMonkey or an exotic Firefox diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/templates.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/templates.py new file mode 100644 index 0000000..808f03d --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/templates.py @@ -0,0 +1,31 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#Template used by test-main.js +TEST_MAIN_JS = '''\ +var main = require("main"); + +exports["test main"] = function(assert) { + assert.pass("Unit test running!"); +}; + +exports["test main async"] = function(assert, done) { + assert.pass("async Unit test running!"); + done(); +}; + +require("test").run(exports); +''' + +#Template used by package.json +PACKAGE_JSON = '''\ +{ + "name": "%(name)s", + "fullName": "%(fullName)s", + "description": "a basic add-on", + "author": "", + "license": "MPL 2.0", + "version": "0.1" +} +''' diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/__init__.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/__init__.py index c1a7fd2..c1a7fd2 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/main.js index 980ea88..980ea88 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/package.json index afbc158..afbc158 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js index 533cd34..533cd34 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/addons/simplest-test/tests/test-minimal.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon.png diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/explicit-icon64.png diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json index 8d56d74..8d56d74 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/explicit-icon/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon.png diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/icon64.png diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json index 3f0e241..3f0e241 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/implicit-icon/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json index 3f0e241..3f0e241 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588119-files/packages/no-icon/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/lib/bar-loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json index e83a9d4..e83a9d4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/bar/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/lib/foo-loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json index 4648df6..4648df6 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-588661-files/packages/foo/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md index 54518d3..54518d3 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/docs/main.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js index aeda0e7..aeda0e7 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json index 45d409a..45d409a 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-611495-files/jspath-one/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/doc/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/lib/foo-loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json index ccc61b2..ccc61b2 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/commonjs-naming/test/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/docs/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/lib/foo-loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json index ccc61b2..ccc61b2 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-614712-files/packages/original-naming/tests/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/doc/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/lib/loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json index c2d22aa..c2d22aa 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-lib/test/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/locale/emptyFolder diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json index 0967ef4..0967ef4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-locale/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/doc/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json index 100249f..100249f 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/default-root/test/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/alt-lib/loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/doc/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json index f79250e..f79250e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-dir-lib/test/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js index 2daeb35..2daeb35 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/alt2-lib/loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md index c92ddb8..c92ddb8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/doc/foo.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json index b017baa..b017baa 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js index bd0cfa9..bd0cfa9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-652227-files/packages/explicit-lib/test/test-foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md index 54518d3..54518d3 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/docs/main.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js index aeda0e7..aeda0e7 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json index de868f7..de868f7 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-669274-files/packages/extra-options/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json index d18aa3d..d18aa3d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-1-pack/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json index 9bcf1eb..9bcf1eb 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-2-unpack/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json index 45d1d91..45d1d91 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/bug-715340-files/pkg-3-pack/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js index ad54ae7..ad54ae7 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar-e10s-adapter.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js index fe9e4fb..fe9e4fb 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/bar.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js index 55633d1..55633d1 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/lib/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json index 0967ef4..0967ef4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/e10s-adapter-files/packages/foo/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/lib/main.js index e32a30f..e32a30f 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/package.json index 98e4b85..98e4b85 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/five/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/five/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js index 7e1ce7e..7e1ce7e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/lib/misc.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json index 3010fae..3010fae 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js index 7e1ce7e..7e1ce7e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four-deps/four-a/topfiles/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/lib/main.js index b95f7bd..b95f7bd 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/package.json index 53180b9..53180b9 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/four/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/four/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/main.js index 7b1f0de..88fd751 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/main.js @@ -5,5 +5,5 @@ var panel = require("panel"); var two = require("two.js"); var a = require("./two"); -var b = require("addon-kit/tabs.js"); +var b = require("sdk/tabs.js"); var c = require("./subdir/three"); diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js index b594f3c..b594f3c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/subdir/three.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/two.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/two.js index 9765219..9765219 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/lib/two.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/lib/two.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/package.json index edd2b17..edd2b17 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/one/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/one/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/data/text.data b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/data/text.data index 1269488..1269488 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/data/text.data +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/data/text.data diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js index b860821..b860821 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js index a7b1c14..a7b1c14 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/lib/unused.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/package.json index 922c77d..922c77d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/seven/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/seven/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js index ada31ef..ada31ef 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/lib/unused.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/package.json index 906b249..906b249 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/unreachable.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/unreachable.js index e8b229c..e8b229c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/six/unreachable.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/six/unreachable.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js index cee7380..cee7380 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js index aec24d0..aec24d0 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/subdir/subfile.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js index 36c4a4e..36c4a4e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/lib/unused.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties index 980ac46..980ac46 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/locale/fr-FR.properties diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json index 6b796fc..6b796fc 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js index 7e1ce7e..7e1ce7e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties index c1bf146..c1bf146 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/locale/fr-FR.properties diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json index c0ff5ee..c0ff5ee 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-b/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js index 7e1ce7e..7e1ce7e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js index 5878496..5878496 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/lib/sub/foo.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties index dac3f13..dac3f13 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/locale/fr-FR.properties diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json index 169c914..169c914 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three-deps/three-c/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/msg.txt b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/msg.txt index 3b18e51..3b18e51 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/msg.txt +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/msg.txt diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/subdir/submsg.txt b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/subdir/submsg.txt index d2cfe80..d2cfe80 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three-deps/three-a/data/subdir/submsg.txt +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/data/subdir/submsg.txt diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/lib/main.js index 4f59443..4f59443 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/package.json index cbfbc5b..cbfbc5b 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js index edbc08e..edbc08e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/nontest.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js index edbc08e..edbc08e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-one.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js index edbc08e..edbc08e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/linker-files/three/tests/test-two.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json index f1d51b0..f1d51b0 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/no-prefs/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js index b7e0a1d..b7e0a1d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/lib/main.js diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json new file mode 100644 index 0000000..a6bf06b --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json @@ -0,0 +1,50 @@ +{ + "id": "jid1-fZHqN9JfrDBa8A", + "fullName": "Simple Prefs Test", + "author": "Erik Vold", + "preferences": [{ + "name": "test", + "type": "bool", + "title": "tëst", + "value": false + }, + { + "name": "test2", + "type": "string", + "title": "tëst", + "value": "ünicødé" + }, + { + "name": "test3", + "type": "menulist", + "title": "\"><test", + "value": "1", + "options": [ + { + "value": "0", + "label": "label1" + }, + { + "value": "1", + "label": "label2" + } + ] + }, + { + "name": "test4", + "type": "radio", + "title": "tëst", + "value": "red", + "options": [ + { + "value": "red", + "label": "rouge" + }, + { + "value": "blue", + "label": "bleu" + } + ] + }], + "loader": "lib/main.js" +} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md index 0f03259..0f03259 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/index.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md index 9859f33..9859f33 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/dev-guide-source/no_h1.md diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/high-level-modules.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/high-level-modules.md new file mode 100644 index 0000000..8745e13 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/high-level-modules.md @@ -0,0 +1,18 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +# High-Level APIs # + +Modules in this section implement high-level APIs for +building add-ons: + +* creating user interfaces +* interacting with the web +* interacting with the browser + +Unless the documentation explicitly says otherwise, all these modules are +"supported": meaning that they are relatively stable, and that we'll avoid +making incompatible changes to them unless absolutely necessary. + +<ul id="module-index"></ul> diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/low-level-modules.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/low-level-modules.md new file mode 100644 index 0000000..bc44007 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/low-level-modules.md @@ -0,0 +1,36 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +# Low-Level APIs # + +Modules in this section implement low-level APIs. These +modules fall roughly into three categories: + +* fundamental utilities such as +[collection](modules/sdk/util/collection.html) and +[url](modules/sdk/url.html). Many add-ons are likely to +want to use modules from this category. + +* building blocks for higher level modules, such as +[events](modules/sdk/events/core.html), +[worker](modules/sdk/content/worker.html), and +[api-utils](modules/sdk/deprecated/api-utils.html). You're more +likely to use these if you are building your own modules that +implement new APIs, thus extending the SDK itself. + +* privileged modules that expose powerful low-level capabilities +such as [window/utils](modules/sdk/window/utils.html) and +[xhr](modules/sdk/net/xhr.html). You can use these +modules in your add-on if you need to, but should be aware that +the cost of privileged access is the need to take more elaborate +security precautions. In many cases these modules have simpler, +more restricted analogs among the "High-Level APIs" (for +example, [windows](modules/sdk/windows.html) or +[request](modules/sdk/request.html)). + +These modules are still in active development, and we expect to +make incompatible changes to them in future releases. + + +<ul id="module-index"></ul> diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/aardvark-feeder.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/aardvark-feeder.md index 3845955..3845955 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/aardvark-feeder.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/aardvark-feeder.md diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/anteater/anteater.md index 27daf30..c480ce3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/anteater/anteater.md @@ -2,6 +2,9 @@ - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> -`cuddlefish` is the name of the SDK's module loader. +The `anteater` module should not be used by anyone. -This module still needs to be documented. +<api name="release"> +@function + Releases the anteater. Do not call this function. +</api> diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/main.md index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/main.md diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/not_a_doc.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/not_a_doc.js new file mode 100644 index 0000000..f4abc3b --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/sdk/not_a_doc.js @@ -0,0 +1,5 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +not a doc
\ No newline at end of file diff --git a/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/third-party-modules.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/third-party-modules.md new file mode 100644 index 0000000..33e957c --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/module-source/third-party-modules.md @@ -0,0 +1,11 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +# Third-party APIs # + +This section include modules you've added to the SDK. The tutorial on +[adding menu items to Firefox](dev-guide/tutorials/adding-menus.html) +explains how to add third-party modules to your SDK installation. + +<ul id="module-index"></ul> diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html index d40a2e8..d40a2e8 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/another.html diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html index 56c993d..3dd3df1 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/base.html @@ -88,7 +88,7 @@ <li class="sidebar-subsection"> <a href="dev-guide/high-level-apis.html"><h3 class="sidebar-subsection-header">High-Level APIs</h3></a> <div class="sidebar-subsection-contents"> - <ul id="high-level-package-summaries"></ul> + <ul id="high-level-module-summaries"></ul> </div> </li> @@ -104,7 +104,7 @@ <li class="sidebar-subsection"> <a href="dev-guide/low-level-apis.html"><h3 class="sidebar-subsection-header">Low-Level APIs</h3></a> <div class="sidebar-subsection-contents"> - <ul id="low-level-package-summaries"></ul> + <ul id="low-level-module-summaries"></ul> </div> </li> diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html index 1909a18..1909a18 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/doc/static-files/index.html diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIreference.html b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIreference.html index e302641..e302641 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIreference.html +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIreference.html diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIsample.md b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIsample.md index c5090c3..c5090c3 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/docs/APIsample.md +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/docs/APIsample.md diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/__init__.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md index e69de29..e69de29 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/doc/main.md diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me index 014242c..014242c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/ignore_me diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js index 0264872..0264872 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too index 066f9b5..066f9b5 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/lib/surprise.js/ignore_me_too diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json index 07eb9b9..afb5698 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/aardvark/package.json @@ -3,5 +3,5 @@ "description": "A package w/ a main module; can be built into an extension.", "keywords": ["potato"], "version": "1.0", - "dependencies": ["api-utils", "barbeque"] + "dependencies": ["addon-sdk", "barbeque"] } diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js index 0264872..0264872 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json index 0e2b552..9684581 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/anteater_files/package.json @@ -4,5 +4,5 @@ "description": "A package w/ a main module; can be built into an extension.", "keywords": ["potato"], "version": "1.0", - "dependencies": ["api-utils", "barbeque"] + "dependencies": ["addon-sdk", "barbeque"] } diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js index 361846d..361846d 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/lib/loader.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json index 64eb065..64eb065 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/api-utils/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js index ff982ae..ff982ae 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/lib/bar-module.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json index 62e3c12..62e3c12 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/barbeque/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js index aeda0e7..aeda0e7 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/lib/main.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json index 530f3c2..530f3c2 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/packages/minimal/package.json diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js index a20bf3f..a20bf3f 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/static-files/xpi-template/components/harness.js diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apiparser.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apiparser.py index c24f5c3..c24f5c3 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apiparser.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apiparser.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apirenderer.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apirenderer.py index 24a1c7c..24a1c7c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_apirenderer.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_apirenderer.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_generate.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_generate.py index ce5665e..901c889 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_generate.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_generate.py @@ -16,12 +16,14 @@ from cuddlefish.tests import env_root INITIAL_FILESET = [ ["static-files", "base.html"], \ ["dev-guide", "index.html"], \ - ["packages", "aardvark", "index.html"] ] + ["modules", "sdk", "aardvark-feeder.html"], \ + ["modules", "sdk", "anteater", "anteater.html"]] EXTENDED_FILESET = [ ["static-files", "base.html"], \ ["dev-guide", "extra.html"], \ ["dev-guide", "index.html"], \ - ["packages", "aardvark", "index.html"] ] + ["modules", "sdk", "aardvark-feeder.html"], \ + ["modules", "sdk", "anteater", "anteater.html"]] EXTRAFILE = ["dev-guide", "extra.html"] @@ -90,6 +92,13 @@ class Link_Checker(HTMLParser.HTMLParser): class Generate_Docs_Tests(unittest.TestCase): def test_generate_static_docs(self): + + def cleanup(): + shutil.rmtree(get_base_url_path()) + tgz.close() + os.remove(tar_filename) + generate.clean_generated_docs(os.path.join(env_root, "doc")) + # make sure we start clean if os.path.exists(get_base_url_path()): shutil.rmtree(get_base_url_path()) @@ -116,23 +125,22 @@ class Generate_Docs_Tests(unittest.TestCase): print "The following links are broken:" for broken_link in sorted(broken_links): print " "+ broken_link + + cleanup() self.fail("%d links are broken" % len(broken_links)) - # clean up - shutil.rmtree(get_base_url_path()) - tgz.close() - os.remove(tar_filename) - generate.clean_generated_docs(os.path.join(env_root, "doc")) + + cleanup() def test_generate_docs(self): test_root = get_test_root() docs_root = os.path.join(test_root, "doc") generate.clean_generated_docs(docs_root) new_digest = self.check_generate_regenerate_cycle(test_root, INITIAL_FILESET) - # touching an MD file under packages **does** cause a regenerate - os.utime(os.path.join(test_root, "packages", "aardvark", "doc", "main.md"), None) + # touching an MD file under sdk **does** cause a regenerate + os.utime(os.path.join(test_root, "doc", "module-source", "sdk", "aardvark-feeder.md"), None) new_digest = self.check_generate_regenerate_cycle(test_root, INITIAL_FILESET, new_digest) - # touching a non MD file under packages **does not** cause a regenerate - os.utime(os.path.join(test_root, "packages", "aardvark", "lib", "main.js"), None) + # touching a non MD file under sdk **does not** cause a regenerate + os.utime(os.path.join(test_root, "doc", "module-source", "sdk", "not_a_doc.js"), None) self.check_generate_is_skipped(test_root, INITIAL_FILESET, new_digest) # touching a non MD file under static-files **does not** cause a regenerate os.utime(os.path.join(docs_root, "static-files", "another.html"), None) diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_init.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_init.py index 33c0059..3558048 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_init.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_init.py @@ -5,7 +5,7 @@ import os, unittest, shutil from StringIO import StringIO from cuddlefish import initializer -from cuddlefish.templates import MAIN_JS, TEST_MAIN_JS, PACKAGE_JSON +from cuddlefish.templates import TEST_MAIN_JS, PACKAGE_JSON tests_path = os.path.abspath(os.path.dirname(__file__)) @@ -45,7 +45,7 @@ class TestInit(unittest.TestCase): self.assertTrue(os.path.exists(main_js)) self.assertTrue(os.path.exists(package_json)) self.assertTrue(os.path.exists(test_main_js)) - self.assertEqual(open(main_js,"r").read(),MAIN_JS) + self.assertEqual(open(main_js,"r").read(),"") self.assertEqual(open(package_json,"r").read(), PACKAGE_JSON % {"name":"tmp_addon_sample", "fullName": "tmp_addon_SAMPLE" }) @@ -64,7 +64,7 @@ class TestInit(unittest.TestCase): def do_test_args(self, basedir): # check that running it with spurious arguments will fail out,err = StringIO(), StringIO() - init_run = initializer(None, ["init", "ignored-dirname"], out, err) + init_run = initializer(None, ["init", "specified-dirname", "extra-arg"], out, err) out, err = out.getvalue(), err.getvalue() self.failIfEqual(init_run, 0) self.assertTrue("Too many arguments" in err) @@ -87,6 +87,55 @@ class TestInit(unittest.TestCase): def test_existing_files(self): self.run_init_in_subdir("existing_files", self._test_existing_files) + def test_init_subdir(self): + parent = os.path.abspath(os.path.join(".test_tmp", self.id())) + basedir = os.path.join(parent, "init-basedir") + if os.path.exists(parent): + shutil.rmtree(parent) + os.makedirs(parent) + + # if the basedir exists and is not empty, init should refuse + os.makedirs(basedir) + f = open(os.path.join(basedir, "boo"), "w") + f.write("stuff") + f.close() + out, err = StringIO(), StringIO() + rc = initializer(None, ["init", basedir], out, err) + out, err = out.getvalue(), err.getvalue() + self.assertEqual(rc, 1) + self.assertTrue("testing if directory is empty" in out, out) + self.assertTrue("This command must be run in an empty directory." in err, + err) + + # a .dotfile should be tolerated + os.rename(os.path.join(basedir, "boo"), os.path.join(basedir, ".phew")) + out, err = StringIO(), StringIO() + rc = initializer(None, ["init", basedir], out, err) + out, err = out.getvalue(), err.getvalue() + self.assertEqual(rc, 0) + self.assertTrue("* data directory created" in out, out) + self.assertTrue("Have fun!" in out) + self.assertEqual(err,"") + self.assertTrue(os.listdir(basedir)) + main_js = os.path.join(basedir,"lib","main.js") + package_json = os.path.join(basedir,"package.json") + self.assertTrue(os.path.exists(main_js)) + self.assertTrue(os.path.exists(package_json)) + shutil.rmtree(basedir) + + # init should create directories that don't exist already + out, err = StringIO(), StringIO() + rc = initializer(None, ["init", basedir], out, err) + out, err = out.getvalue(), err.getvalue() + self.assertEqual(rc, 0) + self.assertTrue("* data directory created" in out) + self.assertTrue("Have fun!" in out) + self.assertEqual(err,"") + self.assertTrue(os.listdir(basedir)) + main_js = os.path.join(basedir,"lib","main.js") + package_json = os.path.join(basedir,"package.json") + self.assertTrue(os.path.exists(main_js)) + self.assertTrue(os.path.exists(package_json)) class TestCfxQuits(unittest.TestCase): diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_licenses.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_licenses.py index 60b5957..60b5957 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_licenses.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_licenses.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_linker.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_linker.py index 84f6a09..792af6f 100755 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_linker.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_linker.py @@ -31,15 +31,15 @@ class Basic(unittest.TestCase): deps = packaging.get_deps_for_targets(pkg_cfg, ["one"]) self.failUnlessEqual(deps, ["one"]) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "one"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "one"]) def test_manifest(self): target_cfg = self.get_pkg("one") pkg_cfg = packaging.build_config(ROOT, target_cfg) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "one"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "one"]) # target_cfg.dependencies is not provided, so we'll search through # all known packages (everything in 'deps'). m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=False) @@ -48,10 +48,10 @@ class Basic(unittest.TestCase): def assertReqIs(modname, reqname, path): reqs = m["one/lib/%s.js" % modname]["requirements"] self.failUnlessEqual(reqs[reqname]["path"], path) - assertReqIs("main", "panel", "addon-kit/lib/panel.js") + assertReqIs("main", "panel", "addon-sdk/lib/sdk/panel.js") assertReqIs("main", "two.js", "one/lib/two.js") assertReqIs("main", "./two", "one/lib/two.js") - assertReqIs("main", "addon-kit/tabs.js", "addon-kit/lib/tabs.js") + assertReqIs("main", "sdk/tabs.js", "addon-sdk/lib/sdk/tabs.js") assertReqIs("main", "./subdir/three", "one/lib/subdir/three.js") assertReqIs("two", "main", "one/lib/main.js") assertReqIs("subdir/three", "../main", "one/lib/main.js") @@ -69,8 +69,8 @@ class Basic(unittest.TestCase): pkg_cfg = packaging.build_config(ROOT, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "three"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "three"]) m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=False) m = m.get_harness_options_manifest() def assertReqIs(modname, reqname, path): @@ -86,8 +86,8 @@ class Basic(unittest.TestCase): pkg_cfg = packaging.build_config(ROOT, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "five"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "five"]) # all we care about is that this next call doesn't raise an exception m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=False) m = m.get_harness_options_manifest() @@ -100,8 +100,8 @@ class Basic(unittest.TestCase): pkg_cfg = packaging.build_config(ROOT, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "six"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "six"]) self.assertRaises(manifest.UnreachablePrefixError, manifest.build_manifest, target_cfg, pkg_cfg, deps, scan_tests=False) @@ -112,8 +112,8 @@ class Basic(unittest.TestCase): pkg_cfg = packaging.build_config(ROOT, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) - self.failUnlessEqual(deps, ["addon-kit", "api-utils", "four"]) + [target_cfg.name, "addon-sdk"]) + self.failUnlessEqual(deps, ["addon-sdk", "four"]) self.assertRaises(manifest.UnreachablePrefixError, manifest.build_manifest, target_cfg, pkg_cfg, deps, scan_tests=False) @@ -190,7 +190,7 @@ class Contents(unittest.TestCase): names = zf.namelist() # the first problem found in bug 664840 was that cuddlefish.js # (the loader) was stripped out on windows, due to a /-vs-\ bug - self.assertIn("resources/api-utils/lib/cuddlefish.js", names) + self.assertIn("resources/addon-sdk/lib/sdk/loader/cuddlefish.js", names) # the second problem found in bug 664840 was that an addon # without an explicit tests/ directory would copy all files from # the package into a bogus JID-PKGNAME-tests/ directory, so check @@ -220,7 +220,7 @@ class Contents(unittest.TestCase): self.failUnlessEqual(e.args[0], 0) zf = zipfile.ZipFile("seven.xpi", "r") names = zf.namelist() - self.assertIn("resources/api-utils/lib/cuddlefish.js", names) + self.assertIn("resources/addon-sdk/lib/sdk/loader/cuddlefish.js", names) testfiles = [fn for fn in names if "seven/tests" in fn] self.failUnlessEqual([], testfiles) self.assertIn("resources/seven/data/text.data", diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_manifest.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_manifest.py index 77ee86f..1bced12 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_manifest.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_manifest.py @@ -191,18 +191,6 @@ class Chrome(unittest.TestCase, Extra): self.failUnlessEqual(problems, False) self.failUnlessEqual(err, []) - def test_chrome_components(self): - # Bug 663541: tolerate "Components" if you're marked with - # require("chrome"), to avoid requiring module authors to rewrite a - # lot of code. Once bug 636145 is fixed, such code will break. To fix - # it, add {Components}=require("chrome"), but that won't work until - # after 636145 is fixed. - mod = """require("chrome"); - var ios = Components.classes['@mozilla.org/network/io-service;1'];""" - requires, problems, err = scan2(mod) - self.failUnlessKeysAre(requires, ["chrome"]) - self.failUnlessEqual((problems, err), (False, [])) - def test_not_chrome(self): # from bug 596595 mod = r'soughtLines: new RegExp("^\\s*(\\[[0-9 .]*\\])?\\s*\\(\\((EE|WW)\\)|.* [Cc]hipsets?: \\)|\\s*Backtrace")' @@ -233,7 +221,7 @@ class BadChrome(unittest.TestCase, Extra): self.failUnlessEqual(err[4], "use 'Components' to access chrome authority. To do so, you need to add a\n") self.failUnlessEqual(err[5], "line somewhat like the following:\n") self.failUnlessEqual(err[7], ' const {Cc,Cu} = require("chrome");\n') - self.failUnlessEqual(err[9], "Then you can use 'Components' as well as any shortcuts to its properties\n") + self.failUnlessEqual(err[9], "Then you can use any shortcuts to its properties that you import from the\n") def test_bad_misc(self): # If it looks like you're using something that doesn't have an alias, @@ -248,7 +236,22 @@ class BadChrome(unittest.TestCase, Extra): self.failUnlessEqual(err[3], "use 'Components' to access chrome authority. To do so, you need to add a\n") self.failUnlessEqual(err[4], "line somewhat like the following:\n") self.failUnlessEqual(err[6], ' const {components} = require("chrome");\n') - self.failUnlessEqual(err[8], "Then you can use 'Components' as well as any shortcuts to its properties\n") + self.failUnlessEqual(err[8], "Then you can use any shortcuts to its properties that you import from the\n") + + def test_chrome_components(self): + # Bug 636145/774636: We no longer tolerate usages of "Components", + # even when adding `require("chrome")` to your module. + mod = """require("chrome"); + var ios = Components.classes['@mozilla.org/network/io-service;1'];""" + requires, problems, err = scan2(mod) + self.failUnlessKeysAre(requires, ["chrome"]) + self.failUnlessEqual(problems, True) + self.failUnlessEqual(err[1], "The following lines from file fake.js:\n") + self.failUnlessEqual(err[2], " 2: var ios = Components.classes['@mozilla.org/network/io-service;1'];\n") + self.failUnlessEqual(err[3], "use 'Components' to access chrome authority. To do so, you need to add a\n") + self.failUnlessEqual(err[4], "line somewhat like the following:\n") + self.failUnlessEqual(err[6], ' const {Cc} = require("chrome");\n') + self.failUnlessEqual(err[8], "Then you can use any shortcuts to its properties that you import from the\n") if __name__ == '__main__': unittest.main() diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_packaging.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_packaging.py index ff3d851..ccd2812 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_packaging.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_packaging.py @@ -45,10 +45,10 @@ class PackagingTests(unittest.TestCase): configs = get_configs('aardvark') packages = configs.pkg_cfg.packages - self.assertTrue('api-utils' in packages) + self.assertTrue('addon-sdk' in packages) self.assertTrue('aardvark' in packages) - self.assertTrue('api-utils' in packages.aardvark.dependencies) - self.assertEqual(packages['api-utils'].loader, 'lib/loader.js') + self.assertTrue('addon-sdk' in packages.aardvark.dependencies) + self.assertEqual(packages['addon-sdk'].loader, 'lib/sdk/loader/cuddlefish.js') self.assertTrue(packages.aardvark.main == 'main') self.assertTrue(packages.aardvark.version == "1.0") diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_preflight.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_preflight.py index 571b791..571b791 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_preflight.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_preflight.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_property_parser.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_property_parser.py index f037f07..4988f8e 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_property_parser.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_property_parser.py @@ -37,10 +37,19 @@ class TestParser(unittest.TestCase): # With multiline string, left spaces are stripped ... "some= spaces\\", " are\\ ", " stripped ", # ... but not right spaces, except the last line! - "but=not \\", "all of \\", " them " + "but=not \\", "all of \\", " them ", + + # Explicit [other] plural definition + "explicitPlural[one] = one", + "explicitPlural[other] = other", + + # Implicit [other] plural definition + "implicitPlural[one] = one", + "implicitPlural = other", # This key is the [other] one ] - # Ensure that lines end with a `\n` - lines = [l + "\n" for l in lines] + # Ensure that all lines end with a `\n` + # And that strings are unicode ones (parser code relies on it) + lines = [unicode(l + "\n") for l in lines] pairs = parse(lines) expected = { "sharp": "#can be in value", @@ -55,7 +64,16 @@ class TestParser(unittest.TestCase): "multi": "linevalue", "some": "spacesarestripped", - "but": "not all of them" + "but": "not all of them", + + "implicitPlural": { + "one": "one", + "other": "other" + }, + "explicitPlural": { + "one": "one", + "other": "other" + }, } self.assertEqual(pairs, expected) @@ -63,7 +81,7 @@ class TestParser(unittest.TestCase): self.failUnlessRaises(MalformedLocaleFileError, parse, ["invalid line with no key value"]) self.failUnlessRaises(MalformedLocaleFileError, parse, - ["plural[one]=plural with no generic value"]) + ["plural[one]=plural with no [other] value"]) self.failUnlessRaises(MalformedLocaleFileError, parse, ["multiline with no last empty line=\\"]) self.failUnlessRaises(MalformedLocaleFileError, parse, diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_rdf.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_rdf.py index 128289f..67b486c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_rdf.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_rdf.py @@ -10,7 +10,7 @@ from cuddlefish import rdf, packaging parent = os.path.dirname test_dir = parent(os.path.abspath(__file__)) -template_dir = os.path.join(parent(test_dir), "app-extension") +template_dir = os.path.join(parent(test_dir), "../../app-extension") class RDFTests(unittest.TestCase): def testBug567660(self): diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_runner.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_runner.py index 26583ab..26583ab 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_runner.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_runner.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_util.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_util.py index aa636a4..aa636a4 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_util.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_util.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_version.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_version.py index 814c57c..814c57c 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_version.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_version.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_webdocs.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_webdocs.py index d9d4eab..7653bea 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_webdocs.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_webdocs.py @@ -8,30 +8,13 @@ import unittest from cuddlefish.docs import webdocs class WebDocTests(unittest.TestCase): - def test_create_package_doc(self): - root = os.path.join(os.getcwd() + \ - '/python-lib/cuddlefish/tests/static-files') - web_docs = webdocs.WebDocs(root) - aarvark_package = web_docs.create_package_page('aardvark') - self._test_common_contents(aarvark_package) - self.assertTrue('<h1>aardvark</h1>'\ - in aarvark_package) - self.assertTrue(\ - '<span class="meta-header">Author</span>'\ - in aarvark_package) - self.assertTrue(\ - '<span class="author">Jon Smith</span>'\ - in aarvark_package) - self.assertTrue(\ - '<title>aardvark - Add-on SDK Documentation</title>'\ - in aarvark_package) def test_create_guide1_doc(self): root = os.path.join(os.getcwd() + \ '/python-lib/cuddlefish/tests/static-files') web_docs = webdocs.WebDocs(root) guide = web_docs.create_guide_page(os.path.join(\ - root + '/doc/dev-guide-source/index.blah')) + root + '/doc/dev-guide-source/index.md')) self._test_common_contents(guide) self.assertTrue(\ '<title>An Imposing Title - Add-on SDK Documentation</title>'\ @@ -46,7 +29,7 @@ class WebDocTests(unittest.TestCase): '/python-lib/cuddlefish/tests/static-files') web_docs = webdocs.WebDocs(root) guide = web_docs.create_guide_page(os.path.join(\ - root + '/doc/dev-guide-source/no_h1.blah')) + root + '/doc/dev-guide-source/no_h1.md')) self._test_common_contents(guide) self.assertTrue('<title>Add-on SDK Documentation</title>'\ in guide) @@ -58,7 +41,7 @@ class WebDocTests(unittest.TestCase): '/python-lib/cuddlefish/tests/static-files') web_docs = webdocs.WebDocs(root) module = web_docs.create_module_page(os.path.join(\ - root + '/packages/aardvark/doc/aardvark-feeder.blah')) + root + '/doc/module-source/sdk/aardvark-feeder.md')) self._test_common_contents(module) self.assertTrue(\ '<title>aardvark-feeder - Add-on SDK Documentation</title>'\ @@ -87,11 +70,9 @@ class WebDocTests(unittest.TestCase): def _test_common_contents(self, doc): self.assertTrue(\ - '<a href="packages/aardvark/index.html"' in doc) - self.assertTrue(\ - '<a href="packages/anteater_files/index.html"' in doc) + '<a href="modules/sdk/anteater/anteater.html">anteater/anteater</a>' in doc) self.assertTrue(\ - '<a href="packages/aardvark/main.html">main</a>' in doc) + '<a href="modules/sdk/aardvark-feeder.html">aardvark-feeder</a>' in doc) if __name__ == "__main__": unittest.main() diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_xpi.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_xpi.py index 7d638bb..ec5eaa3 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/test_xpi.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/tests/test_xpi.py @@ -13,6 +13,8 @@ from cuddlefish import xpi, packaging, manifest, buildJID from cuddlefish.tests import test_packaging from test_linker import up +import xml.etree.ElementTree as ElementTree + xpi_template_path = os.path.join(test_packaging.static_files_path, 'xpi-template') @@ -40,15 +42,49 @@ class PrefsTests(unittest.TestCase): self.makexpi('simple-prefs') self.failUnless('options.xul' in self.xpi.namelist()) optsxul = self.xpi.read('options.xul').decode("utf-8") - self.failUnless('pref="extensions.jid1-fZHqN9JfrDBa8A@jetpack.test"' - in optsxul, optsxul) - self.failUnless('type="bool"' in optsxul, optsxul) - self.failUnless(u'title="t\u00EBst"' in optsxul, repr(optsxul)) self.failUnlessEqual(self.xpi_harness_options["jetpackID"], "jid1-fZHqN9JfrDBa8A@jetpack") + + root = ElementTree.XML(optsxul.encode('utf-8')) + + xulNamespacePrefix = \ + "{http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul}" + + settings = root.findall(xulNamespacePrefix + 'setting') + + def assertPref(setting, name, prefType, title): + packageName = 'jid1-fZHqN9JfrDBa8A@jetpack' + self.failUnlessEqual(setting.get('data-jetpack-id'), packageName) + self.failUnlessEqual(setting.get('pref'), + 'extensions.' + packageName + '.' + name) + self.failUnlessEqual(setting.get('pref-name'), name) + self.failUnlessEqual(setting.get('type'), prefType) + self.failUnlessEqual(setting.get('title'), title) + + assertPref(settings[0], 'test', 'bool', u't\u00EBst') + assertPref(settings[1], 'test2', 'string', u't\u00EBst') + assertPref(settings[2], 'test3', 'menulist', '"><test') + assertPref(settings[3], 'test4', 'radio', u't\u00EBst') + + menuItems = settings[2].findall( + '%(0)smenulist/%(0)smenupopup/%(0)smenuitem' % { "0": xulNamespacePrefix }) + radios = settings[3].findall( + '%(0)sradiogroup/%(0)sradio' % { "0": xulNamespacePrefix }) + + def assertOption(option, value, label): + self.failUnlessEqual(option.get('value'), value) + self.failUnlessEqual(option.get('label'), label) + + assertOption(menuItems[0], "0", "label1") + assertOption(menuItems[1], "1", "label2") + assertOption(radios[0], "red", "rouge") + assertOption(radios[1], "blue", "bleu") + prefsjs = self.xpi.read('defaults/preferences/prefs.js').decode("utf-8") exp = [u'pref("extensions.jid1-fZHqN9JfrDBa8A@jetpack.test", false);', u'pref("extensions.jid1-fZHqN9JfrDBa8A@jetpack.test2", "\u00FCnic\u00F8d\u00E9");', + u'pref("extensions.jid1-fZHqN9JfrDBa8A@jetpack.test3", "1");', + u'pref("extensions.jid1-fZHqN9JfrDBa8A@jetpack.test4", "red");', ] self.failUnlessEqual(prefsjs, "\n".join(exp)+"\n") @@ -163,7 +199,8 @@ class SmallXPI(unittest.TestCase): pkg_cfg = packaging.build_config(self.root, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) + [target_cfg.name, "addon-sdk"]) + addon_sdk_dir = pkg_cfg.packages["addon-sdk"].lib[0] m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=False) used_files = list(m.get_used_files()) here = up(os.path.abspath(__file__)) @@ -174,15 +211,26 @@ class SmallXPI(unittest.TestCase): [("three", "lib", "main.js"), ("three-deps", "three-a", "lib", "main.js"), ("three-deps", "three-a", "lib", "subdir", "subfile.js"), - ("three-deps", "three-a", "data", "msg.txt"), - ("three-deps", "three-a", "data", "subdir", "submsg.txt"), + ("three", "data", "msg.txt"), + ("three", "data", "subdir", "submsg.txt"), ("three-deps", "three-b", "lib", "main.js"), ("three-deps", "three-c", "lib", "main.js"), - ("three-deps", "three-c", "lib", "sub", "foo.js"), + ("three-deps", "three-c", "lib", "sub", "foo.js") ]] + + add_addon_sdk= lambda path: os.path.join(addon_sdk_dir, path) + expected.extend([add_addon_sdk(module) for module in [ + os.path.join("sdk", "self.js"), + os.path.join("sdk", "core", "promise.js"), + os.path.join("sdk", "net", "url.js"), + os.path.join("sdk", "util", "object.js") + ]]) + missing = set(expected) - set(used_files) extra = set(used_files) - set(expected) - self.failUnlessEqual((list(missing), list(extra)), ([], [])) + + self.failUnlessEqual(list(missing), []) + self.failUnlessEqual(list(extra), []) used_deps = m.get_used_packages() build = packaging.generate_build_for_target(pkg_cfg, target_cfg.name, @@ -207,17 +255,25 @@ class SmallXPI(unittest.TestCase): "install.rdf", "defaults/preferences/prefs.js", "resources/", - "resources/api-utils/", - "resources/api-utils/data/", - "resources/api-utils/lib/", + "resources/addon-sdk/", + "resources/addon-sdk/data/", + "resources/addon-sdk/lib/", + "resources/addon-sdk/lib/sdk/", + "resources/addon-sdk/lib/sdk/self.js", + "resources/addon-sdk/lib/sdk/core/", + "resources/addon-sdk/lib/sdk/util/", + "resources/addon-sdk/lib/sdk/net/", + "resources/addon-sdk/lib/sdk/core/promise.js", + "resources/addon-sdk/lib/sdk/util/object.js", + "resources/addon-sdk/lib/sdk/net/url.js", "resources/three/", "resources/three/lib/", "resources/three/lib/main.js", + "resources/three/data/", + "resources/three/data/msg.txt", + "resources/three/data/subdir/", + "resources/three/data/subdir/submsg.txt", "resources/three-a/", - "resources/three-a/data/", - "resources/three-a/data/msg.txt", - "resources/three-a/data/subdir/", - "resources/three-a/data/subdir/submsg.txt", "resources/three-a/lib/", "resources/three-a/lib/main.js", "resources/three-a/lib/subdir/", @@ -267,8 +323,9 @@ class SmallXPI(unittest.TestCase): package_path = [self.get_linker_files_dir("three-deps")] pkg_cfg = packaging.build_config(self.root, target_cfg, packagepath=package_path) + deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) + [target_cfg.name, "addon-sdk"]) m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=True) self.failUnlessEqual(sorted(m.get_all_test_modules()), sorted(["test-one", "test-two"])) @@ -293,10 +350,10 @@ class SmallXPI(unittest.TestCase): limit_to=None) x = zipfile.ZipFile(xpi_name, "r") names = x.namelist() - self.failUnless("resources/api-utils/lib/unit-test.js" in names, names) - self.failUnless("resources/api-utils/lib/unit-test-finder.js" in names, names) - self.failUnless("resources/test-harness/lib/harness.js" in names, names) - self.failUnless("resources/test-harness/lib/run-tests.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/deprecated/unit-test.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/deprecated/unit-test-finder.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/test/harness.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/test/runner.js" in names, names) # all files are copied into the XPI, even the things that don't look # like tests. self.failUnless("resources/three/tests/test-one.js" in names, names) @@ -309,7 +366,7 @@ class SmallXPI(unittest.TestCase): pkg_cfg = packaging.build_config(self.root, target_cfg, packagepath=package_path) deps = packaging.get_deps_for_targets(pkg_cfg, - [target_cfg.name, "addon-kit"]) + [target_cfg.name, "addon-sdk"]) FILTER = ".*one.*" m = manifest.build_manifest(target_cfg, pkg_cfg, deps, scan_tests=True, test_filter_re=FILTER) @@ -336,10 +393,10 @@ class SmallXPI(unittest.TestCase): limit_to=None) x = zipfile.ZipFile(xpi_name, "r") names = x.namelist() - self.failUnless("resources/api-utils/lib/unit-test.js" in names, names) - self.failUnless("resources/api-utils/lib/unit-test-finder.js" in names, names) - self.failUnless("resources/test-harness/lib/harness.js" in names, names) - self.failUnless("resources/test-harness/lib/run-tests.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/deprecated/unit-test.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/deprecated/unit-test-finder.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/test/harness.js" in names, names) + self.failUnless("resources/addon-sdk/lib/sdk/test/runner.js" in names, names) # get_all_test_modules() respects the filter. But all files are still # copied into the XPI. self.failUnless("resources/three/tests/test-one.js" in names, names) diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/util.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/util.py index 513495a..513495a 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/util.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/util.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/version_comparator.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/version_comparator.py index 3999e71..3999e71 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/version_comparator.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/version_comparator.py diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/xpi.py b/tools/addon-sdk-1.12/python-lib/cuddlefish/xpi.py index 72b8477..3943e56 100644 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/xpi.py +++ b/tools/addon-sdk-1.12/python-lib/cuddlefish/xpi.py @@ -117,13 +117,13 @@ def build_xpi(template_root_dir, manifest, xpi_path, # Be carefull about strings, we need to always ensure working with UTF-8 jsonStr = json.dumps(locale, indent=1, sort_keys=True, ensure_ascii=False) info = zipfile.ZipInfo('locale/' + language + '.json') - info.external_attr = 0444 << 16L + info.external_attr = 0644 << 16L zf.writestr(info, jsonStr.encode( "utf-8" )) del harness_options['locale'] jsonStr = json.dumps(locales_json_data, ensure_ascii=True) +"\n" info = zipfile.ZipInfo('locales.json') - info.external_attr = 0444 << 16L + info.external_attr = 0644 << 16L zf.writestr(info, jsonStr.encode("utf-8")) # now figure out which directories we need: all retained files parents diff --git a/tools/addon-sdk-1.7/python-lib/jetpack_sdk_env.py b/tools/addon-sdk-1.12/python-lib/jetpack_sdk_env.py index 79fdd61..79fdd61 100644 --- a/tools/addon-sdk-1.7/python-lib/jetpack_sdk_env.py +++ b/tools/addon-sdk-1.12/python-lib/jetpack_sdk_env.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/AUTHORS b/tools/addon-sdk-1.12/python-lib/markdown/AUTHORS index cfe2b34..cfe2b34 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/AUTHORS +++ b/tools/addon-sdk-1.12/python-lib/markdown/AUTHORS diff --git a/tools/addon-sdk-1.7/python-lib/markdown/LICENSE b/tools/addon-sdk-1.12/python-lib/markdown/LICENSE index 4cd8b14..4cd8b14 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/LICENSE +++ b/tools/addon-sdk-1.12/python-lib/markdown/LICENSE diff --git a/tools/addon-sdk-1.7/python-lib/markdown/__init__.py b/tools/addon-sdk-1.12/python-lib/markdown/__init__.py index 0d1c504..0d1c504 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/blockparser.py b/tools/addon-sdk-1.12/python-lib/markdown/blockparser.py index e18b338..e18b338 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/blockparser.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/blockparser.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/blockprocessors.py b/tools/addon-sdk-1.12/python-lib/markdown/blockprocessors.py index 79f4db9..79f4db9 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/blockprocessors.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/blockprocessors.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/commandline.py b/tools/addon-sdk-1.12/python-lib/markdown/commandline.py index 1eedc6d..1eedc6d 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/commandline.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/commandline.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/etree_loader.py b/tools/addon-sdk-1.12/python-lib/markdown/etree_loader.py index e2599b2..e2599b2 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/etree_loader.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/etree_loader.py diff --git a/tools/addon-sdk-1.12/python-lib/markdown/extensions/__init__.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/abbr.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/abbr.py index 783220e..783220e 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/abbr.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/abbr.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/codehilite.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/codehilite.py index c5d496b..c5d496b 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/codehilite.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/codehilite.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/def_list.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/def_list.py index 73a1c85..73a1c85 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/def_list.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/def_list.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/extra.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/extra.py index 4a2ffbf..4a2ffbf 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/extra.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/extra.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/fenced_code.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/fenced_code.py index 307b1dc..307b1dc 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/fenced_code.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/fenced_code.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/footnotes.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/footnotes.py index 6dacab7..6dacab7 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/footnotes.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/footnotes.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/headerid.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/headerid.py index f70a7a9..f70a7a9 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/headerid.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/headerid.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/html_tidy.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/html_tidy.py index 5105e33..5105e33 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/html_tidy.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/html_tidy.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/imagelinks.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/imagelinks.py index ee0b708..ee0b708 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/imagelinks.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/imagelinks.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/meta.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/meta.py index 1b555b2..1b555b2 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/meta.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/meta.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/rss.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/rss.py index 1274da2..1274da2 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/rss.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/rss.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/tables.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/tables.py index 1d3c920..1d3c920 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/tables.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/tables.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/toc.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/toc.py index 1624ccf..1624ccf 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/toc.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/toc.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/extensions/wikilinks.py b/tools/addon-sdk-1.12/python-lib/markdown/extensions/wikilinks.py index df44e1c..df44e1c 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/extensions/wikilinks.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/extensions/wikilinks.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/html4.py b/tools/addon-sdk-1.12/python-lib/markdown/html4.py index 08f241d..08f241d 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/html4.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/html4.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/inlinepatterns.py b/tools/addon-sdk-1.12/python-lib/markdown/inlinepatterns.py index 89fa3b2..89fa3b2 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/inlinepatterns.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/inlinepatterns.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/odict.py b/tools/addon-sdk-1.12/python-lib/markdown/odict.py index bf3ef07..bf3ef07 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/odict.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/odict.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/postprocessors.py b/tools/addon-sdk-1.12/python-lib/markdown/postprocessors.py index 80227bb..80227bb 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/postprocessors.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/postprocessors.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/preprocessors.py b/tools/addon-sdk-1.12/python-lib/markdown/preprocessors.py index 712a1e8..712a1e8 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/preprocessors.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/preprocessors.py diff --git a/tools/addon-sdk-1.7/python-lib/markdown/treeprocessors.py b/tools/addon-sdk-1.12/python-lib/markdown/treeprocessors.py index 1dc612a..1dc612a 100644 --- a/tools/addon-sdk-1.7/python-lib/markdown/treeprocessors.py +++ b/tools/addon-sdk-1.12/python-lib/markdown/treeprocessors.py diff --git a/tools/addon-sdk-1.7/python-lib/mozrunner/__init__.py b/tools/addon-sdk-1.12/python-lib/mozrunner/__init__.py index b88c734..b88c734 100644 --- a/tools/addon-sdk-1.7/python-lib/mozrunner/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/mozrunner/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/mozrunner/killableprocess.py b/tools/addon-sdk-1.12/python-lib/mozrunner/killableprocess.py index 892ed87..892ed87 100644 --- a/tools/addon-sdk-1.7/python-lib/mozrunner/killableprocess.py +++ b/tools/addon-sdk-1.12/python-lib/mozrunner/killableprocess.py diff --git a/tools/addon-sdk-1.7/python-lib/mozrunner/qijo.py b/tools/addon-sdk-1.12/python-lib/mozrunner/qijo.py index 0580557..0580557 100644 --- a/tools/addon-sdk-1.7/python-lib/mozrunner/qijo.py +++ b/tools/addon-sdk-1.12/python-lib/mozrunner/qijo.py diff --git a/tools/addon-sdk-1.7/python-lib/mozrunner/winprocess.py b/tools/addon-sdk-1.12/python-lib/mozrunner/winprocess.py index 4bea3fc..4bea3fc 100644 --- a/tools/addon-sdk-1.7/python-lib/mozrunner/winprocess.py +++ b/tools/addon-sdk-1.12/python-lib/mozrunner/winprocess.py diff --git a/tools/addon-sdk-1.7/python-lib/mozrunner/wpk.py b/tools/addon-sdk-1.12/python-lib/mozrunner/wpk.py index 6c92f5d..6c92f5d 100644 --- a/tools/addon-sdk-1.7/python-lib/mozrunner/wpk.py +++ b/tools/addon-sdk-1.12/python-lib/mozrunner/wpk.py diff --git a/tools/addon-sdk-1.7/python-lib/plural-rules-generator.py b/tools/addon-sdk-1.12/python-lib/plural-rules-generator.py index 5776fd8..923cc18 100644 --- a/tools/addon-sdk-1.7/python-lib/plural-rules-generator.py +++ b/tools/addon-sdk-1.12/python-lib/plural-rules-generator.py @@ -165,8 +165,10 @@ const RULES = { */ exports.getRulesForLocale = function getRulesForLocale(locale) { let index = LOCALES_TO_RULES[locale]; - if (!(index in RULES)) - throw new Error('Plural form unknown for locale \"' + locale + '\"'); + if (!(index in RULES)) { + console.warn('Plural form unknown for locale "' + locale + '"'); + return function () { return "other"; }; + } return RULES[index]; } """ % (UNICODE_ORG_XML_URL, diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/LICENSE.txt b/tools/addon-sdk-1.12/python-lib/simplejson/LICENSE.txt index ad95f29..ad95f29 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/LICENSE.txt +++ b/tools/addon-sdk-1.12/python-lib/simplejson/LICENSE.txt diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/__init__.py b/tools/addon-sdk-1.12/python-lib/simplejson/__init__.py index adcce7e..adcce7e 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/__init__.py +++ b/tools/addon-sdk-1.12/python-lib/simplejson/__init__.py diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/decoder.py b/tools/addon-sdk-1.12/python-lib/simplejson/decoder.py index baf10e9..baf10e9 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/decoder.py +++ b/tools/addon-sdk-1.12/python-lib/simplejson/decoder.py diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/encoder.py b/tools/addon-sdk-1.12/python-lib/simplejson/encoder.py index 772a261..772a261 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/encoder.py +++ b/tools/addon-sdk-1.12/python-lib/simplejson/encoder.py diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/scanner.py b/tools/addon-sdk-1.12/python-lib/simplejson/scanner.py index 2a18390..2a18390 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/scanner.py +++ b/tools/addon-sdk-1.12/python-lib/simplejson/scanner.py diff --git a/tools/addon-sdk-1.7/python-lib/simplejson/tool.py b/tools/addon-sdk-1.12/python-lib/simplejson/tool.py index caa1818..caa1818 100644 --- a/tools/addon-sdk-1.7/python-lib/simplejson/tool.py +++ b/tools/addon-sdk-1.12/python-lib/simplejson/tool.py diff --git a/tools/addon-sdk-1.12/test/addons/l10n/data/test-localization.html b/tools/addon-sdk-1.12/test/addons/l10n/data/test-localization.html new file mode 100644 index 0000000..5428863 --- /dev/null +++ b/tools/addon-sdk-1.12/test/addons/l10n/data/test-localization.html @@ -0,0 +1,24 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<html> + <head> + <meta charset="UTF-8"> + <title>HTML Localization</title> + </head> + <body> + <div data-l10n-id="Not translated">Kept as-is</div> + <ul data-l10n-id="Translated"> + <li>Inner html content is replaced,</li> + <li data-l10n-id="text-content"> + Elements with data-l10n-id attribute whose parent element is translated + will be replaced by the content of the translation. + </li> + </ul> + <div data-l10n-id="text-content">No</div> + <div data-l10n-id="Translated"> + A data-l10n-id value can be used in multiple elements + </div> + </body> +</html diff --git a/tools/addon-sdk-1.7/packages/addon-kit/locale/en-GB.properties b/tools/addon-sdk-1.12/test/addons/l10n/locale/en-GB.properties index 08db753..e625690 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/locale/en-GB.properties +++ b/tools/addon-sdk-1.12/test/addons/l10n/locale/en-GB.properties @@ -4,8 +4,13 @@ Translated= Yes +text-content=no <b>HTML</b> injection + downloadsCount=%d downloads downloadsCount[one]=one download pluralTest=fallback to other pluralTest[zero]=optional zero form + +explicitPlural[one]=one +explicitPlural[other]=other diff --git a/tools/addon-sdk-1.7/packages/addon-kit/locale/eo.properties b/tools/addon-sdk-1.12/test/addons/l10n/locale/eo.properties index a979fca..a979fca 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/locale/eo.properties +++ b/tools/addon-sdk-1.12/test/addons/l10n/locale/eo.properties diff --git a/tools/addon-sdk-1.7/packages/addon-kit/locale/fr-FR.properties b/tools/addon-sdk-1.12/test/addons/l10n/locale/fr-FR.properties index 2c5ffbb..2c5ffbb 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/locale/fr-FR.properties +++ b/tools/addon-sdk-1.12/test/addons/l10n/locale/fr-FR.properties diff --git a/tools/addon-sdk-1.12/test/addons/l10n/main.js b/tools/addon-sdk-1.12/test/addons/l10n/main.js new file mode 100644 index 0000000..b4e980f --- /dev/null +++ b/tools/addon-sdk-1.12/test/addons/l10n/main.js @@ -0,0 +1,181 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const prefs = require("sdk/preferences/service"); +const { Loader } = require('sdk/test/loader'); +const { resolveURI } = require('toolkit/loader'); +const { rootURI } = require("@loader/options"); + +const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS"; +const PREF_SELECTED_LOCALE = "general.useragent.locale"; + +function setLocale(locale) { + prefs.set(PREF_MATCH_OS_LOCALE, false); + prefs.set(PREF_SELECTED_LOCALE, locale); +} + +function resetLocale() { + prefs.reset(PREF_MATCH_OS_LOCALE); + prefs.reset(PREF_SELECTED_LOCALE); +} + +function definePseudo(loader, id, exports) { + let uri = resolveURI(id, loader.mapping); + loader.modules[uri] = { exports: exports }; +} + +function createTest(locale, testFunction) { + return function (assert, done) { + let loader = Loader(module); + // Change the locale before loading new l10n modules in order to load + // the right .json file + setLocale(locale); + // Initialize main l10n module in order to load new locale files + loader.require("sdk/l10n/loader"). + load(rootURI). + then(function success(data) { + definePseudo(loader, '@l10n/data', data); + // Execute the given test function + try { + testFunction(assert, loader, function onDone() { + loader.unload(); + resetLocale(); + done(); + }); + } + catch(e) { + console.exception(e); + } + }, + function failure(error) { + assert.fail("Unable to load locales: " + error); + }); + }; +} + +exports.testExactMatching = createTest("fr-FR", function(assert, loader, done) { + let _ = loader.require("sdk/l10n").get; + assert.equal(_("Not translated"), "Not translated", + "Key not translated"); + assert.equal(_("Translated"), "Oui", + "Simple key translated"); + + // Placeholders + assert.equal(_("placeholderString", "works"), "Placeholder works", + "Value with placeholder"); + assert.equal(_("Placeholder %s", "works"), "Placeholder works", + "Key without value but with placeholder"); + assert.equal(_("Placeholders %2s %1s %s.", "working", "are", "correctly"), + "Placeholders are working correctly.", + "Multiple placeholders"); + + // Plurals + assert.equal(_("downloadsCount", 0), + "0 téléchargement", + "PluralForm form 'one' for 0 in french"); + assert.equal(_("downloadsCount", 1), + "1 téléchargement", + "PluralForm form 'one' for 1 in french"); + assert.equal(_("downloadsCount", 2), + "2 téléchargements", + "PluralForm form 'other' for n > 1 in french"); + + done(); +}); + +exports.testHtmlLocalization = createTest("en-GB", function(assert, loader, done) { + + // Ensure initing html component that watch document creations + // Note that this module is automatically initialized in + // cuddlefish.js:Loader.main in regular addons. But it isn't for unit tests. + let loaderHtmlL10n = loader.require("sdk/l10n/html"); + loaderHtmlL10n.enable(); + + let uri = require("sdk/self").data.url("test-localization.html"); + let worker = loader.require("sdk/page-worker").Page({ + contentURL: uri, + contentScript: "new " + function ContentScriptScope() { + let nodes = document.body.querySelectorAll("*[data-l10n-id]"); + self.postMessage([nodes[0].innerHTML, + nodes[1].innerHTML, + nodes[2].innerHTML, + nodes[3].innerHTML]); + }, + onMessage: function (data) { + assert.equal( + data[0], + "Kept as-is", + "Nodes with unknown id in .properties are kept 'as-is'" + ); + assert.equal(data[1], "Yes", "HTML is translated"); + assert.equal( + data[2], + "no <b>HTML</b> injection", + "Content from .properties is text content; HTML can't be injected." + ); + assert.equal(data[3], "Yes", "Multiple elements with same data-l10n-id are accepted."); + + done(); + } + }); + +}); + +exports.testEnUsLocaleName = createTest("en-US", function(assert, loader, done) { + let _ = loader.require("sdk/l10n").get; + + assert.equal(_("Not translated"), "Not translated", + "String w/o translation is kept as-is"); + assert.equal(_("Translated"), "Yes", + "String with translation is correctly translated"); + + // Check plural forms regular matching + assert.equal(_("downloadsCount", 0), + "0 downloads", + "PluralForm form 'other' for 0 in english"); + assert.equal(_("downloadsCount", 1), + "one download", + "PluralForm form 'one' for 1 in english"); + assert.equal(_("downloadsCount", 2), + "2 downloads", + "PluralForm form 'other' for n != 1 in english"); + + // Check optional plural forms + assert.equal(_("pluralTest", 0), + "optional zero form", + "PluralForm form 'zero' can be optionaly specified. (Isn't mandatory in english)"); + assert.equal(_("pluralTest", 1), + "fallback to other", + "If the specific plural form is missing, we fallback to 'other'"); + + // Ensure that we can omit specifying the generic key without [other] + // key[one] = ... + // key[other] = ... # Instead of `key = ...` + assert.equal(_("explicitPlural", 1), + "one", + "PluralForm form can be omitting generic key [i.e. without ...[other] at end of key)"); + assert.equal(_("explicitPlural", 10), + "other", + "PluralForm form can be omitting generic key [i.e. without ...[other] at end of key)"); + + done(); +}); + +exports.testShortLocaleName = createTest("eo", function(assert, loader, done) { + let _ = loader.require("sdk/l10n").get; + assert.equal(_("Not translated"), "Not translated", + "String w/o translation is kept as-is"); + assert.equal(_("Translated"), "jes", + "String with translation is correctly translated"); + + done(); +}); + + +// Before running tests, disable HTML service which is automatially enabled +// in api-utils/addon/runner.js +require('sdk/l10n/html').disable(); + +require("sdk/test/runner").runTestsFromModule(module); diff --git a/tools/addon-sdk-1.12/test/addons/l10n/package.json b/tools/addon-sdk-1.12/test/addons/l10n/package.json new file mode 100644 index 0000000..a13c952 --- /dev/null +++ b/tools/addon-sdk-1.12/test/addons/l10n/package.json @@ -0,0 +1,3 @@ +{ + "id": "test-l10n" +}
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/commonjs-test-adapter/asserts.js b/tools/addon-sdk-1.12/test/commonjs-test-adapter/asserts.js index 8618ace..8618ace 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/commonjs-test-adapter/asserts.js +++ b/tools/addon-sdk-1.12/test/commonjs-test-adapter/asserts.js diff --git a/tools/addon-sdk-1.12/test/fixtures/addon-install-unit-test@mozilla.com.xpi b/tools/addon-sdk-1.12/test/fixtures/addon-install-unit-test@mozilla.com.xpi Binary files differnew file mode 100644 index 0000000..c7cfccd --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/addon-install-unit-test@mozilla.com.xpi diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/addEventListener.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/addEventListener.js new file mode 100644 index 0000000..a251701 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/addEventListener.js @@ -0,0 +1,8 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +postMessage('Hello'); diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/jsctypes.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/jsctypes.js new file mode 100644 index 0000000..8d5ea9a --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/jsctypes.js @@ -0,0 +1,8 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +postMessage(typeof ctypes.open); diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onerror.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onerror.js new file mode 100644 index 0000000..7310a70 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onerror.js @@ -0,0 +1,8 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +throw new Error('ok'); diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onmessage.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onmessage.js new file mode 100644 index 0000000..42962f9 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/onmessage.js @@ -0,0 +1,10 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +onmessage = function (event) { + postMessage(event.data); +}; diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/setTimeout.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/setTimeout.js new file mode 100644 index 0000000..1a137f1 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/setTimeout.js @@ -0,0 +1,10 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +setTimeout(function () { + postMessage('ok'); +}, 0); diff --git a/tools/addon-sdk-1.12/test/fixtures/chrome-worker/xhr.js b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/xhr.js new file mode 100644 index 0000000..7f76289 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/chrome-worker/xhr.js @@ -0,0 +1,13 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +let xhr = XMLHttpRequest(); +xhr.open("GET", "data:text/plain,ok", true); +xhr.onload = function () { + postMessage(xhr.responseText); +}; +xhr.send(null); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/es5.js b/tools/addon-sdk-1.12/test/fixtures/es5.js index 746cae3..746cae3 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/es5.js +++ b/tools/addon-sdk-1.12/test/fixtures/es5.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/find-tests.js b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/a.js index 60550bf..f6e13cc 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/find-tests.js +++ b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/a.js @@ -2,4 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -// this file left intentionally blank +'use strict'; + +exports.b = require('b'); diff --git a/tools/addon-sdk-1.12/test/fixtures/loader/cycles/b.js b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/b.js new file mode 100644 index 0000000..69e23f1 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/b.js @@ -0,0 +1,7 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +exports.a = require('a'); diff --git a/tools/addon-sdk-1.12/test/fixtures/loader/cycles/c.js b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/c.js new file mode 100644 index 0000000..ce34b3c --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/c.js @@ -0,0 +1,7 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +exports.main = require('main'); diff --git a/tools/addon-sdk-1.12/test/fixtures/loader/cycles/main.js b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/main.js new file mode 100644 index 0000000..6d13200 --- /dev/null +++ b/tools/addon-sdk-1.12/test/fixtures/loader/cycles/main.js @@ -0,0 +1,14 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +var a = require('a'); +var b = require('b'); +var c = require('c'); + +exports.a = a; +exports.b = b; +exports.c = c; +exports.main = exports; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-complex-character.js b/tools/addon-sdk-1.12/test/fixtures/sandbox-complex-character.js index 6ae6769..6ae6769 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-complex-character.js +++ b/tools/addon-sdk-1.12/test/fixtures/sandbox-complex-character.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-normal.js b/tools/addon-sdk-1.12/test/fixtures/sandbox-normal.js index 5425298..5425298 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/fixtures/sandbox-normal.js +++ b/tools/addon-sdk-1.12/test/fixtures/sandbox-normal.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/loader/fixture.js b/tools/addon-sdk-1.12/test/loader/fixture.js index c2dc0f1..ebf91ab 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/loader/fixture.js +++ b/tools/addon-sdk-1.12/test/loader/fixture.js @@ -3,4 +3,5 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ exports.foo = foo; -console.log('testing', 1, [2, 3, 4]); +exports.bar = 2; +print('testing'); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/add.js b/tools/addon-sdk-1.12/test/modules/add.js index 5472934..5472934 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/add.js +++ b/tools/addon-sdk-1.12/test/modules/add.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/async1.js b/tools/addon-sdk-1.12/test/modules/async1.js index b7b60fd..b7b60fd 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/async1.js +++ b/tools/addon-sdk-1.12/test/modules/async1.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/async2.js b/tools/addon-sdk-1.12/test/modules/async2.js index 802fb25..802fb25 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/async2.js +++ b/tools/addon-sdk-1.12/test/modules/async2.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badExportAndReturn.js b/tools/addon-sdk-1.12/test/modules/badExportAndReturn.js index 35a5359..35a5359 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badExportAndReturn.js +++ b/tools/addon-sdk-1.12/test/modules/badExportAndReturn.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badFirst.js b/tools/addon-sdk-1.12/test/modules/badFirst.js index fdb03bd..fdb03bd 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badFirst.js +++ b/tools/addon-sdk-1.12/test/modules/badFirst.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badSecond.js b/tools/addon-sdk-1.12/test/modules/badSecond.js index 8321a85..8321a85 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/badSecond.js +++ b/tools/addon-sdk-1.12/test/modules/badSecond.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/blue.js b/tools/addon-sdk-1.12/test/modules/blue.js index 14ab149..14ab149 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/blue.js +++ b/tools/addon-sdk-1.12/test/modules/blue.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/castor.js b/tools/addon-sdk-1.12/test/modules/castor.js index 9209623..9209623 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/castor.js +++ b/tools/addon-sdk-1.12/test/modules/castor.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/cheetah.js b/tools/addon-sdk-1.12/test/modules/cheetah.js index 37d12bf..37d12bf 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/cheetah.js +++ b/tools/addon-sdk-1.12/test/modules/cheetah.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/color.js b/tools/addon-sdk-1.12/test/modules/color.js index 0d946bd..0d946bd 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/color.js +++ b/tools/addon-sdk-1.12/test/modules/color.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupe.js b/tools/addon-sdk-1.12/test/modules/dupe.js index f87fa55..f87fa55 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupe.js +++ b/tools/addon-sdk-1.12/test/modules/dupe.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeNested.js b/tools/addon-sdk-1.12/test/modules/dupeNested.js index 703948c..703948c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeNested.js +++ b/tools/addon-sdk-1.12/test/modules/dupeNested.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeSetExports.js b/tools/addon-sdk-1.12/test/modules/dupeSetExports.js index 12a1be2..12a1be2 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/dupeSetExports.js +++ b/tools/addon-sdk-1.12/test/modules/dupeSetExports.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/exportsEquals.js b/tools/addon-sdk-1.12/test/modules/exportsEquals.js index e176316..e176316 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/exportsEquals.js +++ b/tools/addon-sdk-1.12/test/modules/exportsEquals.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/green.js b/tools/addon-sdk-1.12/test/modules/green.js index ce2d134..ce2d134 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/green.js +++ b/tools/addon-sdk-1.12/test/modules/green.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/lion.js b/tools/addon-sdk-1.12/test/modules/lion.js index 9c3ac3b..9c3ac3b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/lion.js +++ b/tools/addon-sdk-1.12/test/modules/lion.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/orange.js b/tools/addon-sdk-1.12/test/modules/orange.js index 900a32b..900a32b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/orange.js +++ b/tools/addon-sdk-1.12/test/modules/orange.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/pollux.js b/tools/addon-sdk-1.12/test/modules/pollux.js index 61cf66f..61cf66f 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/pollux.js +++ b/tools/addon-sdk-1.12/test/modules/pollux.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/red.js b/tools/addon-sdk-1.12/test/modules/red.js index c47b8e9..c47b8e9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/red.js +++ b/tools/addon-sdk-1.12/test/modules/red.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/setExports.js b/tools/addon-sdk-1.12/test/modules/setExports.js index 495c301..495c301 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/setExports.js +++ b/tools/addon-sdk-1.12/test/modules/setExports.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/subtract.js b/tools/addon-sdk-1.12/test/modules/subtract.js index 06e1053..06e1053 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/subtract.js +++ b/tools/addon-sdk-1.12/test/modules/subtract.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/tiger.js b/tools/addon-sdk-1.12/test/modules/tiger.js index e332deb..e332deb 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/tiger.js +++ b/tools/addon-sdk-1.12/test/modules/tiger.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional1.js b/tools/addon-sdk-1.12/test/modules/traditional1.js index 28af8ef..28af8ef 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional1.js +++ b/tools/addon-sdk-1.12/test/modules/traditional1.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional2.js b/tools/addon-sdk-1.12/test/modules/traditional2.js index 67b64ee..67b64ee 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/traditional2.js +++ b/tools/addon-sdk-1.12/test/modules/traditional2.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/types/cat.js b/tools/addon-sdk-1.12/test/modules/types/cat.js index 41513d6..41513d6 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/modules/types/cat.js +++ b/tools/addon-sdk-1.12/test/modules/types/cat.js diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/pagemod-test-helpers.js b/tools/addon-sdk-1.12/test/pagemod-test-helpers.js index 7c741eb..c76bcb9 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/pagemod-test-helpers.js +++ b/tools/addon-sdk-1.12/test/pagemod-test-helpers.js @@ -5,9 +5,9 @@ "use strict"; const {Cc,Ci} = require("chrome"); -const timer = require("timer"); -const xulApp = require("xul-app"); -const { Loader } = require('./helpers'); +const timer = require("sdk/timers"); +const xulApp = require("sdk/system/xul-app"); +const { Loader } = require("sdk/test/loader"); /** * A helper function that creates a PageMod, then opens the specified URL @@ -36,7 +36,7 @@ exports.testPageMod = function testPageMod(test, testURL, pageModOptions, test.waitUntilDone(); let loader = Loader(module); - let pageMod = loader.require("page-mod"); + let pageMod = loader.require("sdk/page-mod"); var pageMods = [new pageMod.PageMod(opts) for each(opts in pageModOptions)]; @@ -59,7 +59,8 @@ exports.testPageMod = function testPageMod(test, testURL, pageModOptions, tabBrowser.removeTab(newTab); loader.unload(); test.done(); - }); + } + ); } b.addEventListener("load", onPageLoad, true); diff --git a/tools/addon-sdk-1.12/test/private-browsing-helper.js b/tools/addon-sdk-1.12/test/private-browsing-helper.js new file mode 100644 index 0000000..01b85e3 --- /dev/null +++ b/tools/addon-sdk-1.12/test/private-browsing-helper.js @@ -0,0 +1,32 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +let { Cc,Ci } = require('chrome'); +const { Loader } = require('sdk/test/loader'); +let { loader } = LoaderWithHookedConsole(); +const pb = loader.require('sdk/private-browsing'); +const pbUtils = loader.require('sdk/private-browsing/utils'); + +function LoaderWithHookedConsole() { + let errors = []; + let loader = Loader(module, { + console: Object.create(console, { + error: { value: function(e) { + if (!/DEPRECATED:/.test(e)) { + console.error(e); + } + }} + }) + }); + + return { + loader: loader, + errors: errors + } +} + +exports.pb = pb; +exports.pbUtils = pbUtils; +exports.LoaderWithHookedConsole = LoaderWithHookedConsole; diff --git a/tools/addon-sdk-1.12/test/tabs/test-fennec-tabs.js b/tools/addon-sdk-1.12/test/tabs/test-fennec-tabs.js new file mode 100644 index 0000000..f3cd660 --- /dev/null +++ b/tools/addon-sdk-1.12/test/tabs/test-fennec-tabs.js @@ -0,0 +1,621 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Cc, Ci } = require('chrome'); +const { Loader } = require('sdk/test/loader'); +const timer = require('sdk/timers'); +const tabs = require('sdk/tabs'); +const windows = require('sdk/windows'); + +const tabsLen = tabs.length; +const URL = 'data:text/html;charset=utf-8,<html><head><title>#title#</title></head></html>'; +const ERR_MSG = 'Error: This method is not yet supported by Fennec'; + +function LoaderWithHookedConsole() { + let errors = []; + let loader = Loader(module, { + console: Object.create(console, { + error: { value: function(error) { + errors.push(error); + }} + }) + }); + + return { + loader: loader, + errors: errors + } +} + +// TEST: tab unloader +exports.testAutomaticDestroy = function(test) { + test.waitUntilDone(); + + let called = false; + + let loader2 = Loader(module); + let loader3 = Loader(module); + let tabs2 = loader2.require('sdk/tabs'); + let tabs3 = loader3.require('sdk/tabs'); + let tabs2Len = tabs2.length; + + tabs2.on('open', function onOpen(tab) { + test.fail("an onOpen listener was called that should not have been"); + called = true; + }); + tabs2.on('ready', function onReady(tab) { + test.fail("an onReady listener was called that should not have been"); + called = true; + }); + tabs2.on('select', function onSelect(tab) { + test.fail("an onSelect listener was called that should not have been"); + called = true; + }); + tabs2.on('close', function onClose(tab) { + test.fail("an onClose listener was called that should not have been"); + called = true; + }); + loader2.unload(); + + tabs3.on('open', function onOpen(tab) { + test.pass("an onOpen listener was called for tabs3"); + + tab.on('ready', function onReady(tab) { + test.fail("an onReady listener was called that should not have been"); + called = true; + }); + tab.on('select', function onSelect(tab) { + test.fail("an onSelect listener was called that should not have been"); + called = true; + }); + tab.on('close', function onClose(tab) { + test.fail("an onClose listener was called that should not have been"); + called = true; + }); + }); + tabs3.open(URL.replace(/#title#/, 'tabs3')); + loader3.unload(); + + // Fire a tab event and ensure that the destroyed tab is inactive + tabs.once('open', function(tab) { + test.pass('tabs.once("open") works!'); + + test.assertEqual(tabs2Len, tabs2.length, "tabs2 length was not changed"); + test.assertEqual(tabs.length, (tabs2.length+2), "tabs.length > tabs2.length"); + + tab.once('ready', function() { + test.pass('tab.once("ready") works!'); + + tab.once('close', function() { + test.pass('tab.once("close") works!'); + + timer.setTimeout(function () { + test.assert(!called, "Unloaded tab module is destroyed and inactive"); + + // end test + test.done(); + }); + }); + + tab.close(); + }); + }); + + tabs.open('data:text/html;charset=utf-8,foo'); +}; + +// TEST: tab properties +exports.testTabProperties = function(test) { + test.waitUntilDone(); + let { loader, errors } = LoaderWithHookedConsole(); + let tabs = loader.require('sdk/tabs'); + + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head><body>foo</body></html>"; + let tabsLen = tabs.length; + tabs.open({ + url: url, + onReady: function(tab) { + test.assertEqual(tab.title, "foo", "title of the new tab matches"); + test.assertEqual(tab.url, url, "URL of the new tab matches"); + test.assert(tab.favicon, "favicon of the new tab is not empty"); + // TODO: remove need for this test by implementing the favicon feature + test.assertEqual(errors.length, 1, "favicon logs an error for now"); + test.assertEqual(tab.style, null, "style of the new tab matches"); + test.assertEqual(tab.index, tabsLen, "index of the new tab matches"); + test.assertNotEqual(tab.getThumbnail(), null, "thumbnail of the new tab matches"); + + tab.close(function() { + loader.unload(); + + // end test + test.done(); + }); + } + }); +}; + +// TEST: tabs iterator and length property +exports.testTabsIteratorAndLength = function(test) { + test.waitUntilDone(); + + let newTabs = []; + let startCount = 0; + for each (let t in tabs) startCount++; + + test.assertEqual(startCount, tabs.length, "length property is correct"); + + let url = "data:text/html;charset=utf-8,testTabsIteratorAndLength"; + tabs.open({url: url, onOpen: function(tab) newTabs.push(tab)}); + tabs.open({url: url, onOpen: function(tab) newTabs.push(tab)}); + tabs.open({ + url: url, + onOpen: function(tab) { + let count = 0; + for each (let t in tabs) count++; + test.assertEqual(count, startCount + 3, "iterated tab count matches"); + test.assertEqual(startCount + 3, tabs.length, "iterated tab count matches length property"); + + let newTabsLength = newTabs.length; + newTabs.forEach(function(t) t.close(function() { + if (--newTabsLength > 0) return; + + tab.close(function() { + // end test + test.done(); + }); + })); + } + }); +}; + +// TEST: tab.url setter +exports.testTabLocation = function(test) { + test.waitUntilDone(); + + let url1 = "data:text/html;charset=utf-8,foo"; + let url2 = "data:text/html;charset=utf-8,bar"; + + tabs.on('ready', function onReady(tab) { + if (tab.url != url2) + return; + + tabs.removeListener('ready', onReady); + test.pass("tab loaded the correct url"); + + tab.close(function() { + // end test + test.done(); + }); + }); + + tabs.open({ + url: url1, + onOpen: function(tab) { + tab.url = url2; + } + }); +}; + +// TEST: tab.reload() +exports.testTabReload = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,<!doctype%20html><title></title>"; + + tabs.open({ + url: url, + onReady: function onReady(tab) { + tab.removeListener('ready', onReady); + + tab.once( + 'ready', + function onReload() { + test.pass("the tab was loaded again"); + test.assertEqual(tab.url, url, "the tab has the same URL"); + + // end test + tab.close(function() test.done()); + } + ); + + tab.reload(); + } + }); +}; + +// TEST: tab.move() +exports.testTabMove = function(test) { + test.waitUntilDone(); + + let { loader, errors } = LoaderWithHookedConsole(); + let tabs = loader.require('sdk/tabs'); + + let url = "data:text/html;charset=utf-8,testTabMove"; + + tabs.open({ + url: url, + onOpen: function(tab1) { + test.assert(tab1.index >= 0, "opening a tab returns a tab w/ valid index"); + + tabs.open({ + url: url, + onOpen: function(tab) { + let i = tab.index; + test.assert(tab.index > tab1.index, "2nd tab has valid index"); + tab.index = 0; + test.assertEqual(tab.index, i, "tab index after move matches"); + test.assertEqual(errors.length, 1, "setting tab.index logs error"); + + // end test + tab1.close(function() tab.close(function() { + loader.unload(); + test.done(); + })); + } + }); + } + }); +}; + +// TEST: open tab with default options +exports.testTabsOpen_alt = function(test) { + test.waitUntilDone(); + + let { loader, errors } = LoaderWithHookedConsole(); + let tabs = loader.require('sdk/tabs'); + let url = "data:text/html;charset=utf-8,default"; + + tabs.open({ + url: url, + onReady: function(tab) { + test.assertEqual(tab.url, url, "URL of the new tab matches"); + test.assertEqual(tabs.activeTab, tab, "URL of active tab in the current window matches"); + test.assertEqual(tab.isPinned, false, "The new tab is not pinned"); + test.assertEqual(errors.length, 1, "isPinned logs error"); + + // end test + tab.close(function() { + loader.unload(); + test.done(); + }); + } + }); +}; + +// TEST: open pinned tab +exports.testOpenPinned_alt = function(test) { + test.waitUntilDone(); + + let { loader, errors } = LoaderWithHookedConsole(); + let tabs = loader.require('sdk/tabs'); + let url = "about:blank"; + + tabs.open({ + url: url, + isPinned: true, + onOpen: function(tab) { + test.assertEqual(tab.isPinned, false, "The new tab is pinned"); + test.assertEqual(errors.length, 2, "isPinned logs error"); + + // end test + tab.close(function() { + loader.unload(); + test.done(); + }); + } + }); +}; + +// TEST: pin/unpin opened tab +exports.testPinUnpin_alt = function(test) { + test.waitUntilDone(); + + let { loader, errors } = LoaderWithHookedConsole(); + let tabs = loader.require('sdk/tabs'); + let url = "data:text/html;charset=utf-8,default"; + + tabs.open({ + url: url, + onOpen: function(tab) { + tab.pin(); + test.assertEqual(tab.isPinned, false, "The tab was pinned correctly"); + test.assertEqual(errors.length, 2, "tab.pin() logs error"); + + tab.unpin(); + test.assertEqual(tab.isPinned, false, "The tab was unpinned correctly"); + test.assertEqual(errors.length, 4, "tab.unpin() logs error"); + + // end test + tab.close(function() { + loader.unload(); + test.done(); + }); + } + }); +}; + +// TEST: open tab in background +exports.testInBackground = function(test) { + test.waitUntilDone(); + + let activeUrl = tabs.activeTab.url; + let url = "data:text/html;charset=utf-8,background"; + let window = windows.browserWindows.activeWindow; + tabs.once('ready', function onReady(tab) { + test.assertEqual(tabs.activeTab.url, activeUrl, "URL of active tab has not changed"); + test.assertEqual(tab.url, url, "URL of the new background tab matches"); + test.assertEqual(windows.browserWindows.activeWindow, window, "a new window was not opened"); + test.assertNotEqual(tabs.activeTab.url, url, "URL of active tab is not the new URL"); + + // end test + tab.close(function() test.done()); + }); + + tabs.open({ + url: url, + inBackground: true + }); +}; + +// TEST: open tab in new window +exports.testOpenInNewWindow = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,newwindow"; + let window = windows.browserWindows.activeWindow; + + tabs.open({ + url: url, + inNewWindow: true, + onReady: function(tab) { + test.assertEqual(windows.browserWindows.length, 1, "a new window was not opened"); + test.assertEqual(windows.browserWindows.activeWindow, window, "old window is active"); + test.assertEqual(tab.url, url, "URL of the new tab matches"); + test.assertEqual(tabs.activeTab, tab, "tab is the activeTab"); + + tab.close(function() test.done()); + } + }); +}; + +// TEST: onOpen event handler +exports.testTabsEvent_onOpen = function(test) { + test.waitUntilDone(); + + let url = URL.replace('#title#', 'testTabsEvent_onOpen'); + let eventCount = 0; + + // add listener via property assignment + function listener1(tab) { + eventCount++; + }; + tabs.on('open', listener1); + + // add listener via collection add + tabs.on('open', function listener2(tab) { + test.assertEqual(++eventCount, 2, "both listeners notified"); + tabs.removeListener('open', listener1); + tabs.removeListener('open', listener2); + + // ends test + tab.close(function() test.done()); + }); + + tabs.open(url); +}; + +// TEST: onClose event handler +exports.testTabsEvent_onClose = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,onclose"; + let eventCount = 0; + + // add listener via property assignment + function listener1(tab) { + eventCount++; + } + tabs.on('close', listener1); + + // add listener via collection add + tabs.on('close', function listener2(tab) { + test.assertEqual(++eventCount, 2, "both listeners notified"); + tabs.removeListener('close', listener1); + tabs.removeListener('close', listener2); + + // end test + test.done(); + }); + + tabs.on('ready', function onReady(tab) { + tabs.removeListener('ready', onReady); + tab.close(); + }); + + tabs.open(url); +}; + +// TEST: onClose event handler when a window is closed +exports.testTabsEvent_onCloseWindow = function(test) { + test.waitUntilDone(); + + let closeCount = 0, individualCloseCount = 0; + function listener() { + closeCount++; + } + tabs.on('close', listener); + + // One tab is already open with the window + let openTabs = 0; + function testCasePossiblyLoaded(tab) { + tab.close(function() { + if (++openTabs == 3) { + tabs.removeListener("close", listener); + + test.assertEqual(closeCount, 3, "Correct number of close events received"); + test.assertEqual(individualCloseCount, 3, + "Each tab with an attached onClose listener received a close " + + "event when the window was closed"); + + test.done(); + } + }); + } + + tabs.open({ + url: "data:text/html;charset=utf-8,tab2", + onOpen: testCasePossiblyLoaded, + onClose: function() individualCloseCount++ + }); + + tabs.open({ + url: "data:text/html;charset=utf-8,tab3", + onOpen: testCasePossiblyLoaded, + onClose: function() individualCloseCount++ + }); + + tabs.open({ + url: "data:text/html;charset=utf-8,tab4", + onOpen: testCasePossiblyLoaded, + onClose: function() individualCloseCount++ + }); +}; + +// TEST: onReady event handler +exports.testTabsEvent_onReady = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,onready"; + let eventCount = 0; + + // add listener via property assignment + function listener1(tab) { + eventCount++; + }; + tabs.on('ready', listener1); + + // add listener via collection add + tabs.on('ready', function listener2(tab) { + test.assertEqual(++eventCount, 2, "both listeners notified"); + tabs.removeListener('ready', listener1); + tabs.removeListener('ready', listener2); + + // end test + tab.close(function() test.done()); + }); + + tabs.open(url); +}; + +// TEST: onActivate event handler +exports.testTabsEvent_onActivate = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,onactivate"; + let eventCount = 0; + + // add listener via property assignment + function listener1(tab) { + eventCount++; + }; + tabs.on('activate', listener1); + + // add listener via collection add + tabs.on('activate', function listener2(tab) { + test.assertEqual(++eventCount, 2, "both listeners notified"); + test.assertEqual(tab, tabs.activeTab, 'the active tab is correct'); + tabs.removeListener('activate', listener1); + tabs.removeListener('activate', listener2); + + // end test + tab.close(function() test.done()); + }); + + tabs.open(url); +}; + +// TEST: onDeactivate event handler +exports.testTabsEvent_onDeactivate = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,ondeactivate"; + let eventCount = 0; + + // add listener via property assignment + function listener1(tab) { + eventCount++; + }; + tabs.on('deactivate', listener1); + + // add listener via collection add + tabs.on('deactivate', function listener2(tab) { + test.assertEqual(++eventCount, 2, 'both listeners notified'); + test.assertNotEqual(tab, tabs.activeTab, 'the active tab is not the deactivated tab'); + tabs.removeListener('deactivate', listener1); + tabs.removeListener('deactivate', listener2); + + // end test + tab.close(function() test.done()); + }); + + tabs.on('activate', function onActivate(tab) { + tabs.removeListener('activate', onActivate); + tabs.open("data:text/html;charset=utf-8,foo"); + tab.close(); + }); + + tabs.open(url); +}; + +// TEST: per-tab event handlers +exports.testPerTabEvents = function(test) { + test.waitUntilDone(); + + let eventCount = 0; + + tabs.open({ + url: "data:text/html;charset=utf-8,foo", + onOpen: function(tab) { + // add listener via property assignment + function listener1() { + eventCount++; + }; + tab.on('ready', listener1); + + // add listener via collection add + tab.on('ready', function listener2() { + test.assertEqual(eventCount, 1, "both listeners notified"); + tab.removeListener('ready', listener1); + tab.removeListener('ready', listener2); + + // end test + tab.close(function() test.done()); + }); + } + }); +}; + +// TEST: tabs.activeTab getter +exports.testActiveTab_getter_alt = function(test) { + test.waitUntilDone(); + + let url = URL.replace("#title#", "foo"); + tabs.open({ + url: url, + onActivate: function(tab) { + test.assertEqual(tabs.activeTab.url, tab.url, 'the active tab is correct'); + + tab.once('ready', function() { + test.assertEqual(tab.url, url); + test.assertEqual(tab.title, "foo"); + + tab.close(function() { + // end test + test.done(); + }); + }); + } + }); +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-tabs.js b/tools/addon-sdk-1.12/test/tabs/test-firefox-tabs.js index 5719ab4..d7c822b 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-tabs.js +++ b/tools/addon-sdk-1.12/test/tabs/test-firefox-tabs.js @@ -1,20 +1,22 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; +'use strict'; -var {Cc,Ci} = require("chrome"); -const { Loader } = require("./helpers"); +const { Cc, Ci } = require('chrome'); +const { Loader } = require('sdk/test/loader'); +const timer = require('sdk/timers'); +const { StringBundle } = require('sdk/deprecated/app-strings'); -// test tab.activeTab getter +// TEST: tabs.activeTab getter exports.testActiveTab_getter = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); - let url = "data:text/html,<html><head><title>foo</title></head></html>"; - require("tab-browser").addTab( + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head></html>"; + require("sdk/deprecated/tab-browser").addTab( url, { onLoad: function(e) { @@ -28,34 +30,86 @@ exports.testActiveTab_getter = function(test) { }); }; -// test 'BrowserWindow' instance creation on tab 'activate' event +// Bug 682681 - tab.title should never be empty +exports.testBug682681_aboutURI = function(test) { + test.waitUntilDone(); + + let tabStrings = StringBundle('chrome://browser/locale/tabbrowser.properties'); + + openBrowserWindow(function(window, browser) { + let tabs = require("sdk/tabs"); + + tabs.on('ready', function onReady(tab) { + tabs.removeListener('ready', onReady); + + test.assertEqual(tab.title, + tabStrings.get('tabs.emptyTabTitle'), + "title of about: tab is not blank"); + + // end of test + closeBrowserWindow(window, function() test.done()); + }); + + // open a about: url + tabs.open({ + url: "about:blank", + inBackground: true + }); + }); +}; + +// related to Bug 682681 +exports.testTitleForDataURI = function(test) { + test.waitUntilDone(); + + openBrowserWindow(function(window, browser) { + let tabs = require("sdk/tabs"); + + tabs.on('ready', function onReady(tab) { + tabs.removeListener('ready', onReady); + + test.assertEqual(tab.title, "tab", "data: title is not Connecting..."); + + // end of test + closeBrowserWindow(window, function() test.done()); + }); + + // open a about: url + tabs.open({ + url: "data:text/html;charset=utf-8,<title>tab</title>", + inBackground: true + }); + }); +}; + +// TEST: 'BrowserWindow' instance creation on tab 'activate' event // See bug 648244: there was a infinite loop. exports.testBrowserWindowCreationOnActivate = function(test) { test.waitUntilDone(); - - let windows = require("windows").browserWindows; - let tabs = require("tabs"); - + + let windows = require("sdk/windows").browserWindows; + let tabs = require("sdk/tabs"); + let gotActivate = false; - + tabs.once('activate', function onActivate(eventTab) { test.assert(windows.activeWindow, "Is able to fetch activeWindow"); gotActivate = true; }); - + openBrowserWindow(function(window, browser) { test.assert(gotActivate, "Received activate event before openBrowserWindow's callback is called"); closeBrowserWindow(window, function () test.done()); }); } -// test tab.activeTab setter +// TEST: tab.activate() exports.testActiveTab_setter = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,<html><head><title>foo</title></head></html>"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head></html>"; tabs.on('ready', function onReady(tab) { tabs.removeListener('ready', onReady); @@ -78,33 +132,33 @@ exports.testActiveTab_setter = function(test) { }); }; +// TEST: tab unloader exports.testAutomaticDestroy = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - + let tabs = require("sdk/tabs"); + // Create a second tab instance that we will destroy let called = false; - + let loader = Loader(module); - let tabs2 = loader.require("tabs"); + let tabs2 = loader.require("sdk/tabs"); tabs2.on('open', function onOpen(tab) { called = true; }); - + loader.unload(); - - // Fire a tab event an ensure that this destroyed tab is inactive + + // Fire a tab event and ensure that the destroyed tab is inactive tabs.once('open', function () { - require("timer").setTimeout(function () { + timer.setTimeout(function () { test.assert(!called, "Unloaded tab module is destroyed and inactive"); closeBrowserWindow(window, function() test.done()); }, 0); }); - - tabs.open("data:text/html,foo"); - + + tabs.open("data:text/html;charset=utf-8,foo"); }); }; @@ -112,8 +166,8 @@ exports.testAutomaticDestroy = function(test) { exports.testTabProperties = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs= require("tabs"); - let url = "data:text/html,<html><head><title>foo</title></head><body>foo</body></html>"; + let tabs= require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head><body>foo</body></html>"; tabs.open({ url: url, onReady: function(tab) { @@ -129,15 +183,37 @@ exports.testTabProperties = function(test) { }); }; -// test tabs iterator and length property +// TEST: tab properties +exports.testTabContentTypeAndReload = function(test) { + test.waitUntilDone(); + openBrowserWindow(function(window, browser) { + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head><body>foo</body></html>"; + let urlXML = "data:text/xml;charset=utf-8,<foo>bar</foo>"; + tabs.open({ + url: url, + onReady: function(tab) { + if (tab.url === url) { + test.assertEqual(tab.contentType, "text/html"); + tab.url = urlXML; + } else { + test.assertEqual(tab.contentType, "text/xml"); + closeBrowserWindow(window, function() test.done()); + } + } + }); + }); +}; + +// TEST: tabs iterator and length property exports.testTabsIteratorAndLength = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); let startCount = 0; for each (let t in tabs) startCount++; test.assertEqual(startCount, tabs.length, "length property is correct"); - let url = "data:text/html,default"; + let url = "data:text/html;charset=utf-8,default"; tabs.open(url); tabs.open(url); tabs.open({ @@ -153,13 +229,13 @@ exports.testTabsIteratorAndLength = function(test) { }); }; -// test tab.url setter +// TEST: tab.url setter exports.testTabLocation = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url1 = "data:text/html,foo"; - let url2 = "data:text/html,bar"; + let tabs = require("sdk/tabs"); + let url1 = "data:text/html;charset=utf-8,foo"; + let url2 = "data:text/html;charset=utf-8,bar"; tabs.on('ready', function onReady(tab) { if (tab.url != url2) @@ -178,19 +254,22 @@ exports.testTabLocation = function(test) { }); }; -// test tab.close() +// TEST: tab.close() exports.testTabClose = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,foo"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,foo"; - test.assertNotEqual(tabs.activeTab.url, url, "tab is now the active tab"); + test.assertNotEqual(tabs.activeTab.url, url, "tab is not the active tab"); tabs.on('ready', function onReady(tab) { tabs.removeListener('ready', onReady); test.assertEqual(tabs.activeTab.url, tab.url, "tab is now the active tab"); tab.close(function() { - closeBrowserWindow(window, function() test.done()); + closeBrowserWindow(window, function() { + test.assertNotEqual(tabs.activeTab.url, url, "tab is no longer the active tab"); + test.done() + }); }); test.assertNotEqual(tabs.activeTab.url, url, "tab is no longer the active tab"); }); @@ -199,12 +278,12 @@ exports.testTabClose = function(test) { }); }; -// test tab.reload() +// TEST: tab.reload() exports.testTabReload = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,<!doctype%20html><title></title>"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,<!doctype%20html><title></title>"; tabs.open({ url: url, onReady: function onReady(tab) { tab.removeListener("ready", onReady); @@ -232,12 +311,12 @@ exports.testTabReload = function(test) { }); }; -// test tab.move() +// TEST: tab.move() exports.testTabMove = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,foo"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,foo"; tabs.open({ url: url, @@ -251,32 +330,34 @@ exports.testTabMove = function(test) { }); }; -// open tab with default options +// TEST: open tab with default options exports.testOpen = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,default"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,default"; tabs.open({ url: url, onReady: function(tab) { test.assertEqual(tab.url, url, "URL of the new tab matches"); test.assertEqual(window.content.location, url, "URL of active tab in the current window matches"); + test.assertEqual(tab.isPinned, false, "The new tab is not pinned"); + closeBrowserWindow(window, function() test.done()); } }); }); }; -// open pinned tab +// TEST: open pinned tab exports.testOpenPinned = function(test) { - const xulApp = require("xul-app"); + const xulApp = require("sdk/system/xul-app"); if (xulApp.versionInRange(xulApp.platformVersion, "2.0b2", "*")) { // test tab pinning test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,default"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,default"; tabs.open({ url: url, isPinned: true, @@ -292,14 +373,14 @@ exports.testOpenPinned = function(test) { } }; -// pin/unpin opened tab +// TEST: pin/unpin opened tab exports.testPinUnpin = function(test) { - const xulApp = require("xul-app"); + const xulApp = require("sdk/system/xul-app"); if (xulApp.versionInRange(xulApp.platformVersion, "2.0b2", "*")) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let url = "data:text/html,default"; + let tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,default"; tabs.open({ url: url, onOpen: function(tab) { @@ -317,13 +398,13 @@ exports.testPinUnpin = function(test) { } }; -// open tab in background +// TEST: open tab in background exports.testInBackground = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); let activeUrl = tabs.activeTab.url; - let url = "data:text/html,background"; + let url = "data:text/html;charset=utf-8,background"; test.assertEqual(activeWindow, window, "activeWindow matches this window"); tabs.on('ready', function onReady(tab) { tabs.removeListener('ready', onReady); @@ -340,14 +421,14 @@ exports.testInBackground = function(test) { }); }; -// open tab in new window +// TEST: open tab in new window exports.testOpenInNewWindow = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); let cache = []; - let windowUtils = require("window-utils"); + let windowUtils = require("sdk/deprecated/window-utils"); let wt = new windowUtils.WindowTracker({ onTrack: function(win) { cache.push(win); @@ -358,7 +439,7 @@ exports.testOpenInNewWindow = function(test) { }); let startWindowCount = cache.length; - let url = "data:text/html,newwindow"; + let url = "data:text/html;charset=utf-8,newwindow"; tabs.open({ url: url, inNewWindow: true, @@ -379,12 +460,12 @@ exports.testOpenInNewWindow = function(test) { }); }; -// onOpen event handler +// TEST: onOpen event handler exports.testTabsEvent_onOpen = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,1"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,1"; let eventCount = 0; // add listener via property assignment @@ -405,12 +486,12 @@ exports.testTabsEvent_onOpen = function(test) { }); }; -// onClose event handler +// TEST: onClose event handler exports.testTabsEvent_onClose = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,onclose"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,onclose"; let eventCount = 0; // add listener via property assignment @@ -436,12 +517,12 @@ exports.testTabsEvent_onClose = function(test) { }); }; -// onClose event handler when a window is closed +// TEST: onClose event handler when a window is closed exports.testTabsEvent_onCloseWindow = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); + var tabs = require("sdk/tabs"); let closeCount = 0, individualCloseCount = 0; function listener() { @@ -458,19 +539,19 @@ exports.testTabsEvent_onCloseWindow = function(test) { } tabs.open({ - url: "data:text/html,tab2", + url: "data:text/html;charset=utf-8,tab2", onOpen: function() testCasePossiblyLoaded(), onClose: function() individualCloseCount++ }); tabs.open({ - url: "data:text/html,tab3", + url: "data:text/html;charset=utf-8,tab3", onOpen: function() testCasePossiblyLoaded(), onClose: function() individualCloseCount++ }); tabs.open({ - url: "data:text/html,tab4", + url: "data:text/html;charset=utf-8,tab4", onOpen: function() testCasePossiblyLoaded(), onClose: function() individualCloseCount++ }); @@ -491,12 +572,12 @@ exports.testTabsEvent_onCloseWindow = function(test) { }); } -// onReady event handler +// TEST: onReady event handler exports.testTabsEvent_onReady = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,onready"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,onready"; let eventCount = 0; // add listener via property assignment @@ -517,12 +598,12 @@ exports.testTabsEvent_onReady = function(test) { }); }; -// onActivate event handler +// TEST: onActivate event handler exports.testTabsEvent_onActivate = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,onactivate"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,onactivate"; let eventCount = 0; // add listener via property assignment @@ -547,8 +628,8 @@ exports.testTabsEvent_onActivate = function(test) { exports.testTabsEvent_onDeactivate = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,ondeactivate"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,ondeactivate"; let eventCount = 0; // add listener via property assignment @@ -567,18 +648,19 @@ exports.testTabsEvent_onDeactivate = function(test) { tabs.on('open', function onOpen(tab) { tabs.removeListener('open', onOpen); - tabs.open("data:text/html,foo"); + tabs.open("data:text/html;charset=utf-8,foo"); }); tabs.open(url); }); }; +// pinning exports.testTabsEvent_pinning = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); - let url = "data:text/html,1"; + var tabs = require("sdk/tabs"); + let url = "data:text/html;charset=utf-8,1"; tabs.on('open', function onOpen(tab) { tabs.removeListener('open', onOpen); @@ -601,15 +683,15 @@ exports.testTabsEvent_pinning = function(test) { }); }; -// per-tab event handlers +// TEST: per-tab event handlers exports.testPerTabEvents = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - var tabs = require("tabs"); + var tabs = require("sdk/tabs"); let eventCount = 0; tabs.open({ - url: "data:text/html,foo", + url: "data:text/html;charset=utf-8,foo", onOpen: function(tab) { // add listener via property assignment function listener1() { @@ -633,15 +715,15 @@ exports.testAttachOnOpen = function (test) { // Take care that attach has to be called on tab ready and not on tab open. test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - + let tabs = require("sdk/tabs"); + tabs.open({ - url: "data:text/html,foobar", + url: "data:text/html;charset=utf-8,foobar", onOpen: function (tab) { let worker = tab.attach({ contentScript: 'self.postMessage(document.location.href); ', onMessage: function (msg) { - test.assertEqual(msg, "about:blank", + test.assertEqual(msg, "about:blank", "Worker document url is about:blank on open"); worker.destroy(); closeBrowserWindow(window, function() test.done()); @@ -649,7 +731,7 @@ exports.testAttachOnOpen = function (test) { }); } }); - + }); } @@ -657,10 +739,10 @@ exports.testAttachOnMultipleDocuments = function (test) { // Example of attach that process multiple tab documents test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let firstLocation = "data:text/html,foobar"; - let secondLocation = "data:text/html,bar"; - let thirdLocation = "data:text/html,fox"; + let tabs = require("sdk/tabs"); + let firstLocation = "data:text/html;charset=utf-8,foobar"; + let secondLocation = "data:text/html;charset=utf-8,bar"; + let thirdLocation = "data:text/html;charset=utf-8,fox"; let onReadyCount = 0; let worker1 = null; let worker2 = null; @@ -675,7 +757,7 @@ exports.testAttachOnMultipleDocuments = function (test) { ' function () self.postMessage(document.location.href)' + ');', onMessage: function (msg) { - test.assertEqual(msg, firstLocation, + test.assertEqual(msg, firstLocation, "Worker url is equal to the 1st document"); tab.url = secondLocation; }, @@ -684,22 +766,22 @@ exports.testAttachOnMultipleDocuments = function (test) { test.pass("Got worker1 detach event"); test.assertRaises(function () { worker1.postMessage("ex-1"); - }, - /The page has been destroyed/, + }, + /Couldn't find the worker/, "postMessage throw because worker1 is destroyed"); checkEnd(); } }); worker1.postMessage("new-doc-1"); - } + } else if (onReadyCount == 2) { - + worker2 = tab.attach({ contentScript: 'self.on("message", ' + ' function () self.postMessage(document.location.href)' + ');', onMessage: function (msg) { - test.assertEqual(msg, secondLocation, + test.assertEqual(msg, secondLocation, "Worker url is equal to the 2nd document"); tab.url = thirdLocation; }, @@ -708,32 +790,29 @@ exports.testAttachOnMultipleDocuments = function (test) { test.pass("Got worker2 detach event"); test.assertRaises(function () { worker2.postMessage("ex-2"); - }, - /The page has been destroyed/, + }, + /Couldn't find the worker/, "postMessage throw because worker2 is destroyed"); checkEnd(); } }); worker2.postMessage("new-doc-2"); - } + } else if (onReadyCount == 3) { - tab.close(); - } - } }); - + function checkEnd() { if (detachEventCount != 2) return; - + test.pass("Got all detach events"); - + closeBrowserWindow(window, function() test.done()); } - + }); } @@ -742,11 +821,11 @@ exports.testAttachWrappers = function (test) { // Check that content script has access to wrapped values by default test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let document = "data:text/html,<script>var globalJSVar = true; " + + let tabs = require("sdk/tabs"); + let document = "data:text/html;charset=utf-8,<script>var globalJSVar = true; " + " document.getElementById = 3;</script>"; let count = 0; - + tabs.open({ url: document, onReady: function (tab) { @@ -765,7 +844,7 @@ exports.testAttachWrappers = function (test) { }); } }); - + }); } @@ -776,10 +855,10 @@ exports.testAttachUnwrapped = function (test) { // Check that content script has access to unwrapped values through unsafeWindow test.waitUntilDone(); openBrowserWindow(function(window, browser) { - let tabs = require("tabs"); - let document = "data:text/html,<script>var globalJSVar=true;</script>"; + let tabs = require("sdk/tabs"); + let document = "data:text/html;charset=utf-8,<script>var globalJSVar=true;</script>"; let count = 0; - + tabs.open({ url: document, onReady: function (tab) { @@ -796,7 +875,7 @@ exports.testAttachUnwrapped = function (test) { }); } }); - + }); } */ @@ -805,7 +884,7 @@ exports['test window focus changes active tab'] = function(test) { test.waitUntilDone(); let win1 = openBrowserWindow(function() { let win2 = openBrowserWindow(function() { - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); tabs.on("activate", function onActivate() { tabs.removeListener("activate", onActivate); test.pass("activate was called on windows focus change."); @@ -814,17 +893,17 @@ exports['test window focus changes active tab'] = function(test) { }); }); win1.focus(); - }, "data:text/html,test window focus changes active tab</br><h1>Window #2"); - }, "data:text/html,test window focus changes active tab</br><h1>Window #1"); + }, "data:text/html;charset=utf-8,test window focus changes active tab</br><h1>Window #2"); + }, "data:text/html;charset=utf-8,test window focus changes active tab</br><h1>Window #1"); }; exports['test ready event on new window tab'] = function(test) { test.waitUntilDone(); - let uri = encodeURI("data:text/html,Waiting for ready event!"); + let uri = encodeURI("data:text/html;charset=utf-8,Waiting for ready event!"); - require("tabs").on("ready", function onReady(tab) { + require("sdk/tabs").on("ready", function onReady(tab) { if (tab.url === uri) { - require("tabs").removeListener("ready", onReady); + require("sdk/tabs").removeListener("ready", onReady); test.pass("ready event was emitted"); closeBrowserWindow(window, function() { test.done(); @@ -852,17 +931,20 @@ function openBrowserWindow(callback, url) { urlString.data = url; let window = ww.openWindow(null, "chrome://browser/content/browser.xul", "_blank", "chrome,all,dialog=no", urlString); - + if (callback) { window.addEventListener("load", function onLoad(event) { if (event.target && event.target.defaultView == window) { window.removeEventListener("load", onLoad, true); let browsers = window.document.getElementsByTagName("tabbrowser"); try { - require("timer").setTimeout(function () { + timer.setTimeout(function () { callback(window, browsers[0]); }, 10); - } catch (e) { console.exception(e); } + } + catch (e) { + console.exception(e); + } } }, true); } @@ -883,18 +965,18 @@ function closeBrowserWindow(window, callback) { // throw. In that case, remove all tests above from exports, and add one dummy // test that passes. try { - require("tabs"); + require("sdk/tabs"); } catch (err) { // This bug should be mentioned in the error message. let bug = "https://bugzilla.mozilla.org/show_bug.cgi?id=560716"; + if (err.message.indexOf(bug) < 0) throw err; - for (let [prop, val] in Iterator(exports)) { - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; + + module.exports = { + testAppNotSupported: function (test) { + test.pass("the tabs module does not support this application."); + } } - exports.testAppNotSupported = function (test) { - test.pass("the tabs module does not support this application."); - }; } diff --git a/tools/addon-sdk-1.12/test/test-addon-installer.js b/tools/addon-sdk-1.12/test/test-addon-installer.js new file mode 100644 index 0000000..e2d3b10 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-addon-installer.js @@ -0,0 +1,131 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const { Cc, Ci, Cu } = require("chrome"); +const AddonInstaller = require("sdk/addon/installer"); +const observers = require("sdk/deprecated/observer-service"); +const { setTimeout } = require("sdk/timers"); +const tmp = require("sdk/test/tmp-file"); +const system = require("sdk/system"); + +const testFolderURL = module.uri.split('test-addon-installer.js')[0]; +const ADDON_URL = testFolderURL + "fixtures/addon-install-unit-test@mozilla.com.xpi"; +const ADDON_PATH = tmp.createFromURL(ADDON_URL); + +exports.testInstall = function (test) { + test.waitUntilDone(); + + // Save all events distpatched by bootstrap.js of the installed addon + let events = []; + function eventsObserver(subject, data) { + events.push(data); + } + observers.add("addon-install-unit-test", eventsObserver, false); + + // Install the test addon + AddonInstaller.install(ADDON_PATH).then( + function onInstalled(id) { + test.assertEqual(id, "addon-install-unit-test@mozilla.com", "`id` is valid"); + + // Now uninstall it + AddonInstaller.uninstall(id).then(function () { + // Ensure that bootstrap.js methods of the addon have been called + // successfully and in the right order + let expectedEvents = ["install", "startup", "shutdown", "uninstall"]; + test.assertEqual(JSON.stringify(events), + JSON.stringify(expectedEvents), + "addon's bootstrap.js functions have been called"); + + observers.remove("addon-install-unit-test", eventsObserver); + test.done(); + }); + }, + function onFailure(code) { + test.fail("Install failed: "+code); + observers.remove("addon-install-unit-test", eventsObserver); + test.done(); + } + ); +} + +exports.testFailingInstallWithInvalidPath = function (test) { + test.waitUntilDone(); + + AddonInstaller.install("invalid-path").then( + function onInstalled(id) { + test.fail("Unexpected success"); + test.done(); + }, + function onFailure(code) { + test.assertEqual(code, AddonInstaller.ERROR_FILE_ACCESS, + "Got expected error code"); + test.done(); + } + ); +} + +exports.testFailingInstallWithInvalidFile = function (test) { + test.waitUntilDone(); + + let directory = system.pathFor("ProfD"); + AddonInstaller.install(directory).then( + function onInstalled(id) { + test.fail("Unexpected success"); + test.done(); + }, + function onFailure(code) { + test.assertEqual(code, AddonInstaller.ERROR_CORRUPT_FILE, + "Got expected error code"); + test.done(); + } + ); +} + +exports.testUpdate = function (test) { + test.waitUntilDone(); + + // Save all events distpatched by bootstrap.js of the installed addon + let events = []; + let iteration = 1; + function eventsObserver(subject, data) { + events.push(data); + } + observers.add("addon-install-unit-test", eventsObserver); + + function onInstalled(id) { + let prefix = "[" + iteration + "] "; + test.assertEqual(id, "addon-install-unit-test@mozilla.com", + prefix + "`id` is valid"); + + // On 2nd and 3rd iteration, we receive uninstall events from the last + // previously installed addon + let expectedEvents = + iteration == 1 + ? ["install", "startup"] + : ["shutdown", "uninstall", "install", "startup"]; + test.assertEqual(JSON.stringify(events), + JSON.stringify(expectedEvents), + prefix + "addon's bootstrap.js functions have been called"); + + if (iteration++ < 3) { + next(); + } + else { + observers.remove("addon-install-unit-test", eventsObserver); + test.done(); + } + } + function onFailure(code) { + test.fail("Install failed: "+code); + observers.remove("addon-install-unit-test", eventsObserver); + test.done(); + } + + function next() { + events = []; + AddonInstaller.install(ADDON_PATH).then(onInstalled, onFailure); + } + + next(); +} diff --git a/tools/addon-sdk-1.12/test/test-addon-page.js b/tools/addon-sdk-1.12/test/test-addon-page.js new file mode 100644 index 0000000..cff3273 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-addon-page.js @@ -0,0 +1,65 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +const { isTabOpen, activateTab, openTab, + closeTab, getURI } = require('sdk/tabs/utils'); +const windows = require('sdk/deprecated/window-utils'); +const { Loader } = require('sdk/test/loader'); +const { setTimeout } = require('sdk/timers'); +const { is } = require('sdk/system/xul-app'); +const tabs = require('sdk/tabs'); + +let uri = require('sdk/self').data.url('index.html'); + +function isChromeVisible(window) { + let x = window.document.documentElement.getAttribute('disablechrome') + return x !== 'true'; +} + +exports['test that add-on page has no chrome'] = function(assert, done) { + let loader = Loader(module); + loader.require('addon-kit/addon-page'); + + let window = windows.activeBrowserWindow; + let tab = openTab(window, uri); + + assert.ok(isChromeVisible(window), 'chrome is visible for non addon page'); + + // need to do this in another turn to make sure event listener + // that sets property has time to do that. + setTimeout(function() { + activateTab(tab); + + assert.equal(isChromeVisible(window), is('Fennec'), 'chrome is not visible for addon page'); + + closeTab(tab); + assert.ok(isChromeVisible(window), 'chrome is visible again'); + loader.unload(); + done(); + }); +}; + +exports['test that add-on pages are closed on unload'] = function(assert, done) { + let loader = Loader(module); + loader.require('sdk/addon-page'); + + // Wait for addon page document to be loaded + tabs.once("ready", function listener(tab) { + // Ignore loading of about:blank document + if (tab.url != uri) + return; + + loader.unload(); + assert.ok(!isTabOpen(tab), 'add-on page tabs are closed on unload'); + + done(); + }, false); + + tabs.open(uri); +}; + + +require('sdk/test').run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-api-utils.js b/tools/addon-sdk-1.12/test/test-api-utils.js index 15f1f3e..5ba031a 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-api-utils.js +++ b/tools/addon-sdk-1.12/test/test-api-utils.js @@ -4,7 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const apiUtils = require("api-utils/api-utils"); +const apiUtils = require("sdk/deprecated/api-utils"); exports.testPublicConstructor = function (test) { function PrivateCtor() {} @@ -204,36 +204,19 @@ exports.testAddIterator = function testAddIterator(test) { for (let i = 0; i < vals.length; i++) test.assertEqual(valsItr[i], vals[i], "the val is correct"); - let keysValsItr = []; - for (let keyVal in Iterator(obj)) - keysValsItr.push(keyVal); - test.assertEqual(keysValsItr.length, keysVals.length, "the keys/vals " + - "iterator returns the correct number of items"); - for (let i = 0; i < keysVals.length; i++) { - test.assertEqual(keysValsItr[i][0], keysVals[i][0], "the key is correct"); - test.assertEqual(keysValsItr[i][1], keysVals[i][1], "the val is correct"); - } - - let keysOnlyItr = []; - for (let key in Iterator(obj, true /* keysonly */)) - keysOnlyItr.push(key); - test.assertEqual(keysOnlyItr.length, keysVals.length, "the keys only " + - "iterator returns the correct number of items"); - for (let i = 0; i < keysVals.length; i++) - test.assertEqual(keysOnlyItr[i], keysVals[i][0], "the key is correct"); }; function assertObjsEqual(test, obj1, obj2) { var items = 0; - for (let [key, val] in Iterator(obj1)) { + for (let key in obj1) { items++; test.assert(key in obj2, "obj1 key should be present in obj2"); - test.assertEqual(obj2[key], val, "obj1 value should match obj2 value"); + test.assertEqual(obj2[key], obj1[key], "obj1 value should match obj2 value"); } - for (let [key, val] in Iterator(obj2)) { + for (let key in obj2) { items++; test.assert(key in obj1, "obj2 key should be present in obj1"); - test.assertEqual(obj1[key], val, "obj2 value should match obj1 value"); + test.assertEqual(obj1[key], obj2[key], "obj2 value should match obj1 value"); } if (!items) test.assertEqual(JSON.stringify(obj1), JSON.stringify(obj2), diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-app-strings.js b/tools/addon-sdk-1.12/test/test-app-strings.js index 902c31f..faa52fc 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-app-strings.js +++ b/tools/addon-sdk-1.12/test/test-app-strings.js @@ -4,7 +4,7 @@ const { Cc,Ci } = require("chrome"); -let StringBundle = require("app-strings").StringBundle; +let StringBundle = require("sdk/deprecated/app-strings").StringBundle; exports.testStringBundle = function(test) { let url = "chrome://global/locale/security/caps.properties"; @@ -43,8 +43,8 @@ exports.testStringBundle = function(test) { let elem = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement); a.push([elem.key, elem.value]); } - for (let keyVal in Iterator(strings)) - b.push(keyVal); + for (let key in strings) + b.push([ key, strings.get(key) ]); // Sort the arrays, because we don't assume enumeration has a set order. // Sort compares [key, val] as string "key,val", which sorts the way we want diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-array.js b/tools/addon-sdk-1.12/test/test-array.js index 878a6ce..d68891b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-array.js +++ b/tools/addon-sdk-1.12/test/test-array.js @@ -1,8 +1,9 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict' -var array = require("array"); +const array = require('sdk/util/array'); exports.testHas = function(test) { var testAry = [1, 2, 3]; @@ -14,7 +15,25 @@ exports.testHas = function(test) { test.assertEqual(array.has(testAry, 2), true); test.assertEqual(array.has(testAry, 3), true); test.assertEqual(array.has(testAry, 4), false); - test.assertEqual(array.has(testAry, "1"), false); + test.assertEqual(array.has(testAry, '1'), false); +}; +exports.testHasAny = function(test) { + var testAry = [1, 2, 3]; + test.assertEqual(array.hasAny([1, 2, 3], [1]), true); + test.assertEqual(array.hasAny([1, 2, 3], [1, 5]), true); + test.assertEqual(array.hasAny([1, 2, 3], [5, 1]), true); + test.assertEqual(array.hasAny([1, 2, 3], [5, 2]), true); + test.assertEqual(array.hasAny([1, 2, 3], [5, 3]), true); + test.assertEqual(array.hasAny([1, 2, 3], [5, 4]), false); + test.assertEqual(testAry.length, 3); + test.assertEqual(testAry[0], 1); + test.assertEqual(testAry[1], 2); + test.assertEqual(testAry[2], 3); + test.assertEqual(array.hasAny(testAry, [2]), true); + test.assertEqual(array.hasAny(testAry, [3]), true); + test.assertEqual(array.hasAny(testAry, [4]), false); + test.assertEqual(array.hasAny(testAry), false); + test.assertEqual(array.hasAny(testAry, '1'), false); }; exports.testAdd = function(test) { @@ -38,3 +57,10 @@ exports.testRemove = function(test) { test.assertEqual(testAry.length, 1); test.assertEqual(testAry[0], 1); }; + +exports.testFlatten = function(test) { + test.assertEqual(array.flatten([1, 2, 3]).length, 3); + test.assertEqual(array.flatten([1, [2, 3]]).length, 3); + test.assertEqual(array.flatten([1, [2, [3]]]).length, 3); + test.assertEqual(array.flatten([[1], [[2, [3]]]]).length, 3); +}; diff --git a/tools/addon-sdk-1.12/test/test-base64.js b/tools/addon-sdk-1.12/test/test-base64.js new file mode 100644 index 0000000..6ca7500 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-base64.js @@ -0,0 +1,75 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const base64 = require("sdk/base64"); + +const text = "Awesome!"; +const b64text = "QXdlc29tZSE="; + +const utf8text = "✓ à la mode"; +const b64utf8text = "4pyTIMOgIGxhIG1vZGU="; + +exports["test base64.encode"] = function (assert) { + assert.equal(base64.encode(text), b64text, "encode correctly") +} + +exports["test base64.decode"] = function (assert) { + assert.equal(base64.decode(b64text), text, "decode correctly") +} + +exports["test base64.encode Unicode"] = function (assert) { + + assert.equal(base64.encode(utf8text, "utf-8"), b64utf8text, + "encode correctly Unicode strings.") +} + +exports["test base64.decode Unicode"] = function (assert) { + + assert.equal(base64.decode(b64utf8text, "utf-8"), utf8text, + "decode correctly Unicode strings.") +} + +exports["test base64.encode with wrong charset"] = function (assert) { + + assert.throws(function() { + base64.encode(utf8text, "utf-16"); + }, "The charset argument can be only 'utf-8'"); + + assert.throws(function() { + base64.encode(utf8text, ""); + }, "The charset argument can be only 'utf-8'"); + + assert.throws(function() { + base64.encode(utf8text, 8); + }, "The charset argument can be only 'utf-8'"); + +} + +exports["test base64.decode with wrong charset"] = function (assert) { + + assert.throws(function() { + base64.decode(utf8text, "utf-16"); + }, "The charset argument can be only 'utf-8'"); + + assert.throws(function() { + base64.decode(utf8text, ""); + }, "The charset argument can be only 'utf-8'"); + + assert.throws(function() { + base64.decode(utf8text, 8); + }, "The charset argument can be only 'utf-8'"); + +} + +exports["test encode/decode Unicode without utf-8 as charset"] = function (assert) { + + assert.notEqual(base64.decode(base64.encode(utf8text)), utf8text, + "Unicode strings needs 'utf-8' charset" + ); + +} + +require("test").run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-byte-streams.js b/tools/addon-sdk-1.12/test/test-byte-streams.js index 5bd1e42..18a105a 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-byte-streams.js +++ b/tools/addon-sdk-1.12/test/test-byte-streams.js @@ -4,10 +4,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const byteStreams = require("byte-streams"); -const file = require("file"); -const { pathFor } = require("api-utils/system"); -const { Loader } = require("./helpers"); +const byteStreams = require("sdk/io/byte-streams"); +const file = require("sdk/io/file"); +const { pathFor } = require("sdk/system"); +const { Loader } = require("sdk/test/loader"); const STREAM_CLOSED_ERROR = "The stream is closed and cannot be used."; @@ -145,7 +145,7 @@ exports.testTruncate = function (test) { exports.testUnload = function (test) { let loader = Loader(module); - let file = loader.require("file"); + let file = loader.require("sdk/io/file"); let filename = dataFileFilename("temp-b"); let stream = file.open(filename, "wb"); diff --git a/tools/addon-sdk-1.12/test/test-chrome.js b/tools/addon-sdk-1.12/test/test-chrome.js new file mode 100644 index 0000000..697d392 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-chrome.js @@ -0,0 +1,86 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +'use strict'; + +let chrome = require('chrome'); + +const FIXTURES_URL = module.uri.substr(0, module.uri.lastIndexOf('/') + 1) + + 'fixtures/chrome-worker/' + +exports['test addEventListener'] = function(assert, done) { + let uri = FIXTURES_URL + 'addEventListener.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.addEventListener('message', function(event) { + assert.equal(event.data, 'Hello', 'message received'); + worker.terminate(); + done(); + }); +}; + +exports['test onmessage'] = function(assert, done) { + let uri = FIXTURES_URL + 'onmessage.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.onmessage = function(event) { + assert.equal(event.data, 'ok', 'message received'); + worker.terminate(); + done(); + }; + worker.postMessage('ok'); +}; + +exports['test setTimeout'] = function(assert, done) { + let uri = FIXTURES_URL + 'setTimeout.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.onmessage = function(event) { + assert.equal(event.data, 'ok', 'setTimeout fired'); + worker.terminate(); + done(); + }; +}; + +exports['test jsctypes'] = function(assert, done) { + let uri = FIXTURES_URL + 'jsctypes.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.onmessage = function(event) { + assert.equal(event.data, 'function', 'ctypes.open is a function'); + worker.terminate(); + done(); + }; +}; + +exports['test XMLHttpRequest'] = function(assert, done) { + let uri = FIXTURES_URL + 'xhr.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.onmessage = function(event) { + assert.equal(event.data, 'ok', 'XMLHttpRequest works'); + worker.terminate(); + done(); + }; +}; + +exports['test onerror'] = function(assert, done) { + let uri = FIXTURES_URL + 'onerror.js'; + + let worker = new chrome.ChromeWorker(uri); + worker.onerror = function(event) { + assert.equal(event.filename, uri, 'event reports the correct uri'); + assert.equal(event.lineno, 8, 'event reports the correct line number'); + assert.equal(event.target, worker, 'event reports the correct worker'); + assert.ok(event.message.match(/ok/), + 'event contains the exception message'); + // Call preventDefault in order to avoid being displayed in JS console. + event.preventDefault(); + worker.terminate(); + done(); + }; +}; + +require('test').run(exports); diff --git a/tools/addon-sdk-1.12/test/test-clipboard.js b/tools/addon-sdk-1.12/test/test-clipboard.js new file mode 100644 index 0000000..4749747 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-clipboard.js @@ -0,0 +1,214 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Cc, Ci } = require("chrome"); + +const imageTools = Cc["@mozilla.org/image/tools;1"]. + getService(Ci.imgITools); + +const io = Cc["@mozilla.org/network/io-service;1"]. + getService(Ci.nsIIOService); + +const base64png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYA" + + "AABzenr0AAAASUlEQVRYhe3O0QkAIAwD0eyqe3Q993AQ3cBSUKpygfsNTy" + + "N5ugbQpK0BAADgP0BRDWXWlwEAAAAAgPsA3rzDaAAAAHgPcGrpgAnzQ2FG" + + "bWRR9AAAAABJRU5ErkJggg%3D%3D"; + +const base64jpeg = "data:image/jpeg;base64,%2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F" + + "2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCg" + + "sOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD%2F2wBDAQMDAwQDBAgEBAgQCw" + + "kLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQ" + + "EBAQEBAQEBD%2FwAARCAAgACADAREAAhEBAxEB%2F8QAHwAAAQUBAQEBAQ" + + "EAAAAAAAAAAAECAwQFBgcICQoL%2F8QAtRAAAgEDAwIEAwUFBAQAAAF9AQ" + + "IDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRol" + + "JicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eX" + + "qDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJ" + + "ytLT1NXW19jZ2uHi4%2BTl5ufo6erx8vP09fb3%2BPn6%2F8QAHwEAAwEB" + + "AQEBAQEBAQAAAAAAAAECAwQFBgcICQoL%2F8QAtREAAgECBAQDBAcFBAQA" + + "AQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNO" + + "El8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0" + + "dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6ws" + + "PExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3%2BPn6%2F9oADAMB" + + "AAIRAxEAPwD5Kr8kP9CwoA5f4m%2F8iRqX%2FbH%2FANHJXr5F%2FwAjCn" + + "8%2F%2FSWfnnir%2FwAkji%2F%2B4f8A6dgeD1%2BiH8bn1BX5If6FmFqW" + + "pXtveyQwzbUXGBtB7D2r9l4U4UyjMsoo4rFUeacua75pLaUktFJLZH5NxN" + + "xNmmX5pVw2Gq8sI8tlyxe8U3q03uzD8S3dxqOi3NneSeZDJs3LgDOHBHI5" + + "6gV%2BkcG%2BH%2FDmJzuhSq4e8XzfbqfyS%2FvH5rx1xTm2MyDEUa1W8X" + + "yXXLFbTi%2BkThv7B0r%2FAJ9f%2FH2%2Fxr90%2FwCIVcI%2F9An%2FAJ" + + "Uq%2FwDyZ%2FO%2F16v%2FADfgv8j0r%2FhZvgj%2FAKDf%2FktN%2FwDE" + + "V%2Fnr%2FYWYf8%2B%2Fxj%2Fmf3R%2FxFXhH%2FoL%2FwDKdX%2F5Azrv" + + "xLouo3D3lne%2BZDJja3luM4GDwRnqDX9LeH%2FBud4nhzD1aVC8Xz%2Fa" + + "h%2Fz8l%2FePx%2FinjrIMZm1WtRxF4vls%2BSa2jFdYlDUdRsp7OSKKbc" + + "7YwNpHce1fqfCvCub5bm9HFYqjywjzXfNF7xklopN7s%2BC4l4lyvMMrq4" + + "fD1bzfLZcsltJPqktkYlfsZ%2BUnBV%2FnufVnXaD%2FAMgqD%2FgX%2Fo" + + "Rr%2BxvCr%2FkkcJ%2F3E%2F8ATsz5%2FHfx5fL8kX6%2FQjkCgD%2F%2F" + + "2Q%3D%3D"; + +const canvasHTML = "data:text/html," + encodeURIComponent( + "<html>\ + <body>\ + <canvas width='32' height='32'></canvas>\ + </body>\ + </html>" +); + +function comparePixelImages(imageA, imageB, callback) { + let tabs = require("sdk/tabs"); + + tabs.open({ + url: canvasHTML, + + onReady: function onReady(tab) { + let worker = tab.attach({ + contentScript: "new " + function() { + let canvas = document.querySelector("canvas"); + let context = canvas.getContext("2d"); + + self.port.on("draw-image", function(imageURI) { + let img = new Image(); + + img.onload = function() { + context.drawImage(this, 0, 0); + + let pixels = Array.join(context.getImageData(0, 0, 32, 32).data); + self.port.emit("image-pixels", pixels); + } + + img.src = imageURI; + }); + } + }); + + let compared = ""; + + worker.port.on("image-pixels", function (pixels) { + if (!compared) { + compared = pixels; + this.emit("draw-image", imageB); + } else { + callback(compared === pixels); + tab.close() + } + }); + + worker.port.emit("draw-image", imageA); + } + }); +} + + +// Test the typical use case, setting & getting with no flavors specified +exports.testWithNoFlavor = function(test) { + var contents = "hello there"; + var flavor = "text"; + var fullFlavor = "text/unicode"; + var clip = require("sdk/clipboard"); + // Confirm we set the clipboard + test.assert(clip.set(contents)); + // Confirm flavor is set + test.assertEqual(clip.currentFlavors[0], flavor); + // Confirm we set the clipboard + test.assertEqual(clip.get(), contents); + // Confirm we can get the clipboard using the flavor + test.assertEqual(clip.get(flavor), contents); + // Confirm we can still get the clipboard using the full flavor + test.assertEqual(clip.get(fullFlavor), contents); +}; + +// Test the slightly less common case where we specify the flavor +exports.testWithFlavor = function(test) { + var contents = "<b>hello there</b>"; + var contentsText = "hello there"; + var flavor = "html"; + var fullFlavor = "text/html"; + var unicodeFlavor = "text"; + var unicodeFullFlavor = "text/unicode"; + var clip = require("sdk/clipboard"); + test.assert(clip.set(contents, flavor)); + test.assertEqual(clip.currentFlavors[0], unicodeFlavor); + test.assertEqual(clip.currentFlavors[1], flavor); + test.assertEqual(clip.get(), contentsText); + test.assertEqual(clip.get(flavor), contents); + test.assertEqual(clip.get(fullFlavor), contents); + test.assertEqual(clip.get(unicodeFlavor), contentsText); + test.assertEqual(clip.get(unicodeFullFlavor), contentsText); +}; + +// Test that the typical case still works when we specify the flavor to set +exports.testWithRedundantFlavor = function(test) { + var contents = "<b>hello there</b>"; + var flavor = "text"; + var fullFlavor = "text/unicode"; + var clip = require("sdk/clipboard"); + test.assert(clip.set(contents, flavor)); + test.assertEqual(clip.currentFlavors[0], flavor); + test.assertEqual(clip.get(), contents); + test.assertEqual(clip.get(flavor), contents); + test.assertEqual(clip.get(fullFlavor), contents); +}; + +exports.testNotInFlavor = function(test) { + var contents = "hello there"; + var flavor = "html"; + var clip = require("sdk/clipboard"); + test.assert(clip.set(contents)); + // If there's nothing on the clipboard with this flavor, should return null + test.assertEqual(clip.get(flavor), null); +}; + +exports.testSetImage = function(test) { + var clip = require("sdk/clipboard"); + var flavor = "image"; + var fullFlavor = "image/png"; + + test.assert(clip.set(base64png, flavor), "clipboard set"); + test.assertEqual(clip.currentFlavors[0], flavor, "flavor is set"); +}; + +exports.testGetImage = function(test) { + test.waitUntilDone(); + + var clip = require("sdk/clipboard"); + + clip.set(base64png, "image"); + + var contents = clip.get(); + + comparePixelImages(base64png, contents, function (areEquals) { + test.assert(areEquals, + "Image gets from clipboard equals to image sets to the clipboard"); + + test.done(); + }); +} + +exports.testSetImageTypeNotSupported = function(test) { + var clip = require("sdk/clipboard"); + var flavor = "image"; + + test.assertRaises(function () { + clip.set(base64jpeg, flavor); + }, "Invalid flavor for image/jpeg"); + +}; + +// Notice that `imageTools.decodeImageData`, used by `clipboard.set` method for +// images, write directly to the javascript console the error in case the image +// is corrupt, even if the error is catched. +// +// See: http://mxr.mozilla.org/mozilla-central/source/image/src/Decoder.cpp#136 +exports.testSetImageTypeWrongData = function(test) { + var clip = require("sdk/clipboard"); + var flavor = "image"; + + var wrongPNG = "data:image/png" + base64jpeg.substr(15); + + test.assertRaises(function () { + clip.set(wrongPNG, flavor); + }, "Unable to decode data given in a valid image."); +}; + +// TODO: Test error cases. diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-collection.js b/tools/addon-sdk-1.12/test/test-collection.js index f3e5476..cd533bf 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-collection.js +++ b/tools/addon-sdk-1.12/test/test-collection.js @@ -4,7 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const collection = require("collection"); +const collection = require("sdk/util/collection"); exports.testAddRemove = function (test) { let coll = new collection.Collection(); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-commonjs-test-adapter.js b/tools/addon-sdk-1.12/test/test-commonjs-test-adapter.js index 936bea9..936bea9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-commonjs-test-adapter.js +++ b/tools/addon-sdk-1.12/test/test-commonjs-test-adapter.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-loader.js b/tools/addon-sdk-1.12/test/test-content-loader.js index e19e316..1804ac9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-loader.js +++ b/tools/addon-sdk-1.12/test/test-content-loader.js @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { Loader } = require('content/loader'); -const self = require("self"); +const { Loader } = require('sdk/content/loader'); +const self = require("sdk/self"); exports['test:contentURL'] = function(test) { let loader = Loader(), diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-proxy.js b/tools/addon-sdk-1.12/test/test-content-proxy.js index f7f1235..b447df9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-proxy.js +++ b/tools/addon-sdk-1.12/test/test-content-proxy.js @@ -2,10 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const hiddenFrames = require("hidden-frame"); -const xulApp = require("xul-app"); +const hiddenFrames = require("sdk/frame/hidden-frame"); +const xulApp = require("sdk/system/xul-app"); -const { Loader } = require('./helpers'); +const USE_JS_PROXIES = !xulApp.versionInRange(xulApp.platformVersion, + "17.0a2", "*"); + +const { Loader } = require('sdk/test/loader'); /* * Utility function that allow to easily run a proxy test with a clean @@ -15,7 +18,7 @@ function createProxyTest(html, callback) { return function (test) { test.waitUntilDone(); - let url = 'data:text/html,' + encodeURI(html); + let url = 'data:text/html;charset=utf-8,' + encodeURI(html); let hiddenFrame = hiddenFrames.add(hiddenFrames.HiddenFrame({ onReady: function () { @@ -58,10 +61,10 @@ function createWorker(test, xrayWindow, contentScript, done) { // unlock key `PRIVATE_KEY`. This key should not be used anywhere else. // See `PRIVATE_KEY` definition in worker.js let loader = Loader(module); - let Worker = loader.require("api-utils/content/worker").Worker; - let key = loader.sandbox("api-utils/content/worker").PRIVATE_KEY; + let Worker = loader.require("sdk/content/worker").Worker; + let key = loader.sandbox("sdk/content/worker").PRIVATE_KEY; let worker = Worker({ - exposeUnlockKey : key, + exposeUnlockKey : USE_JS_PROXIES ? key : null, window: xrayWindow, contentScript: [ 'new ' + function () { @@ -129,20 +132,21 @@ exports.testCreateProxyTestWithEvents = createProxyTest("", function (helper, te }); -// Verify that the attribute `exposeUnlockKey`, that allow this test -// to identify proxies, works correctly. -// See `PRIVATE_KEY` definition in worker.js -exports.testKeyAccess = createProxyTest("", function(helper) { - - helper.createWorker( - 'new ' + function ContentScriptScope() { - assert("UNWRAP_ACCESS_KEY" in window, "have access to `UNWRAP_ACCESS_KEY`"); - done(); - } - ); +if (USE_JS_PROXIES) { + // Verify that the attribute `exposeUnlockKey`, that allow this test + // to identify proxies, works correctly. + // See `PRIVATE_KEY` definition in worker.js + exports.testKeyAccess = createProxyTest("", function(helper) { -}); + helper.createWorker( + 'new ' + function ContentScriptScope() { + assert("UNWRAP_ACCESS_KEY" in window, "have access to `UNWRAP_ACCESS_KEY`"); + done(); + } + ); + }); +} // Bug 714778: There was some issue around `toString` functions // that ended up being shared between content scripts @@ -152,10 +156,14 @@ exports.testSharedToStringProxies = createProxyTest("", function(helper) { 'new ' + function ContentScriptScope() { // We ensure that `toString` can't be modified so that nothing could // leak to/from the document and between content scripts + // It only applies to JS proxies, there isn't any such issue with xrays. //document.location.toString = function foo() {}; document.location.toString.foo = "bar"; - assert(!("foo" in document.location.toString), "document.location.toString can't be modified"); - assert(document.location.toString() == "data:text/html,", + if ('UNWRAP_ACCESS_KEY' in window) + assert(!("foo" in document.location.toString), "document.location.toString can't be modified"); + else + assert("foo" in document.location.toString, "document.location.toString can be modified"); + assert(document.location.toString() == "data:text/html;charset=utf-8,", "First document.location.toString()"); self.postMessage("next"); } @@ -165,7 +173,7 @@ exports.testSharedToStringProxies = createProxyTest("", function(helper) { 'new ' + function ContentScriptScope2() { assert(!("foo" in document.location.toString), "document.location.toString is different for each content script"); - assert(document.location.toString() == "data:text/html,", + assert(document.location.toString() == "data:text/html;charset=utf-8,", "Second document.location.toString()"); done(); } @@ -175,17 +183,25 @@ exports.testSharedToStringProxies = createProxyTest("", function(helper) { // Ensure that postMessage is working correctly across documents with an iframe -let html = '<iframe id="iframe" name="test" src="data:text/html," />'; +let html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />'; exports.testPostMessage = createProxyTest(html, function (helper, test) { let ifWindow = helper.xrayWindow.document.getElementById("iframe").contentWindow; // Listen without proxies, to check that it will work in regular case // simulate listening from a web document. ifWindow.addEventListener("message", function listener(event) { - //if (event.source.wrappedJSObject == helper.rawWindow) return; ifWindow.removeEventListener("message", listener, false); // As we are in system principal, event is an XrayWrapper - test.assertEqual(event.source, ifWindow, - "event.source is the iframe window"); + if (USE_JS_PROXIES) { + test.assertEqual(event.source, ifWindow, + "event.source is the iframe window"); + } + else { + // JS proxies had different behavior than xrays, xrays use current + // compartments when calling postMessage method. Whereas js proxies + // was using postMessage method compartment, not the caller one. + test.assertEqual(event.source, helper.xrayWindow, + "event.source is the top window"); + } test.assertEqual(event.origin, "null", "origin is null"); test.assertEqual(event.data, "{\"foo\":\"bar\\n \\\"escaped\\\".\"}", @@ -219,7 +235,8 @@ exports.testObjectListener = createProxyTest(html, function (helper) { assert(this === myClickListener, "`this` is the original object"); assert(!this.called, "called only once"); this.called = true; - assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped"); + if ('UNWRAP_ACCESS_KEY' in window) + assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped"); assert(event.target, input, "event.target is the wrapped window"); done(); } @@ -246,7 +263,8 @@ exports.testObjectListener2 = createProxyTest("", function (helper) { assert(this == myMessageListener, "`this` is the original object"); assert(!this.called, "called only once"); this.called = true; - assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped"); + if ('UNWRAP_ACCESS_KEY' in window) + assert(event.valueOf() !== event.valueOf(UNWRAP_ACCESS_KEY), "event is wrapped"); assert(event.target == document.defaultView, "event.target is the wrapped window"); assert(event.source == document.defaultView, "event.source is the wrapped window"); assert(event.origin == "null", "origin is null"); @@ -264,6 +282,8 @@ exports.testObjectListener2 = createProxyTest("", function (helper) { let html = '<input id="input" type="text" /><input id="input3" type="checkbox" />' + '<input id="input2" type="checkbox" />'; + +/* Disable test to keep tree green until Bug 756214 is fixed. exports.testStringOverload = createProxyTest(html, function (helper, test) { // Proxy - toString error let originalString = "string"; @@ -299,6 +319,7 @@ exports.testStringOverload = createProxyTest(html, function (helper, test) { } ); }); +*/ exports.testMozMatchedSelector = createProxyTest("", function (helper) { helper.createWorker( @@ -434,7 +455,8 @@ exports.testAutoUnwrapCustomAttributes = createProxyTest("", function (helper) { // Setting a custom object to a proxy attribute is not wrapped when we get it afterward let object = {custom: true, enumerable: false}; body.customAttribute = object; - assert(body.customAttribute.valueOf() === body.customAttribute.valueOf(UNWRAP_ACCESS_KEY), "custom JS attributes are not wrapped"); + if ('UNWRAP_ACCESS_KEY' in window) + assert(body.customAttribute.valueOf() === body.customAttribute.valueOf(UNWRAP_ACCESS_KEY), "custom JS attributes are not wrapped"); assert(object === body.customAttribute, "custom JS attributes are not wrapped"); done(); } @@ -465,7 +487,8 @@ exports.testHighlightToStringBehavior = createProxyTest("", function (helper, te test.assertMatches(Object.prototype.toString.call(f), /\[object Function.*\]/, "functions are functions 1"); // This is how jquery call toString: test.assertMatches(helper.rawWindow.Object.prototype.toString.call(""), /\[object String.*\]/, "strings are strings"); - test.assertMatches(helper.rawWindow.Object.prototype.toString.call({}), /\[object Object.*\]/, "objects are objects"); + let o = {__exposedProps__:{}}; + test.assertMatches(helper.rawWindow.Object.prototype.toString.call(o), /\[object Object.*\]/, "objects are objects"); // Make sure to pass a function from the same compartments // or toString will return [object Object] on FF8+ @@ -504,7 +527,7 @@ exports.testDocumentTagName = createProxyTest("", function (helper) { }); -let html = '<iframe id="iframe" name="test" src="data:text/html," />'; +let html = '<iframe id="iframe" name="test" src="data:text/html;charset=utf-8," />'; exports.testWindowFrames = createProxyTest(html, function (helper) { helper.createWorker( @@ -559,7 +582,14 @@ exports.testCollections2 = createProxyTest(html, function (helper) { for(let i in body.childNodes) { count++; } - assert(count == 3, "body.childNodes is iterable"); + // JS proxies were broken, we can iterate over some other items: + // length, item and iterator + let expectedCount; + if ('UNWRAP_ACCESS_KEY' in window) + expectedCount = 3; + else + expectedCount = 6; + assert(count == expectedCount, "body.childNodes is iterable"); done(); } ); @@ -568,15 +598,29 @@ exports.testCollections2 = createProxyTest(html, function (helper) { exports.testValueOf = createProxyTest("", function (helper) { - helper.createWorker( - 'new ' + function ContentScriptScope() { - // Check internal use of valueOf() - assert(window.valueOf().toString().match(/\[object Window.*\]/), "proxy.valueOf() returns the wrapped version"); - assert(window.valueOf({}).toString().match(/\[object Window.*\]/), "proxy.valueOf({}) returns the wrapped version"); - assert(window.valueOf(UNWRAP_ACCESS_KEY).toString().match(/\[object XrayWrapper \[object Window.*\].*\]/), "proxy.valueOf(UNWRAP_ACCESS_KEY) returns the unwrapped version"); - done(); - } - ); + if (USE_JS_PROXIES) { + helper.createWorker( + 'new ' + function ContentScriptScope() { + // Check internal use of valueOf() for JS proxies API + assert(window.valueOf().toString().match(/\[object Window.*\]/), + "proxy.valueOf() returns the wrapped version"); + assert(window.valueOf({}).toString().match(/\[object Window.*\]/), + "proxy.valueOf({}) returns the wrapped version"); + done(); + } + ); + } + else { + helper.createWorker( + 'new ' + function ContentScriptScope() { + // Bug 787013: Until this bug is fixed, we are missing some methods + // on JS objects that comes from global `Object` object + assert(!('valueOf' in window), "valueOf is missing"); + assert(!('toLocateString' in window), "toLocaleString is missing"); + done(); + } + ); + } }); @@ -594,28 +638,29 @@ exports.testXMLHttpRequest = createProxyTest("", function (helper) { }); exports.testXPathResult = createProxyTest("", function (helper, test) { - - // Check XPathResult bug with constants being undefined on - // XPCNativeWrapper - let value = helper.rawWindow.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE; + const XPathResultTypes = ["ANY_TYPE", + "NUMBER_TYPE", "STRING_TYPE", "BOOLEAN_TYPE", + "UNORDERED_NODE_ITERATOR_TYPE", + "ORDERED_NODE_ITERATOR_TYPE", + "UNORDERED_NODE_SNAPSHOT_TYPE", + "ORDERED_NODE_SNAPSHOT_TYPE", + "ANY_UNORDERED_NODE_TYPE", + "FIRST_ORDERED_NODE_TYPE"]; + + // Check XPathResult bug with constants being undefined on XPCNativeWrapper let xpcXPathResult = helper.xrayWindow.XPathResult; - test.assertEqual(xpcXPathResult.wrappedJSObject. - UNORDERED_NODE_SNAPSHOT_TYPE, - value, - "XPathResult's constants are valid on unwrapped node"); - if (xulApp.versionInRange(xulApp.platformVersion, "10.0a1", "*")) { - test.assertEqual(xpcXPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 6, + XPathResultTypes.forEach(function(type, i) { + test.assertEqual(xpcXPathResult.wrappedJSObject[type], + helper.rawWindow.XPathResult[type], + "XPathResult's constants are valid on unwrapped node"); + + test.assertEqual(xpcXPathResult[type], i, "XPathResult's constants are defined on " + "XPCNativeWrapper (platform bug #)"); - } - else { - test.assertEqual(xpcXPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, - undefined, - "XPathResult's constants are undefined on " + - "XPCNativeWrapper (platform bug #665279)"); - } + }); + let value = helper.rawWindow.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE; let worker = helper.createWorker( 'new ' + function ContentScriptScope() { self.port.on("value", function (value) { @@ -627,7 +672,6 @@ exports.testXPathResult = createProxyTest("", function (helper, test) { } ); worker.port.emit("value", value); - }); exports.testPrototypeInheritance = createProxyTest("", function (helper) { @@ -649,8 +693,12 @@ exports.testPrototypeInheritance = createProxyTest("", function (helper) { exports.testFunctions = createProxyTest("", function (helper) { - helper.rawWindow.callFunction = function (f) f(); - helper.rawWindow.isEqual = function (a, b) a == b; + helper.rawWindow.callFunction = function callFunction(f) f(); + helper.rawWindow.isEqual = function isEqual(a, b) a == b; + // bug 784116: workaround in order to allow proxy code to cache proxies on + // these functions: + helper.rawWindow.callFunction.__exposedProps__ = {__proxy: 'rw'}; + helper.rawWindow.isEqual.__exposedProps__ = {__proxy: 'rw'}; helper.createWorker( 'new ' + function ContentScriptScope() { @@ -691,7 +739,8 @@ exports.testListeners = createProxyTest(html, function (helper) { addEventListenerCalled = true; assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals"); - assert("__isWrappedProxy" in event.target, "event object is a proxy"); + if ('UNWRAP_ACCESS_KEY' in window) + assert("__isWrappedProxy" in event.target, "event object is a proxy"); let input2 = document.getElementById("input2"); @@ -702,7 +751,8 @@ exports.testListeners = createProxyTest(html, function (helper) { expandoCalled = true; assert(!event.target.ownerDocument.defaultView.documentGlobal, "event object is still wrapped and doesn't expose document globals"); - assert("__isWrappedProxy" in event.target, "event object is a proxy"); + if ('UNWRAP_ACCESS_KEY' in window) + assert("__isWrappedProxy" in event.target, "event object is a proxy"); setTimeout(function () { input.click(); @@ -747,31 +797,47 @@ exports.testGlobalScope = createProxyTest("", function (helper) { }); -// Bug 671016: Typed arrays should not be proxified -exports.testTypedArrays = createProxyTest("", function (helper) { +if (USE_JS_PROXIES) { + // Bug 671016: Typed arrays should not be proxified + exports.testTypedArraysX = createProxyTest("", function (helper) { - helper.createWorker( - 'new ' + function ContentScriptScope() { - let canvas = document.createElement("canvas"); - let context = canvas.getContext("2d"); - let imageData = context.getImageData(0,0, 1, 1); - let unwrappedData = imageData.valueOf(UNWRAP_ACCESS_KEY).data; - let data = imageData.data; - assert(unwrappedData === data, "Typed array isn't proxified") - done(); - } - ); + helper.createWorker( + 'new ' + function ContentScriptScope() { + let canvas = document.createElement("canvas"); + let context = canvas.getContext("2d"); + let imageData = context.getImageData(0,0, 1, 1); + let unwrappedData; + if ('UNWRAP_ACCESS_KEY' in window) + unwrappedData = imageData.valueOf(UNWRAP_ACCESS_KEY).data + else + unwrappedData = imageData.wrappedJSObject.data; + let data = imageData.data; + dump(unwrappedData+" === "+data+"\n"); + assert(unwrappedData === data, "Typed array isn't proxified") + done(); + } + ); -}); + }); +} // Bug 715755: proxy code throw an exception on COW // Create an http server in order to simulate real cross domain documents exports.testCrossDomainIframe = createProxyTest("", function (helper) { let serverPort = 8099; - let server = require("httpd").startServerAsync(serverPort); + let server = require("sdk/test/httpd").startServerAsync(serverPort); server.registerPathHandler("/", function handle(request, response) { - // Returns an empty webpage - response.write(""); + // Returns the webpage that receive a message and forward it back to its + // parent document by appending ' world'. + let content = "<html><head><meta charset='utf-8'></head>\n"; + content += "<script>\n"; + content += " window.addEventListener('message', function (event) {\n"; + content += " parent.postMessage(event.data + ' world', '*');\n"; + content += " }, true);\n"; + content += "</script>\n"; + content += "<body></body>\n"; + content += "</html>\n"; + response.write(content); }); let worker = helper.createWorker( @@ -783,14 +849,17 @@ exports.testCrossDomainIframe = createProxyTest("", function (helper) { iframe.addEventListener("load", function onload() { iframe.removeEventListener("load", onload, true); try { - // Try accessing iframe's content that is made of COW wrappers - // Take care of debug builds that add object address after `Window` - assert(String(iframe.contentWindow).match(/\[object Window.*\]/), - "COW works properly"); + // Try to communicate with iframe's content + window.addEventListener("message", function onmessage(event) { + window.removeEventListener("message", onmessage, true); + + assert(event.data == "hello world", "COW works properly"); + self.port.emit("end"); + }, true); + iframe.contentWindow.postMessage("hello", "*"); } catch(e) { assert(false, "COW fails : "+e.message); } - self.port.emit("end"); }, true); iframe.setAttribute("src", url); document.body.appendChild(iframe); @@ -805,3 +874,42 @@ exports.testCrossDomainIframe = createProxyTest("", function (helper) { worker.postMessage("http://localhost:" + serverPort + "/"); }); + +// Bug 769006: Ensure that MutationObserver works fine with proxies +let html = '<a href="foo">link</a>'; +exports.testMutationObvserver = createProxyTest(html, function (helper) { + + helper.createWorker( + 'new ' + function ContentScriptScope() { + if (typeof MutationObserver == "undefined") { + assert(true, "No MutationObserver for this FF version"); + done(); + return; + } + let link = document.getElementsByTagName("a")[0]; + + // Register a Mutation observer + let obs = new MutationObserver(function(mutations){ + // Ensure that mutation data are valid + assert(mutations.length == 1, "only one attribute mutation"); + let mutation = mutations[0]; + assert(mutation.type == "attributes", "check `type`"); + assert(mutation.target == link, "check `target`"); + assert(mutation.attributeName == "href", "check `attributeName`"); + assert(mutation.oldValue == "foo", "check `oldValue`"); + obs.disconnect(); + done(); + }); + obs.observe(document, { + subtree: true, + attributes: true, + attributeOldValue: true, + attributeFilter: ["href"] + }); + + // Modify the DOM + link.setAttribute("href", "bar"); + } + ); + +}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-symbiont.js b/tools/addon-sdk-1.12/test/test-content-symbiont.js index 526af05..470cf7e 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-symbiont.js +++ b/tools/addon-sdk-1.12/test/test-content-symbiont.js @@ -5,8 +5,8 @@ "use strict"; const { Cc, Ci } = require('chrome'); -const { Symbiont } = require('content/symbiont'); -const self = require("self"); +const { Symbiont } = require('sdk/content/symbiont'); +const self = require("sdk/self"); function makeWindow() { let content = @@ -15,7 +15,7 @@ function makeWindow() { 'xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">' + '<iframe id="content" type="content"/>' + '</window>'; - var url = "data:application/vnd.mozilla.xul+xml," + + var url = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURIComponent(content); var features = ["chrome", "width=10", "height=10"]; @@ -25,50 +25,44 @@ function makeWindow() { } exports['test:constructing symbiont && validating API'] = function(test) { - let window = makeWindow(); - window.addEventListener("load", function onLoad() { - window.removeEventListener("load", onLoad, false); - let frame = window.document.getElementById("content"); - // TODO: support arrays ?? - let contentScripts = ["1;", "2;"]; - let contentSymbiont = Symbiont({ - frame: frame, - contentScriptFile: self.data.url("test-content-symbiont.js"), - contentScript: contentScripts, - contentScriptWhen: "start" - }); - - test.assertEqual( - self.data.url("test-content-symbiont.js"), - contentSymbiont.contentScriptFile, - "There is one contentScriptFile, as specified in options." - ); - test.assertEqual( - contentScripts.length, - contentSymbiont.contentScript.length, - "There are two contentScripts, as specified in options." - ); - test.assertEqual( - contentScripts[0], - contentSymbiont.contentScript[0], - "There are two contentScripts, as specified in options." - ); - test.assertEqual( - contentScripts[1], - contentSymbiont.contentScript[1], - "There are two contentScripts, as specified in options." - ) - test.assertEqual( - contentSymbiont.contentScriptWhen, - "start", - "contentScriptWhen is as specified in options." - ); + let contentScript = ["1;", "2;"]; + let contentScriptFile = self.data.url("test-content-symbiont.js"); + + // We can avoid passing a `frame` argument. Symbiont will create one + // by using HiddenFrame module + let contentSymbiont = Symbiont({ + contentScriptFile: contentScriptFile, + contentScript: contentScript, + contentScriptWhen: "start" + }); - test.done(); - window.close(); - frame.setAttribute("src", "data:text/html,<html><body></body></html>"); - }, false); - test.waitUntilDone(); + test.assertEqual( + contentScriptFile, + contentSymbiont.contentScriptFile, + "There is one contentScriptFile, as specified in options." + ); + test.assertEqual( + contentScript.length, + contentSymbiont.contentScript.length, + "There are two contentScripts, as specified in options." + ); + test.assertEqual( + contentScript[0], + contentSymbiont.contentScript[0], + "There are two contentScripts, as specified in options." + ); + test.assertEqual( + contentScript[1], + contentSymbiont.contentScript[1], + "There are two contentScripts, as specified in options." + ) + test.assertEqual( + contentSymbiont.contentScriptWhen, + "start", + "contentScriptWhen is as specified in options." + ); + + contentSymbiont.destroy(); }; exports["test:communication with worker global scope"] = function(test) { @@ -109,7 +103,7 @@ exports["test:communication with worker global scope"] = function(test) { onMessage: onMessage1 }); - frame.setAttribute("src", "data:text/html,<html><body></body></html>"); + frame.setAttribute("src", "data:text/html;charset=utf-8,<html><body></body></html>"); }, false); test.waitUntilDone(); }; @@ -141,7 +135,7 @@ exports['test:pageWorker'] = function(test) { exports["test:document element present on 'start'"] = function(test) { test.waitUntilDone(); - let xulApp = require("xul-app"); + let xulApp = require("sdk/system/xul-app"); let worker = Symbiont({ contentURL: "about:buildconfig", contentScript: "self.postMessage(!!document.documentElement)", @@ -160,7 +154,7 @@ exports["test:direct communication with trusted document"] = function(test) { test.waitUntilDone(); let worker = Symbiont({ - contentURL: require("self").data.url("test-trusted-document.html") + contentURL: require("sdk/self").data.url("test-trusted-document.html") }); worker.port.on('document-to-addon', function (arg) { @@ -175,7 +169,7 @@ exports["test:`addon` is not available when a content script is set"] = function test.waitUntilDone(); let worker = Symbiont({ - contentURL: require("self").data.url("test-trusted-document.html"), + contentURL: require("sdk/self").data.url("test-trusted-document.html"), contentScript: "new " + function ContentScriptScope() { self.port.emit("cs-to-addon", "addon" in unsafeWindow); } diff --git a/tools/addon-sdk-1.12/test/test-content-worker.js b/tools/addon-sdk-1.12/test/test-content-worker.js new file mode 100644 index 0000000..f1c8983 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-content-worker.js @@ -0,0 +1,657 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use stirct"; + +const { Cc, Ci } = require("chrome"); +const { setTimeout } = require("sdk/timers"); +const { Loader, Require, override } = require("sdk/test/loader"); +const { Worker } = require("sdk/content/worker"); + +const DEFAULT_CONTENT_URL = "data:text/html;charset=utf-8,foo"; + +function makeWindow(contentURL) { + let content = + "<?xml version=\"1.0\"?>" + + "<window " + + "xmlns=\"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul\">" + + "<script>var documentValue=true;</script>" + + "</window>"; + var url = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + + encodeURIComponent(content); + var features = ["chrome", "width=10", "height=10"]; + + return Cc["@mozilla.org/embedcomp/window-watcher;1"]. + getService(Ci.nsIWindowWatcher). + openWindow(null, url, null, features.join(","), null); +} + +// Listen for only first one occurence of DOM event +function listenOnce(node, eventName, callback) { + node.addEventListener(eventName, function onevent(event) { + node.removeEventListener(eventName, onevent, true); + callback(node); + }, true); +} + +// Load a given url in a given browser and fires the callback when it is loaded +function loadAndWait(browser, url, callback) { + listenOnce(browser, "load", callback); + // We have to wait before calling `loadURI` otherwise, if we call + // `loadAndWait` during browser load event, the history will be broken + setTimeout(function () { + browser.loadURI(url); + }, 0); +} + +// Returns a test function that will automatically open a new chrome window +// with a <browser> element loaded on a given content URL +// The callback receive 3 arguments: +// - test: reference to the jetpack test object +// - browser: a reference to the <browser> xul node +// - done: a callback to call when test is over +function WorkerTest(url, callback) { + return function testFunction(test) { + test.waitUntilDone(); + let chromeWindow = makeWindow(); + chromeWindow.addEventListener("load", function onload() { + chromeWindow.removeEventListener("load", onload, true); + let browser = chromeWindow.document.createElement("browser"); + browser.setAttribute("type", "content"); + chromeWindow.document.documentElement.appendChild(browser); + // Wait for about:blank load event ... + listenOnce(browser, "load", function onAboutBlankLoad() { + // ... before loading the expected doc and waiting for its load event + loadAndWait(browser, url, function onDocumentLoaded() { + callback(test, browser, function onTestDone() { + chromeWindow.close(); + test.done(); + }); + }); + }); + }, true); + }; +} + +exports["test:sample"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + test.assertNotEqual(browser.contentWindow.location.href, "about:blank", + "window is now on the right document"); + + let window = browser.contentWindow + let worker = Worker({ + window: window, + contentScript: "new " + function WorkerScope() { + // window is accessible + let myLocation = window.location.toString(); + self.on("message", function(data) { + if (data == "hi!") + self.postMessage("bye!"); + }); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + test.assertEqual("bye!", msg); + test.assertEqual(worker.url, window.location.href, + "worker.url still works"); + done(); + } + }); + + test.assertEqual(worker.url, window.location.href, + "worker.url works"); + worker.postMessage("hi!"); + } +); + +exports["test:emit"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + // Validate self.on and self.emit + self.port.on("addon-to-content", function (data) { + self.port.emit("content-to-addon", data); + }); + + // Check for global pollution + //if (typeof on != "undefined") + // self.postMessage("`on` is in globals"); + if (typeof once != "undefined") + self.postMessage("`once` is in globals"); + if (typeof emit != "undefined") + self.postMessage("`emit` is in globals"); + + }, + onMessage: function(msg) { + test.fail("Got an unexpected message : "+msg); + } + }); + + // Validate worker.port + worker.port.on("content-to-addon", function (data) { + test.assertEqual(data, "event data"); + done(); + }); + worker.port.emit("addon-to-content", "event data"); + } +); + +exports["test:emit hack message"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + // Validate self.port + self.port.on("message", function (data) { + self.port.emit("message", data); + }); + // We should not receive message on self, but only on self.port + self.on("message", function (data) { + self.postMessage("message", data); + }); + }, + onError: function(e) { + test.fail("Got exception: "+e); + } + }); + + worker.port.on("message", function (data) { + test.assertEqual(data, "event data"); + done(); + }); + worker.on("message", function (data) { + test.fail("Got an unexpected message : "+msg); + }); + worker.port.emit("message", "event data"); + } +); + +exports["test:n-arguments emit"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + // Validate self.on and self.emit + self.port.on("addon-to-content", function (a1, a2, a3) { + self.port.emit("content-to-addon", a1, a2, a3); + }); + } + }); + + // Validate worker.port + worker.port.on("content-to-addon", function (arg1, arg2, arg3) { + test.assertEqual(arg1, "first argument"); + test.assertEqual(arg2, "second"); + test.assertEqual(arg3, "third"); + done(); + }); + worker.port.emit("addon-to-content", "first argument", "second", "third"); + } +); + +exports["test:post-json-values-only"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + self.on("message", function (message) { + self.postMessage([ message.fun === undefined, + typeof message.w, + message.w && "port" in message.w, + message.w.url, + Array.isArray(message.array), + JSON.stringify(message.array)]); + }); + } + }); + + // Validate worker.onMessage + let array = [1, 2, 3]; + worker.on("message", function (message) { + test.assert(message[0], "function becomes undefined"); + test.assertEqual(message[1], "object", "object stays object"); + test.assert(message[2], "object's attributes are enumerable"); + test.assertEqual(message[3], DEFAULT_CONTENT_URL, + "jsonable attributes are accessible"); + // See bug 714891, Arrays may be broken over compartements: + test.assert(message[4], "Array keeps being an array"); + test.assertEqual(message[5], JSON.stringify(array), + "Array is correctly serialized"); + done(); + }); + worker.postMessage({ fun: function () {}, w: worker, array: array }); + } +); + +exports["test:emit-json-values-only"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + // Validate self.on and self.emit + self.port.on("addon-to-content", function (fun, w, obj, array) { + self.port.emit("content-to-addon", [ + fun === null, + typeof w, + "port" in w, + w.url, + "fun" in obj, + Object.keys(obj.dom).length, + Array.isArray(array), + JSON.stringify(array) + ]); + }); + } + }); + + // Validate worker.port + let array = [1, 2, 3]; + worker.port.on("content-to-addon", function (result) { + test.assert(result[0], "functions become null"); + test.assertEqual(result[1], "object", "objects stay objects"); + test.assert(result[2], "object's attributes are enumerable"); + test.assertEqual(result[3], DEFAULT_CONTENT_URL, + "json attribute is accessible"); + test.assert(!result[4], "function as object attribute is removed"); + test.assertEqual(result[5], 0, "DOM nodes are converted into empty object"); + // See bug 714891, Arrays may be broken over compartments: + test.assert(result[6], "Array keeps being an array"); + test.assertEqual(result[7], JSON.stringify(array), + "Array is correctly serialized"); + done(); + }); + + let obj = { + fun: function () {}, + dom: browser.contentWindow.document.createElement("div") + }; + worker.port.emit("addon-to-content", function () {}, worker, obj, array); + } +); + +exports["test:content is wrapped"] = WorkerTest( + "data:text/html;charset=utf-8,<script>var documentValue=true;</script>", + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + self.postMessage(!window.documentValue); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + test.assert(msg, + "content script has a wrapped access to content document"); + done(); + } + }); + } +); + +exports["test:chrome is unwrapped"] = function(test) { + let window = makeWindow(); + test.waitUntilDone(); + + listenOnce(window, "load", function onload() { + + let worker = Worker({ + window: window, + contentScript: "new " + function WorkerScope() { + self.postMessage(window.documentValue); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + test.assert(msg, + "content script has an unwrapped access to chrome document"); + window.close(); + test.done(); + } + }); + + }); +} + +exports["test:nothing is leaked to content script"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + self.postMessage([ + "ContentWorker" in window, + "UNWRAP_ACCESS_KEY" in window, + "getProxyForObject" in window + ]); + }, + contentScriptWhen: "ready", + onMessage: function(list) { + test.assert(!list[0], "worker API contrustor isn't leaked"); + test.assert(!list[1], "Proxy API stuff isn't leaked 1/2"); + test.assert(!list[2], "Proxy API stuff isn't leaked 2/2"); + done(); + } + }); + } +); + +exports["test:ensure console.xxx works in cs"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + // Create a new module loader in order to be able to create a `console` + // module mockup: + let loader = Loader(module, { + console: { + log: hook.bind("log"), + info: hook.bind("info"), + warn: hook.bind("warn"), + error: hook.bind("error"), + debug: hook.bind("debug"), + exception: hook.bind("exception") + } + }); + + // Intercept all console method calls + let calls = []; + function hook(msg) { + test.assertEqual(this, msg, + "console.xxx(\"xxx\"), i.e. message is equal to the " + + "console method name we are calling"); + calls.push(msg); + } + + // Finally, create a worker that will call all console methods + let worker = loader.require("sdk/content/worker").Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + console.log("log"); + console.info("info"); + console.warn("warn"); + console.error("error"); + console.debug("debug"); + console.exception("exception"); + self.postMessage(); + }, + onMessage: function() { + // Ensure that console methods are called in the same execution order + test.assertEqual(JSON.stringify(calls), + JSON.stringify(["log", "info", "warn", "error", "debug", "exception"]), + "console has been called successfully, in the expected order"); + done(); + } + }); + } +); + + +exports["test:setTimeout can\"t be cancelled by content"] = WorkerTest( + "data:text/html;charset=utf-8,<script>var documentValue=true;</script>", + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + let id = setTimeout(function () { + self.postMessage("timeout"); + }, 100); + unsafeWindow.eval("clearTimeout("+id+");"); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + test.assert(msg, + "content didn't managed to cancel our setTimeout"); + done(); + } + }); + } +); + +exports["test:clearTimeout"] = WorkerTest( + "data:text/html;charset=utf-8,clear timeout", + function(test, browser, done) { + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + let id1 = setTimeout(function() { + self.postMessage("failed"); + }, 10); + let id2 = setTimeout(function() { + self.postMessage("done"); + }, 100); + clearTimeout(id1); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + if (msg === "failed") { + test.fail("failed to cancel timer"); + } else { + test.pass("timer cancelled"); + done(); + } + } + }); + } +); + +exports["test:clearInterval"] = WorkerTest( + "data:text/html;charset=utf-8,clear timeout", + function(test, browser, done) { + let called = 0; + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + let id = setInterval(function() { + self.postMessage("intreval") + clearInterval(id) + setTimeout(function() { + self.postMessage("done") + }, 100) + }, 10); + }, + contentScriptWhen: "ready", + onMessage: function(msg) { + if (msg === "intreval") { + called = called + 1; + if (called > 1) test.fail("failed to cancel timer"); + } else { + test.pass("interval cancelled"); + done(); + } + } + }); + } +) + +exports["test:setTimeout are unregistered on content unload"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let originalWindow = browser.contentWindow; + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + document.title = "ok"; + let i = 0; + setInterval(function () { + document.title = i++; + }, 10); + }, + contentScriptWhen: "ready" + }); + + // Change location so that content script is destroyed, + // and all setTimeout/setInterval should be unregistered. + // Wait some cycles in order to execute some intervals. + setTimeout(function () { + // Bug 689621: Wait for the new document load so that we are sure that + // previous document cancelled its intervals + let url2 = "data:text/html;charset=utf-8,<title>final</title>"; + loadAndWait(browser, url2, function onload() { + let titleAfterLoad = originalWindow.document.title; + // Wait additional cycles to verify that intervals are really cancelled + setTimeout(function () { + test.assertEqual(browser.contentDocument.title, "final", + "New document has not been modified"); + test.assertEqual(originalWindow.document.title, titleAfterLoad, + "Nor previous one"); + + done(); + }, 100); + }); + }, 100); + } +); + +exports['test:check window attribute in iframes'] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + // Create a first iframe and wait for its loading + let contentWin = browser.contentWindow; + let contentDoc = contentWin.document; + let iframe = contentDoc.createElement("iframe"); + contentDoc.body.appendChild(iframe); + + listenOnce(iframe, "load", function onload() { + + // Create a second iframe inside the first one and wait for its loading + let iframeDoc = iframe.contentWindow.document; + let subIframe = iframeDoc.createElement("iframe"); + iframeDoc.body.appendChild(subIframe); + + listenOnce(subIframe, "load", function onload() { + subIframe.removeEventListener("load", onload, true); + + // And finally create a worker against this second iframe + let worker = Worker({ + window: subIframe.contentWindow, + contentScript: 'new ' + function WorkerScope() { + self.postMessage([ + window.top !== window, + frameElement, + window.parent !== window, + top.location.href, + parent.location.href, + ]); + }, + onMessage: function(msg) { + test.assert(msg[0], "window.top != window"); + test.assert(msg[1], "window.frameElement is defined"); + test.assert(msg[2], "window.parent != window"); + test.assertEqual(msg[3], contentWin.location.href, + "top.location refers to the toplevel content doc"); + test.assertEqual(msg[4], iframe.contentWindow.location.href, + "parent.location refers to the first iframe doc"); + done(); + } + }); + + }); + subIframe.setAttribute("src", "data:text/html;charset=utf-8,bar"); + + }); + iframe.setAttribute("src", "data:text/html;charset=utf-8,foo"); + } +); + +exports['test:check window attribute in toplevel documents'] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + + let worker = Worker({ + window: browser.contentWindow, + contentScript: 'new ' + function WorkerScope() { + self.postMessage([ + window.top === window, + frameElement, + window.parent === window + ]); + }, + onMessage: function(msg) { + test.assert(msg[0], "window.top == window"); + test.assert(!msg[1], "window.frameElement is null"); + test.assert(msg[2], "window.parent == window"); + done(); + } + }); + } +); + +exports["test:check worker API with page history"] = WorkerTest( + DEFAULT_CONTENT_URL, + function(test, browser, done) { + let url2 = "data:text/html;charset=utf-8,bar"; + + loadAndWait(browser, url2, function () { + let worker = Worker({ + window: browser.contentWindow, + contentScript: "new " + function WorkerScope() { + // Just before the content script is disable, we register a timeout + // that will be disable until the page gets visible again + self.on("pagehide", function () { + setTimeout(function () { + self.postMessage("timeout restored"); + }, 0); + }); + }, + contentScriptWhen: "start" + }); + + // postMessage works correctly when the page is visible + worker.postMessage("ok"); + + // We have to wait before going back into history, + // otherwise `goBack` won't do anything. + setTimeout(function () { + browser.goBack(); + }, 0); + + // Wait for the document to be hidden + browser.addEventListener("pagehide", function onpagehide() { + browser.removeEventListener("pagehide", onpagehide, false); + // Now any event sent to this worker should throw + test.assertRaises( + function () { worker.postMessage("data"); }, + "The page is currently hidden and can no longer be used until it" + + " is visible again.", + "postMessage should throw when the page is hidden in history" + ); + test.assertRaises( + function () { worker.port.emit("event"); }, + "The page is currently hidden and can no longer be used until it" + + " is visible again.", + "port.emit should throw when the page is hidden in history" + ); + + // Display the page with attached content script back in order to resume + // its timeout and receive the expected message. + // We have to delay this in order to not break the history. + // We delay for a non-zero amount of time in order to ensure that we + // do not receive the message immediatly, so that the timeout is + // actually disabled + setTimeout(function () { + worker.on("message", function (data) { + test.assert(data, "timeout restored"); + done(); + }); + browser.goForward(); + }, 500); + + }, false); + }); + + } +); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.html b/tools/addon-sdk-1.12/test/test-context-menu.html index 4196d5f..b3f70a1 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.html +++ b/tools/addon-sdk-1.12/test/test-context-menu.html @@ -4,6 +4,7 @@ <html> <head> + <meta charset="UTF-8"> <title>Context menu test</title> </head> <body> @@ -37,7 +38,7 @@ </p> <p> - <iframe id="iframe" src="data:text/html,An iframe." + <iframe id="iframe" src="data:text/html;charset=utf-8,An iframe." width="200" height="100"> </iframe> </p> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.js b/tools/addon-sdk-1.12/test/test-context-menu.js index c398933..727028f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-context-menu.js +++ b/tools/addon-sdk-1.12/test/test-context-menu.js @@ -5,7 +5,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ let {Cc,Ci} = require("chrome"); -const { Loader } = require('./helpers'); +const { Loader } = require('sdk/test/loader'); +const timer = require("sdk/timers"); // These should match the same constants in the module. const ITEM_CLASS = "jetpack-context-menu-item"; @@ -454,7 +455,7 @@ exports.testContentScriptFile = function (test) { // But accept files from data folder let item = new loader.cm.Item({ label: "item", - contentScriptFile: require("self").data.url("test-context-menu.js") + contentScriptFile: require("sdk/self").data.url("test-context-menu.js") }); test.showMenu(null, function (popup) { @@ -473,12 +474,11 @@ exports.testContentContextArgs = function (test) { let item = new loader.cm.Item({ label: "item", contentScript: 'self.on("context", function (node) {' + - ' let Ci = Components.interfaces;' + - ' self.postMessage(node instanceof Ci.nsIDOMHTMLElement);' + + ' self.postMessage(node.tagName);' + ' return false;' + '});', - onMessage: function (isElt) { - test.assert(isElt, "node should be an HTML element"); + onMessage: function (tagName) { + test.assertEqual(tagName, "HTML", "node should be an HTML element"); if (++callbacks == 2) test.done(); } }); @@ -885,15 +885,15 @@ exports.testItemClick = function (test) { label: "item", data: "item data", contentScript: 'self.on("click", function (node, data) {' + - ' let Ci = Components.interfaces;' + + ' let Ci = Components["interfaces"];' + ' self.postMessage({' + - ' isElt: node instanceof Ci.nsIDOMHTMLElement,' + + ' tagName: node.tagName,' + ' data: data' + ' });' + '});', onMessage: function (data) { test.assertEqual(this, item, "`this` inside onMessage should be item"); - test.assert(data.isElt, "node should be an HTML element"); + test.assertEqual(data.tagName, "HTML", "node should be an HTML element"); test.assertEqual(data.data, item.data, "data should be item data"); test.done(); } @@ -931,15 +931,15 @@ exports.testMenuClick = function (test) { let topMenu = new loader.cm.Menu({ label: "top menu", contentScript: 'self.on("click", function (node, data) {' + - ' let Ci = Components.interfaces;' + + ' let Ci = Components["interfaces"];' + ' self.postMessage({' + - ' isAnchor: node instanceof Ci.nsIDOMHTMLAnchorElement,' + + ' tagName: node.tagName,' + ' data: data' + ' });' + '});', onMessage: function (data) { test.assertEqual(this, topMenu, "`this` inside top menu should be menu"); - test.assert(data.isAnchor, "Clicked node should be anchor"); + test.assertEqual(data.tagName, "A", "Clicked node should be anchor"); test.assertEqual(data.data, item.data, "Clicked item data should be correct"); test.done(); @@ -1213,6 +1213,33 @@ exports.testLoadWithOpenTab = function (test) { }); }; +// Bug 732716: Ensure that the node given in `click` event works fine +// (i.e. is correctly wrapped) +exports.testDrawImageOnClickNode = function (test) { + test = new TestHelper(test); + test.withTestDoc(function (window, doc) { + let loader = test.newLoader(); + let item = new loader.cm.Item({ + label: "item", + context: loader.cm.SelectorContext("img"), + contentScript: "new " + function() { + self.on("click", function (img, data) { + let ctx = document.createElement("canvas").getContext("2d"); + ctx.drawImage(img, 1, 1, 1, 1); + self.postMessage("done"); + }); + }, + onMessage: function (msg) { + if (msg === "done") + test.done(); + } + }); + test.showMenu(doc.getElementById("image"), function (popup) { + test.checkMenu([item], [], []); + test.getItemElt(popup, item).click(); + }); + }); +}; // Setting an item's label before the menu is ever shown should correctly change // its label and, if necessary, its order within the menu. @@ -1266,7 +1293,7 @@ exports.testSetLabelBeforeShowOverflow = function (test) { test = new TestHelper(test); let loader = test.newLoader(); - let prefs = loader.loader.require("preferences-service"); + let prefs = loader.loader.require("sdk/preferences/service"); prefs.set(OVERFLOW_THRESH_PREF, 0); let items = [ @@ -1291,7 +1318,7 @@ exports.testSetLabelAfterShowOverflow = function (test) { test = new TestHelper(test); let loader = test.newLoader(); - let prefs = loader.loader.require("preferences-service"); + let prefs = loader.loader.require("sdk/preferences/service"); prefs.set(OVERFLOW_THRESH_PREF, 0); let items = [ @@ -1559,14 +1586,14 @@ exports.testItemImage = function (test) { test = new TestHelper(test); let loader = test.newLoader(); - let imageURL = require("self").data.url("moz_favicon.ico"); + let imageURL = require("sdk/self").data.url("moz_favicon.ico"); let item = new loader.cm.Item({ label: "item", image: imageURL }); let menu = new loader.cm.Menu({ label: "menu", image: imageURL, items: [] }); test.showMenu(null, function (popup) { test.checkMenu([item, menu], [], []); - let imageURL2 = require("self").data.url("dummy.ico"); + let imageURL2 = require("sdk/self").data.url("dummy.ico"); item.image = imageURL2; menu.image = imageURL2; test.checkMenu([item, menu], [], []); @@ -1619,12 +1646,11 @@ exports.testMenuDestroy = function (test) { // NO TESTS BELOW THIS LINE! /////////////////////////////////////////////////// // Run only a dummy test if context-menu doesn't support the host app. -if (!require("xul-app").is("Firefox")) { - for (let [prop, val] in Iterator(exports)) - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; - exports.testAppNotSupported = function (test) { - test.pass("context-menu does not support this application."); +if (!require("sdk/system/xul-app").is("Firefox")) { + module.exports = { + testAppNotSupported: function (test) { + test.pass("context-menu does not support this application."); + } }; } @@ -1868,7 +1894,7 @@ TestHelper.prototype = { const self = this; node.addEventListener(event, function handler(evt) { node.removeEventListener(event, handler, useCapture); - require("timer").setTimeout(function () { + timer.setTimeout(function () { try { callback.call(self, evt); } @@ -1979,8 +2005,8 @@ TestHelper.prototype = { let loader = Loader(module); let wrapper = { loader: loader, - cm: loader.require("context-menu"), - globalScope: loader.sandbox("context-menu"), + cm: loader.require("sdk/context-menu"), + globalScope: loader.sandbox("sdk/context-menu"), unload: function () { loader.unload(); let idx = self.loaders.indexOf(wrapper); @@ -1997,7 +2023,7 @@ TestHelper.prototype = { shouldOverflow: function (presentItems) { return presentItems.length > (this.loaders.length ? - this.loaders[0].loader.require("preferences-service"). + this.loaders[0].loader.require("sdk/preferences/service"). get(OVERFLOW_THRESH_PREF, OVERFLOW_THRESH_DEFAULT) : OVERFLOW_THRESH_DEFAULT); }, diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-cortex.js b/tools/addon-sdk-1.12/test/test-cortex.js index 9f13f0e..ab3d194 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-cortex.js +++ b/tools/addon-sdk-1.12/test/test-cortex.js @@ -6,7 +6,7 @@ "use strict"; -var Cortex = require("cortex").Cortex; +var Cortex = require("sdk/deprecated/cortex").Cortex; exports["test property changes propagate"] = function (assert) { var source = { diff --git a/tools/addon-sdk-1.12/test/test-cuddlefish.js b/tools/addon-sdk-1.12/test/test-cuddlefish.js new file mode 100644 index 0000000..f160469 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-cuddlefish.js @@ -0,0 +1,49 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +const { Loader, Require, unload, override } = require('sdk/loader/cuddlefish'); +const packaging = require('@loader/options'); + +exports['test loader'] = function(assert) { + var prints = []; + function print(message) { + prints.push(message); + } + + let options = JSON.parse(JSON.stringify(packaging)); + + let loader = Loader(override(options, { + globals: { + print: print, + foo: 1 + } + })); + let require = Require(loader, module); + + var fixture = require('./loader/fixture'); + + assert.equal(fixture.foo, 1, 'custom globals must work.'); + assert.equal(fixture.bar, 2, 'exports are set'); + + assert.equal(prints[0], 'testing', 'global print must be injected.'); + + var unloadsCalled = ''; + + require("sdk/system/unload").when(function(reason) { + assert.equal(reason, 'test', 'unload reason is passed'); + unloadsCalled += 'a'; + }); + require('sdk/system/unload.js').when(function() { + unloadsCalled += 'b'; + }); + + unload(loader, 'test'); + + assert.equal(unloadsCalled, 'ba', + 'loader.unload() must call listeners in LIFO order.'); +}; + +require('test').run(exports); diff --git a/tools/addon-sdk-1.12/test/test-deprecate.js b/tools/addon-sdk-1.12/test/test-deprecate.js new file mode 100644 index 0000000..b1e0f32 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-deprecate.js @@ -0,0 +1,78 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const deprecate = require("sdk/util/deprecate"); +var { Loader } = require("sdk/test/loader"); + +function LoaderWithHookedConsole() { + let errors = []; + let loader = Loader(module, { + console: Object.create(console, { + error: { value: function(error) { + errors.push(error); + }} + }) + }); + + return { + loader: loader, + deprecate: loader.require("sdk/util/deprecate"), + errors: errors + } +} + +exports["test Deprecate Usage"] = function testDeprecateUsage(assert) { + let { loader, deprecate, errors } = LoaderWithHookedConsole(); + + function functionIsDeprecated() { + deprecate.deprecateUsage("foo"); + } + + functionIsDeprecated(); + + assert.equal(errors.length, 1, "only one error is dispatched"); + + let msg = errors[0]; + assert.ok(msg.indexOf("foo") !== -1, + "message contains the given message"); + assert.ok(msg.indexOf("functionIsDeprecated") !== -1, + "message contains name of the caller function"); + assert.ok(msg.indexOf(module.uri) !== -1, + "message contains URI of the caller module"); + + loader.unload(); +} + +exports["test Deprecate Function"] = function testDeprecateFunction(assert) { + let { loader, deprecate, errors } = LoaderWithHookedConsole(); + + let self = {}; + let arg1 = "foo"; + let arg2 = {}; + + function originalFunction(a1, a2) { + assert.equal(this, self); + assert.equal(a1, arg1); + assert.equal(a2, arg2); + }; + + let deprecateFunction = deprecate.deprecateFunction(originalFunction, + "bar"); + + deprecateFunction.call(self, arg1, arg2); + + assert.equal(errors.length, 1, + "only one error is dispatched"); + + let msg = errors[0]; + assert.ok(msg.indexOf("bar") !== -1, "message contains the given message"); + assert.ok(msg.indexOf("testDeprecateFunction") !== -1, + "message contains name of the caller function"); + assert.ok(msg.indexOf(module.uri) !== -1, + "message contains URI of the caller module"); + + loader.unload(); +} + +require("test").run(exports) diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-list.js b/tools/addon-sdk-1.12/test/test-deprecated-list.js index 67e67aa..4b5f598 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-list.js +++ b/tools/addon-sdk-1.12/test/test-deprecated-list.js @@ -28,7 +28,7 @@ function assertList(test, array, list) { } } -const { List } = require('api-utils/list'); +const { List } = require('sdk/deprecated/list'); exports['test:test for'] = function(test) { let fixture = List(3, 2, 1); @@ -50,17 +50,6 @@ exports['test:test for each'] = function(test) { } }; -exports['test: for each using Iterator'] = function(test) { - let fixture = new List(3, 2, 1); - - test.assertEqual(3, fixture.length, 'length is 3'); - let v = 3, k = 0; - for each (let [key, value] in Iterator(fixture)) { - test.assertEqual(k++, key, 'key should match'); - test.assertEqual(v--, value, 'value should match'); - } -}; - exports['test:test toString'] = function(test) { let fixture = List(3, 2, 1); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-dom.js b/tools/addon-sdk-1.12/test/test-dom.js index 52ab1c3..87c8372 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-dom.js +++ b/tools/addon-sdk-1.12/test/test-dom.js @@ -4,8 +4,8 @@ "use strict"; -const events = require("dom/events"); -const { activeBrowserWindow: { document } } = require("window-utils"); +const events = require("sdk/dom/events"); +const { activeBrowserWindow: { document } } = require("sdk/deprecated/window-utils"); const window = document.window; exports["test on / emit"] = function (assert, done) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-environment.js b/tools/addon-sdk-1.12/test/test-environment.js index 1d7e783..413997f 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-environment.js +++ b/tools/addon-sdk-1.12/test/test-environment.js @@ -4,7 +4,7 @@ 'use strict'; -const { env } = require('api-utils/environment'); +const { env } = require('sdk/system/environment'); const { Cc, Ci } = require('chrome'); const { get, set, exists } = Cc['@mozilla.org/process/environment;1']. getService(Ci.nsIEnvironment); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-errors.js b/tools/addon-sdk-1.12/test/test-errors.js index 64bb6c9..91ffd78 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-errors.js +++ b/tools/addon-sdk-1.12/test/test-errors.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var errors = require("errors"); +var errors = require("sdk/deprecated/errors"); exports.testCatchAndLog = function(test) { var caught = []; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-event-core.js b/tools/addon-sdk-1.12/test/test-event-core.js index 4b664ff..2d94137 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-event-core.js +++ b/tools/addon-sdk-1.12/test/test-event-core.js @@ -4,8 +4,8 @@ 'use strict'; -const { on, once, off, emit, count, amass } = require('api-utils/event/core'); -const { Loader } = require('./helpers'); +const { on, once, off, emit, count, amass } = require('sdk/event/core'); +const { Loader } = require('sdk/test/loader'); exports['test add a listener'] = function(assert) { let events = [ { name: 'event#1' }, 'event#2' ]; @@ -159,15 +159,14 @@ exports['test error handling'] = function(assert) { exports['test unhandled errors'] = function(assert) { let exceptions = []; - let loader = Loader(module); - let { emit, on } = loader.require('api-utils/event/core'); - Object.defineProperties(loader.sandbox('api-utils/event/core'), { - console: { value: { - exception: function(e) { - exceptions.push(e) - } - }} + let loader = Loader(module, { + console: Object.create(console, { + exception: { value: function(e) { + exceptions.push(e); + }} + }) }); + let { emit, on } = loader.require('sdk/event/core'); let target = {}; let boom = Error('Boom!'); let drax = Error('Draax!!'); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-event-target.js b/tools/addon-sdk-1.12/test/test-event-target.js index b8960e5..d972454 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-event-target.js +++ b/tools/addon-sdk-1.12/test/test-event-target.js @@ -4,13 +4,13 @@ 'use strict'; -const { emit } = require('api-utils/event/core'); -const { EventTarget } = require('api-utils/event/target'); -const { Loader } = require('./helpers'); +const { emit } = require('sdk/event/core'); +const { EventTarget } = require('sdk/event/target'); +const { Loader } = require('sdk/test/loader'); exports['test add a listener'] = function(assert) { let events = [ { name: 'event#1' }, 'event#2' ]; - let target = EventTarget.new(); + let target = EventTarget(); target.on('message', function(message) { assert.equal(this, target, 'this is a target object'); @@ -23,7 +23,7 @@ exports['test add a listener'] = function(assert) { exports['test pass in listeners'] = function(assert) { let actual = [ ]; - let target = EventTarget.new({ + let target = EventTarget({ onMessage: function onMessage(message) { assert.equal(this, target, 'this is an event target'); actual.push(1); @@ -46,7 +46,7 @@ exports['test pass in listeners'] = function(assert) { exports['test that listener is unique per type'] = function(assert) { let actual = [] - let target = EventTarget.new(); + let target = EventTarget(); function listener() { actual.push(1) } target.on('message', listener); target.on('message', listener); @@ -61,7 +61,7 @@ exports['test that listener is unique per type'] = function(assert) { }; exports['test event type matters'] = function(assert) { - let target = EventTarget.new(); + let target = EventTarget(); target.on('message', function() { assert.fail('no event is expected'); }); @@ -75,7 +75,7 @@ exports['test event type matters'] = function(assert) { exports['test all arguments are pasesd'] = function(assert) { let foo = { name: 'foo' }, bar = 'bar'; - let target = EventTarget.new(); + let target = EventTarget(); target.on('message', function(a, b) { assert.equal(a, foo, 'first argument passed'); assert.equal(b, bar, 'second argument passed'); @@ -84,7 +84,7 @@ exports['test all arguments are pasesd'] = function(assert) { }; exports['test no side-effects in emit'] = function(assert) { - let target = EventTarget.new(); + let target = EventTarget(); target.on('message', function() { assert.pass('first listener is called'); target.on('message', function() { @@ -96,7 +96,7 @@ exports['test no side-effects in emit'] = function(assert) { exports['test order of propagation'] = function(assert) { let actual = []; - let target = EventTarget.new(); + let target = EventTarget(); target.on('message', function() { actual.push(1); }); target.on('message', function() { actual.push(2); }); target.on('message', function() { actual.push(3); }); @@ -105,7 +105,7 @@ exports['test order of propagation'] = function(assert) { }; exports['test remove a listener'] = function(assert) { - let target = EventTarget.new(); + let target = EventTarget(); let actual = []; target.on('message', function listener() { actual.push(1); @@ -125,7 +125,7 @@ exports['test remove a listener'] = function(assert) { }; exports['test error handling'] = function(assert) { - let target = EventTarget.new(); + let target = EventTarget(); let error = Error('boom!'); target.on('message', function() { throw error; }) @@ -138,16 +138,16 @@ exports['test error handling'] = function(assert) { exports['test unhandled errors'] = function(assert) { let exceptions = []; let loader = Loader(module); - let { emit } = loader.require('api-utils/event/core'); - let { EventTarget } = loader.require('api-utils/event/target'); - Object.defineProperties(loader.sandbox('api-utils/event/core'), { + let { emit } = loader.require('sdk/event/core'); + let { EventTarget } = loader.require('sdk/event/target'); + Object.defineProperties(loader.sandbox('sdk/event/core'), { console: { value: { exception: function(e) { exceptions.push(e); } }} }); - let target = EventTarget.new(); + let target = EventTarget(); let boom = Error('Boom!'); let drax = Error('Draax!!'); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-events.js b/tools/addon-sdk-1.12/test/test-events.js index 3fe6f03..a1f87bf 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-events.js +++ b/tools/addon-sdk-1.12/test/test-events.js @@ -5,7 +5,7 @@ 'use strict'; // Exposing private methods as public in order to test -const EventEmitter = require('events').EventEmitter.compose({ +const EventEmitter = require('sdk/deprecated/events').EventEmitter.compose({ listeners: function(type) this._listeners(type), emit: function() this._emit.apply(this, arguments), emitOnObject: function() this._emitOnObject.apply(this, arguments), @@ -243,7 +243,7 @@ exports['test:once'] = function(test) { }; exports["test:removing once"] = function(test) { - let e = require("events").EventEmitterTrait.create(); + let e = require("sdk/deprecated/events").EventEmitterTrait.create(); e.once("foo", function() { test.pass("listener was called"); }); e.once("error", function() { test.fail("error event was emitted"); }); e._emit("foo", "bug-656684"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-file.js b/tools/addon-sdk-1.12/test/test-file.js index de89db8..33344b2 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-file.js +++ b/tools/addon-sdk-1.12/test/test-file.js @@ -4,12 +4,12 @@ "use strict"; -const { pathFor } = require('api-utils/system'); -const file = require("api-utils/file"); -const url = require("api-utils/url"); +const { pathFor } = require('sdk/system'); +const file = require("sdk/io/file"); +const url = require("sdk/url"); -const byteStreams = require("api-utils/byte-streams"); -const textStreams = require("api-utils/text-streams"); +const byteStreams = require("sdk/io/byte-streams"); +const textStreams = require("sdk/io/text-streams"); const ERRORS = { FILE_NOT_FOUND: /^path does not exist: .+$/, diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-frame-utils.js b/tools/addon-sdk-1.12/test/test-frame-utils.js index 268643c..6225f00 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-frame-utils.js +++ b/tools/addon-sdk-1.12/test/test-frame-utils.js @@ -4,31 +4,35 @@ 'use strict'; -const { open } = require('api-utils/window/utils'); -const { create } = require('api-utils/frame/utils'); +const { open } = require('sdk/window/utils'); +const { create } = require('sdk/frame/utils'); -exports['test frame creation'] = function(assert) { - let window = open('data:text/html,Window'); - let frame = create(window.document); +exports['test frame creation'] = function(assert, done) { + let window = open('data:text/html;charset=utf-8,Window'); + window.addEventListener('DOMContentLoaded', function windowReady() { + + let frame = create(window.document); - assert.equal(frame.getAttribute('type'), 'content', - 'frame type is content'); - assert.ok(frame.contentWindow, 'frame has contentWindow'); - assert.equal(frame.contentWindow.location.href, 'about:blank', - 'by default "about:blank" is loaded'); - assert.equal(frame.docShell.allowAuth, false, 'auth disabled by default'); - assert.equal(frame.docShell.allowJavascript, false, 'js disabled by default'); - assert.equal(frame.docShell.allowPlugins, false, - 'plugins disabled by default'); - window.close(); + assert.equal(frame.getAttribute('type'), 'content', + 'frame type is content'); + assert.ok(frame.contentWindow, 'frame has contentWindow'); + assert.equal(frame.contentWindow.location.href, 'about:blank', + 'by default "about:blank" is loaded'); + assert.equal(frame.docShell.allowAuth, false, 'auth disabled by default'); + assert.equal(frame.docShell.allowJavascript, false, 'js disabled by default'); + assert.equal(frame.docShell.allowPlugins, false, + 'plugins disabled by default'); + window.close(); + done(); + }, false); }; exports['test fram has js disabled by default'] = function(assert, done) { - let window = open('data:text/html,window'); + let window = open('data:text/html;charset=utf-8,window'); window.addEventListener('DOMContentLoaded', function windowReady() { window.removeEventListener('DOMContentLoaded', windowReady, false); let frame = create(window.document, { - uri: 'data:text/html,<script>document.documentElement.innerHTML' + + uri: 'data:text/html;charset=utf-8,<script>document.documentElement.innerHTML' + '= "J" + "S"</script>', }); frame.contentWindow.addEventListener('DOMContentLoaded', function ready() { @@ -44,11 +48,11 @@ exports['test fram has js disabled by default'] = function(assert, done) { }; exports['test frame with js enabled'] = function(assert, done) { - let window = open('data:text/html,window'); + let window = open('data:text/html;charset=utf-8,window'); window.addEventListener('DOMContentLoaded', function windowReady() { window.removeEventListener('DOMContentLoaded', windowReady, false); let frame = create(window.document, { - uri: 'data:text/html,<script>document.documentElement.innerHTML' + + uri: 'data:text/html;charset=utf-8,<script>document.documentElement.innerHTML' + '= "J" + "S"</script>', allowJavascript: true }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-functional.js b/tools/addon-sdk-1.12/test/test-functional.js index 377a709..81d36e9 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-functional.js +++ b/tools/addon-sdk-1.12/test/test-functional.js @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { setTimeout } = require('api-utils/timer'); -const utils = require('api-utils/functional'); +const { setTimeout } = require('sdk/timers'); +const utils = require('sdk/lang/functional'); const { invoke, defer, curry, compose, memoize, once, delay, wrap } = utils; exports['test forwardApply'] = function(assert) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-globals.js b/tools/addon-sdk-1.12/test/test-globals.js index 1d8caf0..1d8caf0 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-globals.js +++ b/tools/addon-sdk-1.12/test/test-globals.js diff --git a/tools/addon-sdk-1.12/test/test-heritage.js b/tools/addon-sdk-1.12/test/test-heritage.js new file mode 100644 index 0000000..493ffdd --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-heritage.js @@ -0,0 +1,375 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Class, extend, mix, obscure } = require('sdk/core/heritage'); + +exports['test extend'] = function(assert) { + let ancestor = { a: 1 }; + let descendant = extend(ancestor, { + b: 2, + get c() { return 3 }, + d: function() { return 4 } + }); + + assert.ok(ancestor.isPrototypeOf(descendant), + 'descendant inherits from ancestor'); + assert.ok(descendant.b, 2, 'proprety was implemented'); + assert.ok(descendant.c, 3, 'getter was implemented'); + assert.ok(descendant.d(), 4, 'method was implemented'); + + /* Will be fixed once Bug 674195 is shipped. + assert.ok(Object.isFrozen(descendant), + 'extend returns frozen objects'); + */ +}; + +exports['test mix'] = function(assert) { + let ancestor = { a: 1 } + let mixed = mix(extend(ancestor, { b: 1, c: 1 }), { c: 2 }, { d: 3 }); + + assert.deepEqual(JSON.parse(JSON.stringify(mixed)), { b: 1, c: 2, d: 3 }, + 'properties mixed as expected'); + assert.ok(ancestor.isPrototypeOf(mixed), + 'first arguments ancestor is ancestor of result'); +}; + +exports['test obscure'] = function(assert) { + let fixture = mix({ a: 1 }, obscure({ b: 2 })); + + assert.equal(fixture.a, 1, 'a property is included'); + assert.equal(fixture.b, 2, 'b proprety is included'); + assert.ok(!Object.getOwnPropertyDescriptor(fixture, 'b').enumerable, + 'obscured properties are non-enumerable'); +}; + +exports['test inheritance'] = function(assert) { + let Ancestor = Class({ + name: 'ancestor', + method: function () { + return 'hello ' + this.name; + } + }); + + assert.ok(Ancestor() instanceof Ancestor, + 'can be instantiated without new'); + assert.ok(new Ancestor() instanceof Ancestor, + 'can also be instantiated with new'); + assert.ok(Ancestor() instanceof Class, + 'if ancestor not specified than defaults to Class'); + assert.ok(Ancestor.prototype.extends, Class.prototype, + 'extends of prototype points to ancestors prototype'); + + + assert.equal(Ancestor().method(), 'hello ancestor', + 'instance inherits defined properties'); + + let Descendant = Class({ + extends: Ancestor, + name: 'descendant' + }); + + assert.ok(Descendant() instanceof Descendant, + 'instantiates correctly'); + assert.ok(Descendant() instanceof Ancestor, + 'Inherits for passed `extends`'); + assert.equal(Descendant().method(), 'hello descendant', + 'propreties inherited'); +}; + +exports['test prototype immutability'] = function(assert) { + let Foo = Class({ + name: 'hello', + rename: function rename(name) { + this.name = name; + } + }); + + /* Disable until release with Bug 674195 fix is shipped + assert.ok(Object.isFrozen(Foo), 'Foo is frozen'); + assert.ok(Object.isFrozen(Foo.prototype), 'Foo prototype is frozen'); + assert.ok(Object.isFrozen(Object.getPrototypeOf(Foo.prototype)), + 'Class.prototype is frozen'); + assert.equal(Object.getPrototypeOf(Object.getPrototypeOf(Foo.prototype)), + null, 'prototype of Class.prototype is null'); + */ + + assert.throws(function() { + var override = function() {}; + Foo.prototype.extend = override; + if (Foo.prototype.extend !== override) + throw Error('Property was not set'); + }, 'Can not change prototype properties'); + + assert.throws(function() { + Foo.prototype.foo = 'bar'; + if (Foo.prototype.foo !== 'bar') + throw Error('Property was not set'); + }, 'Can not add prototype properties'); + + assert.throws(function() { + delete Foo.prototype.name; + if ('name' in Foo.prototype) + throw Error('Property was not deleted'); + }, 'Can not remove prototype properties'); + + var Bar = Class({ + extends: Foo, + rename: function rename() { + return this.name; + } + }); + + assert.equal(Bar().rename(), 'hello', + 'properties may be overided on decedents'); +}; + +exports['test immunity against __proto__'] = function(assert) { + let Foo = Class({ name: 'foo', hacked: false }); + + let Bar = Class({ extends: Foo, name: 'bar' }); + + assert.throws(function() { + Foo.prototype.__proto__ = { hacked: true }; + if (Foo() instanceof Base && !Foo().hacked) + throw Error('can not change prototype chain'); + }, 'prototype chain is immune to __proto__ hacks'); + + assert.throws(function() { + Foo.prototype.__proto__ = { hacked: true }; + if (Bar() instanceof Foo && !Bar().hacked) + throw Error('can not change prototype chain'); + }, 'prototype chain of decedants immune to __proto__ hacks'); +}; + +exports['test instance mutability'] = function(assert) { + let Foo = Class({ + name: 'foo', + initialize: function initialize(number) { + this.number = number; + } + }); + + let f1 = Foo(); + + assert.throws(function() { + f1.name = 'f1'; + if (f1.name !== 'f1') + throw Error('Property was not set'); + }, 'can not change prototype properties'); + + f1.alias = 'f1'; + assert.equal(f1.alias, 'f1', 'instance is mutable'); + + delete f1.alias; + assert.ok(!('alias' in f1), 'own properties are deletable'); + + f1.initialize(1); + assert.equal(f1.number, 1, 'method can mutate instances own properties'); +}; + +exports['test super'] = function(assert) { + var Foo = Class({ + initialize: function initialize(options) { + this.name = options.name; + } + }); + + var Bar = Class({ + extends: Foo, + initialize: function Bar(options) { + Foo.prototype.initialize.call(this, options); + this.type = 'bar'; + } + }); + + var bar = Bar({ name: 'test' }); + + assert.equal(bar.type, 'bar', 'bar initializer was called'); + assert.equal(bar.name, 'test', 'bar initializer called Foo initializer'); +}; + +exports['test initialize'] = function(assert) { + var Dog = Class({ + initialize: function initialize(name) { + this.name = name; + }, + type: 'dog', + bark: function bark() { + return 'Ruff! Ruff!' + } + }); + + var fluffy = Dog('Fluffy'); // instatiation + assert.ok(fluffy instanceof Dog, + 'instanceof works as expected'); + assert.ok(fluffy instanceof Class, + 'inherits form Class if not specified otherwise'); + assert.ok(fluffy.name, 'fluffy', + 'initialize unless specified otherwise'); +}; + +exports['test complements regular inheritace'] = function(assert) { + let Base = Class({ name: 'base' }); + + function Type() { + // ... + } + Type.prototype = Object.create(Base.prototype); + Type.prototype.run = function() { + // ... + }; + + let value = new Type(); + + assert.ok(value instanceof Type, 'creates instance of Type'); + assert.ok(value instanceof Base, 'inherits from Base'); + assert.equal(value.name, 'base', 'inherits properties from Base'); + + + let SubType = Class({ + extends: Type, + sub: 'type' + }); + + let fixture = SubType(); + + assert.ok(fixture instanceof Base, 'is instance of Base'); + assert.ok(fixture instanceof Type, 'is instance of Type'); + assert.ok(fixture instanceof SubType, 'is instance of SubType'); + + assert.equal(fixture.sub, 'type', 'proprety is defined'); + assert.equal(fixture.run, Type.prototype.run, 'proprety is inherited'); + assert.equal(fixture.name, 'base', 'inherits base properties'); +}; + +exports['test extends object'] = function(assert) { + let prototype = { constructor: function() { return this; }, name: 'me' }; + let Foo = Class({ + extends: prototype, + value: 2 + }); + let foo = new Foo(); + + assert.ok(foo instanceof Foo, 'instance of Foo'); + assert.ok(!(foo instanceof Class), 'is not instance of Class'); + assert.ok(prototype.isPrototypeOf(foo), 'inherits from given prototype'); + assert.equal(Object.getPrototypeOf(Foo.prototype), prototype, + 'contsructor prototype inherits from extends option'); + assert.equal(foo.value, 2, 'property is defined'); + assert.equal(foo.name, 'me', 'prototype proprety is inherited'); +}; + + +var HEX = Class({ + hex: function hex() { + return '#' + this.color; + } +}); + +var RGB = Class({ + red: function red() { + return parseInt(this.color.substr(0, 2), 16); + }, + green: function green() { + return parseInt(this.color.substr(2, 2), 16); + }, + blue: function blue() { + return parseInt(this.color.substr(4, 2), 16); + } +}); + +var CMYK = Class({ + black: function black() { + var color = Math.max(Math.max(this.red(), this.green()), this.blue()); + return (1 - color / 255).toFixed(4); + }, + magenta: function magenta() { + var K = this.black(); + return (((1 - this.green() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); + }, + yellow: function yellow() { + var K = this.black(); + return (((1 - this.blue() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); + }, + cyan: function cyan() { + var K = this.black(); + return (((1 - this.red() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); + } +}); + +var Color = Class({ + implements: [ HEX, RGB, CMYK ], + initialize: function initialize(color) { + this.color = color; + } +}); + +exports['test composition'] = function(assert) { + var pink = Color('FFC0CB'); + + assert.equal(pink.red(), 255, 'red() works'); + assert.equal(pink.green(), 192, 'green() works'); + assert.equal(pink.blue(), 203, 'blue() works'); + + assert.equal(pink.magenta(), 0.2471, 'magenta() works'); + assert.equal(pink.yellow(), 0.2039, 'yellow() works'); + assert.equal(pink.cyan(), 0.0000, 'cyan() works'); + + assert.ok(pink instanceof Color, 'is instance of Color'); + assert.ok(pink instanceof Class, 'is instance of Class'); +}; + +var Point = Class({ + initialize: function initialize(x, y) { + this.x = x; + this.y = y; + }, + toString: function toString() { + return this.x + ':' + this.y; + } +}) + +var Pixel = Class({ + extends: Point, + implements: [ Color ], + initialize: function initialize(x, y, color) { + Color.prototype.initialize.call(this, color); + Point.prototype.initialize.call(this, x, y); + }, + toString: function toString() { + return this.hex() + '@' + Point.prototype.toString.call(this) + } +}); + +exports['test compostion with inheritance'] = function(assert) { + var pixel = Pixel(11, 23, 'CC3399'); + + assert.equal(pixel.toString(), '#CC3399@11:23', 'stringifies correctly'); + assert.ok(pixel instanceof Pixel, 'instance of Pixel'); + assert.ok(pixel instanceof Point, 'instance of Point'); +}; + +exports['test composition with objects'] = function(assert) { + var A = { a: 1, b: 1 }; + var B = Class({ b: 2, c: 2 }); + var C = { c: 3 }; + var D = { d: 4 }; + + var ABCD = Class({ + implements: [ A, B, C, D ], + e: 5 + }); + + var f = ABCD(); + + assert.equal(f.a, 1, 'inherits A.a'); + assert.equal(f.b, 2, 'inherits B.b overrides A.b'); + assert.equal(f.c, 3, 'inherits C.c overrides B.c'); + assert.equal(f.d, 4, 'inherits D.d'); + assert.equal(f.e, 5, 'implements e'); +}; + +require("test").run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-hidden-frame.js b/tools/addon-sdk-1.12/test/test-hidden-frame.js index 2441c3e..cf99df5 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-hidden-frame.js +++ b/tools/addon-sdk-1.12/test/test-hidden-frame.js @@ -5,7 +5,7 @@ let tests = {}, hiddenFrames, HiddenFrame; tests.testFrame = function(test) { - let url = "data:text/html,<!DOCTYPE%20html>"; + let url = "data:text/html;charset=utf-8,<!DOCTYPE%20html>"; test.waitUntilDone(); let hiddenFrame = hiddenFrames.add(HiddenFrame({ onReady: function () { @@ -28,7 +28,7 @@ tests.testFrame = function(test) { let hiddenFrameSupported = true; try { - hiddenFrames = require("hidden-frame"); + hiddenFrames = require("sdk/frame/hidden-frame"); HiddenFrame = hiddenFrames.HiddenFrame; } catch(ex if ex.message == [ diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-hotkeys.js b/tools/addon-sdk-1.12/test/test-hotkeys.js index 0e0ecd6..7dc590f 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-hotkeys.js +++ b/tools/addon-sdk-1.12/test/test-hotkeys.js @@ -4,12 +4,14 @@ "use strict"; -const { Hotkey } = require("hotkeys"); -const { keyDown } = require("dom/events/keys"); -const { Loader } = require('./helpers'); +const { Hotkey } = require("sdk/hotkeys"); +const { keyDown } = require("sdk/dom/events/keys"); +const { Loader } = require('sdk/test/loader'); +const timer = require("sdk/timers"); +const winUtils = require("sdk/deprecated/window-utils"); exports["test hotkey: function key"] = function(assert, done) { - var element = require("window-utils").activeBrowserWindow.document.documentElement; + var element = winUtils.activeBrowserWindow.document.documentElement; var showHotKey = Hotkey({ combo: "f1", onPress: function() { @@ -32,7 +34,7 @@ exports["test hotkey: function key"] = function(assert, done) { }; exports["test hotkey: accel alt shift"] = function(assert, done) { - var element = require("window-utils").activeBrowserWindow.document.documentElement; + var element = winUtils.activeBrowserWindow.document.documentElement; var showHotKey = Hotkey({ combo: "accel-shift-6", onPress: function() { @@ -55,7 +57,7 @@ exports["test hotkey: accel alt shift"] = function(assert, done) { }; exports["test hotkey meta & control"] = function(assert, done) { - var element = require("window-utils").activeBrowserWindow.document.documentElement; + var element = winUtils.activeBrowserWindow.document.documentElement; var showHotKey = Hotkey({ combo: "meta-3", onPress: function() { @@ -78,7 +80,7 @@ exports["test hotkey meta & control"] = function(assert, done) { }; exports["test hotkey: control-1 / meta--"] = function(assert, done) { - var element = require("window-utils").activeBrowserWindow.document.documentElement; + var element = winUtils.activeBrowserWindow.document.documentElement; var showHotKey = Hotkey({ combo: "control-1", onPress: function() { @@ -122,7 +124,7 @@ exports["test invalid combos"] = function(assert) { }; exports["test no exception on unmodified keypress"] = function(assert) { - var element = require("window-utils").activeBrowserWindow.document.documentElement; + var element = winUtils.activeBrowserWindow.document.documentElement; var someHotkey = Hotkey({ combo: "control-alt-1", onPress: function() { @@ -137,8 +139,8 @@ exports["test hotkey: automatic destroy"] = function(assert, done) { let loader = Loader(module); var called = false; - var element = loader.require("window-utils").activeBrowserWindow.document.documentElement; - var hotkey = loader.require("hotkeys").Hotkey({ + var element = loader.require("sdk/deprecated/window-utils").activeBrowserWindow.document.documentElement; + var hotkey = loader.require("sdk/hotkeys").Hotkey({ combo: "accel-shift-x", onPress: function() { called = true; @@ -151,7 +153,7 @@ exports["test hotkey: automatic destroy"] = function(assert, done) { // Ensure that the hotkey is really destroyed keyDown(element, "accel-shift-x"); - require("timer").setTimeout(function () { + timer.setTimeout(function () { assert.ok(!called, "Hotkey is destroyed and not called."); done(); }, 0); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-httpd.js b/tools/addon-sdk-1.12/test/test-httpd.js index dc1adf1..1ab9522 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-httpd.js +++ b/tools/addon-sdk-1.12/test/test-httpd.js @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const port = 8099; -const file = require("api-utils/file"); -const { pathFor } = require("api-utils/system"); +const file = require("sdk/io/file"); +const { pathFor } = require("sdk/system"); exports.testBasicHTTPServer = function(test) { let basePath = pathFor("TmpD"); @@ -14,13 +14,13 @@ exports.testBasicHTTPServer = function(test) { fileStream.write(content); fileStream.close(); - let { startServerAsync } = require("httpd"); + let { startServerAsync } = require("sdk/test/httpd"); let srv = startServerAsync(port, basePath); test.waitUntilDone(); // Request this very file. - let Request = require('request').Request; + let Request = require('sdk/request').Request; Request({ url: "http://localhost:" + port + "/test-httpd.txt", onComplete: function (response) { @@ -39,7 +39,7 @@ exports.testBasicHTTPServer = function(test) { exports.testDynamicServer = function (test) { let content = "This is the HTTPD test file.\n"; - let { startServerAsync } = require("httpd"); + let { startServerAsync } = require("sdk/test/httpd"); let srv = startServerAsync(port); // See documentation here: @@ -54,7 +54,7 @@ exports.testDynamicServer = function (test) { test.waitUntilDone(); // Request this very file. - let Request = require('request').Request; + let Request = require('sdk/request').Request; Request({ url: "http://localhost:" + port + "/test-httpd.txt", onComplete: function (response) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-observer.js b/tools/addon-sdk-1.12/test/test-keyboard-observer.js index 584f01b..091ec73 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-observer.js +++ b/tools/addon-sdk-1.12/test/test-keyboard-observer.js @@ -4,14 +4,15 @@ "use strict"; -const { keyPress } = require("api-utils/dom/events/keys"); -const { Loader } = require("./helpers"); +const { keyPress } = require("sdk/dom/events/keys"); +const { Loader } = require("sdk/test/loader"); +const timer = require("sdk/timers"); exports["test unload keyboard observer"] = function(assert, done) { let loader = Loader(module); - let element = loader.require("api-utils/window-utils"). + let element = loader.require("sdk/deprecated/window-utils"). activeBrowserWindow.document.documentElement; - let observer = loader.require("api-utils/keyboard/observer"). + let observer = loader.require("sdk/keyboard/observer"). observer; let called = 0; @@ -27,7 +28,7 @@ exports["test unload keyboard observer"] = function(assert, done) { keyPress(element, "accel-%"); // Enqueuing asserts to make sure that assertion is not performed early. - require("timer").setTimeout(function () { + timer.setTimeout(function () { assert.equal(called, 1, "observer was called before unload only."); done(); }, 0); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-utils.js b/tools/addon-sdk-1.12/test/test-keyboard-utils.js index 1146a7b..19981de 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-keyboard-utils.js +++ b/tools/addon-sdk-1.12/test/test-keyboard-utils.js @@ -4,8 +4,8 @@ "use strict"; -const utils = require("keyboard/utils"); -const runtime = require("runtime"); +const utils = require("sdk/keyboard/utils"); +const runtime = require("sdk/system/runtime"); const isMac = runtime.OS === "Darwin"; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-locale.js b/tools/addon-sdk-1.12/test/test-l10n-locale.js index db559ba..19e716d 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-locale.js +++ b/tools/addon-sdk-1.12/test/test-l10n-locale.js @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { getPreferedLocales, findClosestLocale } = require("api-utils/l10n/locale"); -const prefs = require("preferences-service"); +const { getPreferedLocales, findClosestLocale } = require("sdk/l10n/locale"); +const prefs = require("sdk/preferences/service"); const { Cc, Ci, Cu } = require("chrome"); const { Services } = Cu.import("resource://gre/modules/Services.jsm"); const BundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-plural-rules.js b/tools/addon-sdk-1.12/test/test-l10n-plural-rules.js index e46ecf6..6ee8a13 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-l10n-plural-rules.js +++ b/tools/addon-sdk-1.12/test/test-l10n-plural-rules.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { getRulesForLocale } = require("api-utils/l10n/plural-rules"); +const { getRulesForLocale } = require("sdk/l10n/plural-rules"); // For more information, please visit unicode website: // http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html diff --git a/tools/addon-sdk-1.12/test/test-layout-change.js b/tools/addon-sdk-1.12/test/test-layout-change.js new file mode 100644 index 0000000..a262251 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-layout-change.js @@ -0,0 +1,178 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +// This test makes sure that require statements used by all AMO hosted +// add-ons will be able to use old require statements. +// Tests are based on following usage data: +// https://docs.google.com/spreadsheet/ccc?key=0ApEBy-GRnGxzdHlRMHJ5RXN1aWJ4RGhINkxSd0FCQXc#gid=0 + +exports["test compatibility"] = function(assert) { + assert.equal(require("self"), + require("sdk/self"), "sdk/self -> self"); + + assert.equal(require("tabs"), + require("sdk/tabs"), "sdk/tabs -> tabs"); + + assert.equal(require("widget"), + require("sdk/widget"), "sdk/widget -> widget"); + + assert.equal(require("page-mod"), + require("sdk/page-mod"), "sdk/page-mod -> page-mod"); + + assert.equal(require("panel"), + require("sdk/panel"), "sdk/panel -> panel"); + + assert.equal(require("request"), + require("sdk/request"), "sdk/request -> request"); + + assert.equal(require("chrome"), + require("chrome"), "chrome -> chrome"); + + assert.equal(require("simple-storage"), + require("sdk/simple-storage"), "sdk/simple-storage -> simple-storage"); + + assert.equal(require("context-menu"), + require("sdk/context-menu"), "sdk/context-menu -> context-menu"); + + assert.equal(require("notifications"), + require("sdk/notifications"), "sdk/notifications -> notifications"); + + assert.equal(require("preferences-service"), + require("sdk/preferences/service"), "sdk/preferences/service -> preferences-service"); + + assert.equal(require("window-utils"), + require("sdk/deprecated/window-utils"), "sdk/deprecated/window-utils -> window-utils"); + + assert.equal(require("url"), + require("sdk/url"), "sdk/url -> url"); + + assert.equal(require("selection"), + require("sdk/selection"), "sdk/selection -> selection"); + + assert.equal(require("timers"), + require("sdk/timers"), "sdk/timers -> timers"); + + assert.equal(require("simple-prefs"), + require("sdk/simple-prefs"), "sdk/simple-prefs -> simple-prefs"); + + assert.equal(require("traceback"), + require("sdk/console/traceback"), "sdk/console/traceback -> traceback"); + + assert.equal(require("unload"), + require("sdk/system/unload"), "sdk/system/unload -> unload"); + + assert.equal(require("hotkeys"), + require("sdk/hotkeys"), "sdk/hotkeys -> hotkeys"); + + assert.equal(require("clipboard"), + require("sdk/clipboard"), "sdk/clipboard -> clipboard"); + + assert.equal(require("windows"), + require("sdk/windows"), "sdk/windows -> windows"); + + assert.equal(require("page-worker"), + require("sdk/page-worker"), "sdk/page-worker -> page-worker"); + + assert.equal(require("timer"), + require("sdk/timers"), "sdk/timers -> timer"); + + assert.equal(require("xhr"), + require("sdk/net/xhr"), "sdk/io/xhr -> xhr"); + + assert.equal(require("observer-service"), + require("sdk/deprecated/observer-service"), "sdk/deprecated/observer-service -> observer-service"); + + assert.equal(require("private-browsing"), + require("sdk/private-browsing"), "sdk/private-browsing -> private-browsing"); + + assert.equal(require("passwords"), + require("sdk/passwords"), "sdk/passwords -> passwords"); + + assert.equal(require("events"), + require("sdk/deprecated/events"), "sdk/deprecated/events -> events"); + + assert.equal(require("match-pattern"), + require("sdk/page-mod/match-pattern"), "sdk/page-mod/match-pattern -> match-pattern"); + + assert.equal(require("tab-browser"), + require("sdk/deprecated/tab-browser"), "sdk/deprecated/tab-browser -> tab-browser"); + + assert.equal(require("file"), + require("sdk/io/file"), "sdk/io/file -> file"); + + assert.equal(require("xul-app"), + require("sdk/system/xul-app"), "sdk/system/xul-app -> xul-app"); + + assert.equal(require("api-utils"), + require("sdk/deprecated/api-utils"), "sdk/deprecated/api-utils -> api-utils"); + + assert.equal(require("runtime"), + require("sdk/system/runtime"), "sdk/system/runtime -> runtime"); + + assert.equal(require("base64"), + require("sdk/base64"), "sdk/base64 -> base64"); + + assert.equal(require("xpcom"), + require("sdk/platform/xpcom"), "sdk/platform/xpcom -> xpcom"); + + assert.equal(require("traits"), + require("sdk/deprecated/traits"), "sdk/deprecated/traits -> traits"); + + assert.equal(require("keyboard/utils"), + require("sdk/keyboard/utils"), "sdk/keyboard/utils -> keyboard/utils"); + + assert.equal(require("system"), + require("sdk/system"), "sdk/system -> system"); + + assert.equal(require("querystring"), + require("sdk/querystring"), "sdk/querystring -> querystring"); + + assert.equal(require("addon-page"), + require("sdk/addon-page"), "sdk/addon-page -> addon-page"); + + assert.equal(require("tabs/utils"), + require("sdk/tabs/utils"), "sdk/tabs/utils -> tabs/utils"); + + assert.equal(require("app-strings"), + require("sdk/deprecated/app-strings"), "sdk/deprecated/app-strings -> app-strings"); + + assert.equal(require("dom/events"), + require("sdk/dom/events"), "sdk/dom/events -> dom/events"); + + assert.equal(require("tabs/tab.js"), + require("sdk/tabs/tab"), "sdk/tabs/tab -> tabs/tab.js"); + + assert.equal(require("memory"), + require("sdk/deprecated/memory"), "sdk/deprecated/memory -> memory"); + + assert.equal(require("light-traits"), + require("sdk/deprecated/light-traits"), "sdk/deprecated/light-traits -> light-traits"); + + assert.equal(require("environment"), + require("sdk/system/environment"), "sdk/system/environment -> environment"); + + assert.equal(require("utils/data"), + require("sdk/io/data"), "sdk/io/data -> utils/data"); + + assert.equal(require("test/assert"), + require("sdk/test/assert"), "sdk/test/assert -> test/assert"); + + assert.equal(require("hidden-frame"), + require("sdk/frame/hidden-frame"), "sdk/frame/hidden-frame -> hidden-frame"); + + assert.equal(require("collection"), + require("sdk/util/collection"), "sdk/util/collection -> collection"); + + assert.equal(require("array"), + require("sdk/util/array"), "sdk/util/array -> array"); + + assert.equal(require("api-utils/cortex"), + require("sdk/deprecated/cortex"), + "api-utils/cortex -> sdk/deprecated/cortex"); +}; + + +require('test').run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-light-traits.js b/tools/addon-sdk-1.12/test/test-light-traits.js index 7c5ca42..7c5ca42 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-light-traits.js +++ b/tools/addon-sdk-1.12/test/test-light-traits.js diff --git a/tools/addon-sdk-1.12/test/test-list.js b/tools/addon-sdk-1.12/test/test-list.js new file mode 100644 index 0000000..1e345d2 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-list.js @@ -0,0 +1,43 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { List, addListItem, removeListItem } = require('sdk/util/list'); +const { Class } = require('sdk/core/heritage'); + +exports.testList = function(test) { + let list = List(); + addListItem(list, 1); + + for (let key in list) { + test.assertEqual(key, 0, 'key is correct'); + test.assertEqual(list[key], 1, 'value is correct'); + } + + let count = 0; + for each (let ele in list) { + test.assertEqual(ele, 1, 'ele is correct'); + test.assertEqual(++count, 1, 'count is correct'); + } + + removeListItem(list, 1); + test.assertEqual(list.length, 0, 'remove worked'); +}; + +exports.testImplementsList = function(test) { + let List2 = Class({ + implements: [List], + initialize: function() { + List.prototype.initialize.apply(this, [0, 1, 2]); + } + }); + let list2 = List2(); + let count = 0; + for each (let ele in list2) { + test.assertEqual(ele, count++, 'ele is correct'); + } + addListItem(list2, 3); + test.assertEqual(list2.length, 4, '3 was added'); + test.assertEqual(list2[list2.length-1], 3, '3 was added'); +} diff --git a/tools/addon-sdk-1.12/test/test-loader.js b/tools/addon-sdk-1.12/test/test-loader.js new file mode 100644 index 0000000..08c285f --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-loader.js @@ -0,0 +1,27 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +'use strict'; + +let { Loader, main, unload } = require('toolkit/loader'); + +exports['test dependency cycles'] = function(assert) { + let uri = module.uri.substr(0, module.uri.lastIndexOf('/')) + + '/fixtures/loader/cycles/' + + let loader = Loader({ + paths: { '': uri } + }); + + let program = main(loader, 'main') + + assert.equal(program.a.b, program.b, 'module `a` gets correct `b`') + assert.equal(program.b.a, program.a, 'module `b` gets correct `a`') + assert.equal(program.c.main, program, 'module `c` gets correct `main`') + + unload(loader); +}; + +require('test').run(exports); + diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-match-pattern.js b/tools/addon-sdk-1.12/test/test-match-pattern.js index 9cedf66..60cdac2 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-match-pattern.js +++ b/tools/addon-sdk-1.12/test/test-match-pattern.js @@ -3,8 +3,9 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; -const { MatchPattern } = require("match-pattern"); +const { MatchPattern } = require("sdk/page-mod/match-pattern"); exports.testMatchPatternTestTrue = function(test) { function ok(pattern, url) { @@ -67,6 +68,7 @@ exports.testMatchPatternTestFalse = function(test) { ok(/zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); ok(/.*zilla/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); + ok(/.*Zilla.*/, "https://bugzilla.redhat.com/show_bug.cgi?id=655464"); // bug 655464 ok(/https:.*zilla/, "https://bugzilla.redhat.com/show_bug.cgi?id=569753"); }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-memory.js b/tools/addon-sdk-1.12/test/test-memory.js index 99e1682..e225707 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-memory.js +++ b/tools/addon-sdk-1.12/test/test-memory.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var memory = require("api-utils/memory"); +var memory = require("sdk/deprecated/memory"); exports.testMemory = function(test) { test.pass("Skipping this test until Gecko memory debugging issues " + diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-module.js b/tools/addon-sdk-1.12/test/test-module.js index 957d075..6c9c6c2 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-module.js +++ b/tools/addon-sdk-1.12/test/test-module.js @@ -6,12 +6,12 @@ /** Disabled because of Bug 672199 exports["test module exports are frozen"] = function(assert) { - assert.ok(Object.isFrozen(require("addon-kit/hotkeys")), + assert.ok(Object.isFrozen(require("sdk/hotkeys")), "module exports are frozen"); }; exports["test redefine exported property"] = function(assert) { - let hotkeys = require("addon-kit/hotkeys"); + let hotkeys = require("sdk/hotkeys"); let { Hotkey } = hotkeys; try { Object.defineProperty(hotkeys, 'Hotkey', { value: {} }); } catch(e) {} assert.equal(hotkeys.Hotkey, Hotkey, "exports can't be redefined"); @@ -19,7 +19,7 @@ exports["test redefine exported property"] = function(assert) { */ exports["test can't delete exported property"] = function(assert) { - let hotkeys = require("addon-kit/hotkeys"); + let hotkeys = require("sdk/hotkeys"); let { Hotkey } = hotkeys; try { delete hotkeys.Hotkey; } catch(e) {} @@ -27,7 +27,7 @@ exports["test can't delete exported property"] = function(assert) { }; exports["test can't override exported property"] = function(assert) { - let hotkeys = require("addon-kit/hotkeys"); + let hotkeys = require("sdk/hotkeys"); let { Hotkey } = hotkeys; try { hotkeys.Hotkey = Object } catch(e) {} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-modules.js b/tools/addon-sdk-1.12/test/test-modules.js index 2868560..2868560 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-modules.js +++ b/tools/addon-sdk-1.12/test/test-modules.js diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-namespace.js b/tools/addon-sdk-1.12/test/test-namespace.js index cb69bb0..dfe88da 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-namespace.js +++ b/tools/addon-sdk-1.12/test/test-namespace.js @@ -4,12 +4,11 @@ "use strict"; -let { Namespace, ns } = require("api-utils/namespace"); -let { Cc, Ci, Cu } = require("chrome"); -let { setTimeout } = require("api-utils/timer") +const { ns } = require("sdk/core/namespace"); +const { Cc, Ci, Cu } = require("chrome"); +const { setTimeout } = require("sdk/timers") exports["test post GC references"] = function (assert, done) { - // Test temporary workaround for a bug 673468. var target = {}, local = ns() local(target).there = true @@ -23,7 +22,7 @@ exports["test post GC references"] = function (assert, done) { }; exports["test namsepace basics"] = function(assert) { - var privates = Namespace(); + var privates = ns(); var object = { foo: function foo() { return "hello foo"; } }; assert.notEqual(privates(object), object, @@ -36,7 +35,7 @@ exports["test namsepace basics"] = function(assert) { }; exports["test namespace overlays"] = function(assert) { - var _ = new Namespace(); + var _ = ns(); var object = { foo: 'foo' }; _(object).foo = 'bar'; @@ -57,16 +56,17 @@ exports["test namespace overlays"] = function(assert) { }; exports["test shared namespaces"] = function(assert) { - var _ = new Namespace({ hello: 'hello world' }); + var _ = ns(); var f1 = { hello: 1 }; - var f2 = { foo: 'foo' }; + var f2 = { foo: 'foo', hello: 2 }; + _(f1).foo = _(f2).foo = 'bar'; assert.equal(_(f1).hello, _(f2).hello, "namespace can be shared"); assert.notEqual(f1.hello, _(f1).hello, "shared namespace can overlay"); assert.notEqual(f2.hello, _(f2).hello, "target is not affected"); - _(f1).hello = 2; + _(f1).hello = 3; assert.notEqual(_(f1).hello, _(f2).hello, "namespaced property can be overided"); @@ -74,8 +74,8 @@ exports["test shared namespaces"] = function(assert) { }; exports["test multi namespace"] = function(assert) { - var n1 = new Namespace(); - var n2 = new Namespace(); + var n1 = ns(); + var n2 = ns(); var object = { baz: 1 }; n1(object).foo = 1; n2(object).foo = 2; @@ -88,8 +88,35 @@ exports["test multi namespace"] = function(assert) { }; exports["test ns alias"] = function(assert) { - assert.strictEqual(ns, Namespace, + assert.strictEqual(ns, require('sdk/core/namespace').Namespace, "ns is an alias of Namespace"); -} +}; + +exports["test ns inheritance"] = function(assert) { + let _ = ns(); + + let prototype = { level: 1 }; + let object = Object.create(prototype); + let delegee = Object.create(object); + + _(prototype).foo = {}; + + assert.ok(!Object.prototype.hasOwnProperty.call(_(delegee), "foo"), + "namespaced property is not copied to descendants"); + assert.equal(_(delegee).foo, _(prototype).foo, + "namespaced properties are inherited by descendants"); + + _(object).foo = {}; + assert.notEqual(_(object).foo, _(prototype).foo, + "namespaced properties may be shadowed"); + assert.equal(_(object).foo, _(delegee).foo, + "shadwed properties are inherited by descendants"); + + _(object).bar = {}; + assert.ok(!("bar" in _(prototype)), + "descendants properties are not copied to ancestors"); + assert.ok(_(object).bar, _(delegee).bar, + "descendants properties are inherited"); +}; require("test").run(exports); diff --git a/tools/addon-sdk-1.12/test/test-net-url.js b/tools/addon-sdk-1.12/test/test-net-url.js new file mode 100644 index 0000000..302c402 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-net-url.js @@ -0,0 +1,212 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { readURI, readURISync } = require("sdk/net/url"); +const { data } = require("self"); + +const utf8text = "Hello, ゼロ!"; +const latin1text = "Hello, ゼãƒ!"; + +const dataURIutf8 = "data:text/plain;charset=utf-8," + encodeURIComponent(utf8text); +const dataURIlatin1 = "data:text/plain;charset=ISO-8859-1," + escape(latin1text); +const chromeURI = "chrome://global-platform/locale/accessible.properties"; + +exports["test async readURI"] = function(assert, done) { + let content = ""; + + readURI(data.url("test-net-url.txt")).then(function(data) { + content = data; + assert.equal(content, utf8text, "The URL content is loaded properly"); + done(); + }, function() { + assert.fail("should not reject"); + done(); + }) + + assert.equal(content, "", "The URL content is not load yet"); +} + +exports["test sync readURI"] = function(assert) { + let content = ""; + + readURI(data.url("test-net-url.txt"), { sync: true }).then(function(data) { + content = data; + }, function() { + assert.fail("should not reject"); + }) + + assert.equal(content, utf8text, "The URL content is loaded properly"); +} + +exports["test readURISync"] = function(assert) { + let content = readURISync(data.url("test-net-url.txt")); + + assert.equal(content, utf8text, "The URL content is loaded properly"); +} + +exports["test async readURI with ISO-8859-1 charset"] = function(assert, done) { + let content = ""; + + readURI(data.url("test-net-url.txt"), { charset : "ISO-8859-1"}).then(function(data) { + content = data; + assert.equal(content, latin1text, "The URL content is loaded properly"); + done(); + }, function() { + assert.fail("should not reject"); + done(); + }) + + assert.equal(content, "", "The URL content is not load yet"); +} + +exports["test sync readURI with ISO-8859-1 charset"] = function(assert) { + let content = ""; + + readURI(data.url("test-net-url.txt"), { + sync: true, + charset: "ISO-8859-1" + }).then(function(data) { + content = data; + }, function() { + assert.fail("should not reject"); + }) + + assert.equal(content, latin1text, "The URL content is loaded properly"); +} + +exports["test readURISync with ISO-8859-1 charset"] = function(assert) { + let content = readURISync(data.url("test-net-url.txt"), "ISO-8859-1"); + + assert.equal(content, latin1text, "The URL content is loaded properly"); +} + +exports["test async readURI with not existing file"] = function(assert, done) { + readURI(data.url("test-net-url-fake.txt")).then(function(data) { + assert.fail("should not resolve"); + done(); + }, function(reason) { + assert.ok(reason.indexOf("Failed to read:") === 0); + done(); + }) +} + +exports["test sync readURI with not existing file"] = function(assert) { + readURI(data.url("test-net-url-fake.txt"), { sync: true }).then(function(data) { + assert.fail("should not resolve"); + }, function(reason) { + assert.ok(reason.indexOf("Failed to read:") === 0); + }) +} + +exports["test readURISync with not existing file"] = function(assert) { + assert.throws(function() { + readURISync(data.url("test-net-url-fake.txt")); + }, /NS_ERROR_FILE_NOT_FOUND/); +} + +exports["test async readURI with data URI"] = function(assert, done) { + let content = ""; + + readURI(dataURIutf8).then(function(data) { + content = data; + assert.equal(content, utf8text, "The URL content is loaded properly"); + done(); + }, function() { + assert.fail("should not reject"); + done(); + }) + + assert.equal(content, "", "The URL content is not load yet"); +} + +exports["test sync readURI with data URI"] = function(assert) { + let content = ""; + + readURI(dataURIutf8, { sync: true }).then(function(data) { + content = data; + }, function() { + assert.fail("should not reject"); + }) + + assert.equal(content, utf8text, "The URL content is loaded properly"); +} + +exports["test readURISync with data URI"] = function(assert) { + let content = readURISync(dataURIutf8); + + assert.equal(content, utf8text, "The URL content is loaded properly"); +} + +exports["test async readURI with data URI and ISO-8859-1 charset"] = function(assert, done) { + let content = ""; + + readURI(dataURIlatin1, { charset : "ISO-8859-1"}).then(function(data) { + content = unescape(data); + assert.equal(content, latin1text, "The URL content is loaded properly"); + done(); + }, function() { + assert.fail("should not reject"); + done(); + }) + + assert.equal(content, "", "The URL content is not load yet"); +} + +exports["test sync readURI with data URI and ISO-8859-1 charset"] = function(assert) { + let content = ""; + + readURI(dataURIlatin1, { + sync: true, + charset: "ISO-8859-1" + }).then(function(data) { + content = unescape(data); + }, function() { + assert.fail("should not reject"); + }) + + assert.equal(content, latin1text, "The URL content is loaded properly"); +} + +exports["test readURISync with data URI and ISO-8859-1 charset"] = function(assert) { + let content = unescape(readURISync(dataURIlatin1, "ISO-8859-1")); + + assert.equal(content, latin1text, "The URL content is loaded properly"); +} + +exports["test readURISync with chrome URI"] = function(assert) { + let content = readURISync(chromeURI); + + assert.ok(content, "The URL content is loaded properly"); +} + +exports["test async readURI with chrome URI"] = function(assert, done) { + let content = ""; + + readURI(chromeURI).then(function(data) { + content = data; + assert.equal(content, readURISync(chromeURI), "The URL content is loaded properly"); + done(); + }, function() { + assert.fail("should not reject"); + done(); + }) + + assert.equal(content, "", "The URL content is not load yet"); +} + +exports["test sync readURI with chrome URI"] = function(assert) { + let content = ""; + + readURI(chromeURI, { sync: true }).then(function(data) { + content = data; + }, function() { + assert.fail("should not reject"); + }) + + assert.equal(content, readURISync(chromeURI), "The URL content is loaded properly"); +} + +require("test").run(exports) diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-notifications.js b/tools/addon-sdk-1.12/test/test-notifications.js index b0e1f37..3f29410 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-notifications.js +++ b/tools/addon-sdk-1.12/test/test-notifications.js @@ -4,11 +4,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { Loader } = require('./helpers'); +const { Loader } = require('sdk/test/loader'); exports.testOnClick = function (test) { let [loader, mockAlertServ] = makeLoader(module); - let notifs = loader.require("notifications"); + let notifs = loader.require("sdk/notifications"); let data = "test data"; let opts = { onClick: function (clickedData) { @@ -39,8 +39,8 @@ function makeLoader(test) { this._alertListener.observe(null, "alertclickcallback", this._cookie); } }; - loader.require("notifications"); - let scope = loader.sandbox("notifications"); + loader.require("sdk/notifications"); + let scope = loader.sandbox("sdk/notifications"); scope.notify = mockAlertServ.showAlertNotification.bind(mockAlertServ); return [loader, mockAlertServ]; }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-observer-service.js b/tools/addon-sdk-1.12/test/test-observer-service.js index 222ae22..bd4c903 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-observer-service.js +++ b/tools/addon-sdk-1.12/test/test-observer-service.js @@ -2,16 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var observers = require("api-utils/observer-service"); -var {Cc,Ci} = require("chrome"); -const { Loader } = require("./helpers"); +const observers = require("sdk/deprecated/observer-service"); +const { Cc, Ci } = require("chrome"); +const { Loader } = require("sdk/test/loader"); +const { PlainTextConsole } = require("sdk/console/plain-text"); exports.testUnloadAndErrorLogging = function(test) { var prints = []; - var loader = Loader(module, { dump: function print(message) { - prints.push(message); - }}); - var sbobsvc = loader.require("api-utils/observer-service"); + var loader = Loader(module, { + console: new PlainTextConsole(function(_) { + prints.push(_); + }) + }); + var sbobsvc = loader.require("sdk/deprecated/observer-service"); var timesCalled = 0; var cb = function(subject, data) { @@ -26,7 +29,7 @@ exports.testUnloadAndErrorLogging = function(test) { sbobsvc.add("narg", badCb); observers.notify("narg", "yo yo"); var lines = prints[0].split("\n"); - test.assertEqual(lines[0], "error: An exception occurred."); + test.assertEqual(lines[0], "error: " + require("sdk/self").name + ": An exception occurred."); test.assertEqual(lines[1], "Traceback (most recent call last):"); test.assertEqual(lines.slice(-2)[0], "Error: foo"); diff --git a/tools/addon-sdk-1.12/test/test-packaging.js b/tools/addon-sdk-1.12/test/test-packaging.js new file mode 100644 index 0000000..b7a96cd --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-packaging.js @@ -0,0 +1,15 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +var url = require("sdk/url"); +var file = require("sdk/io/file"); +var {Cm,Ci} = require("chrome"); +var options = require("@loader/options"); + +exports.testPackaging = function(test) { + + test.assertEqual(options.metadata.description, + "Add-on development made easy.", + "packaging metadata should be available"); +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-mod.js b/tools/addon-sdk-1.12/test/test-page-mod.js index 14a3ef9..9cb9265 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-mod.js +++ b/tools/addon-sdk-1.12/test/test-page-mod.js @@ -1,13 +1,18 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - "use strict"; -var pageMod = require("page-mod"); -var testPageMod = require("pagemod-test-helpers").testPageMod; -const { Loader } = require('./helpers'); -const tabs = require("tabs"); +var pageMod = require("sdk/page-mod"); +var testPageMod = require("./pagemod-test-helpers").testPageMod; +const { Loader } = require('sdk/test/loader'); +const tabs = require("sdk/tabs"); +const timer = require("sdk/timers"); +const { Cc, Ci } = require("chrome"); +const { open, getFrames, getMostRecentBrowserWindow } = require('sdk/window/utils'); +const windowUtils = require('sdk/deprecated/window-utils'); +const { getTabContentWindow, getActiveTab, openTab, closeTab } = require('sdk/tabs/utils'); +const { data } = require('self'); /* XXX This can be used to delay closing the test Firefox instance for interactive * testing or visual inspection. This test is registered first so that it runs @@ -15,11 +20,15 @@ const tabs = require("tabs"); exports.delay = function(test) { if (false) { test.waitUntilDone(60000); - require("timer").setTimeout(function() {test.done();}, 4000); + timer.setTimeout(function() {test.done();}, 4000); } else test.pass(); } +function Isolate(worker) { + return "(" + worker + ")()"; +} + /* Tests for the PageMod APIs */ exports.testPageMod1 = function(test) { @@ -180,7 +189,7 @@ exports.testCommunication2 = function(test) { let callbackDone = null, window; - testPageMod(test, "about:credits", [{ + testPageMod(test, "about:license", [{ include: "about:*", contentScriptWhen: 'start', contentScript: 'new ' + function WorkerScope() { @@ -267,7 +276,7 @@ exports.testMixedContext = function(test) { let doneCallback = null; let messages = 0; let modObject = { - include: "data:text/html,", + include: "data:text/html;charset=utf-8,", contentScript: 'new ' + function WorkerScope() { // Both scripts will execute this, // context is shared if one script see the other one modification. @@ -288,7 +297,7 @@ exports.testMixedContext = function(test) { }); } }; - testPageMod(test, "data:text/html,", [modObject, modObject], + testPageMod(test, "data:text/html;charset=utf-8,", [modObject, modObject], function(win, done) { doneCallback = done; } @@ -299,7 +308,7 @@ exports.testHistory = function(test) { // We need a valid url in order to have a working History API. // (i.e do not work on data: or about: pages) // Test bug 679054. - let url = require("self").data.url("test-page-mod.html"); + let url = require("sdk/self").data.url("test-page-mod.html"); let callbackDone = null; testPageMod(test, url, [{ include: url, @@ -327,7 +336,7 @@ exports.testRelatedTab = function(test) { test.waitUntilDone(); let tab; - let { PageMod } = require("page-mod"); + let { PageMod } = require("sdk/page-mod"); let pageMod = new PageMod({ include: "about:*", onAttach: function(worker) { @@ -347,19 +356,42 @@ exports.testRelatedTab = function(test) { }; +exports.testWorksWithExistingTabs = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8," + encodeURI("Test unique document"); + let { PageMod } = require("sdk/page-mod"); + tabs.open({ + url: url, + onReady: function onReady(tab) { + let pageMod = new PageMod({ + include: url, + attachTo: ["existing", "top", "frame"], + onAttach: function(worker) { + test.assertEqual(tab, worker.tab, "A worker has been created on this existing tab"); + pageMod.destroy(); + tab.close(); + test.done(); + } + }); + } + }); + +}; + exports['test tab worker on message'] = function(test) { test.waitUntilDone(); - let { browserWindows } = require("windows"); - let tabs = require("tabs"); - let { PageMod } = require("page-mod"); + let { browserWindows } = require("sdk/windows"); + let tabs = require("sdk/tabs"); + let { PageMod } = require("sdk/page-mod"); - let url1 = "data:text/html,<title>tab1</title><h1>worker1.tab</h1>"; - let url2 = "data:text/html,<title>tab2</title><h1>worker2.tab</h1>"; + let url1 = "data:text/html;charset=utf-8,<title>tab1</title><h1>worker1.tab</h1>"; + let url2 = "data:text/html;charset=utf-8,<title>tab2</title><h1>worker2.tab</h1>"; let worker1 = null; let mod = PageMod({ - include: "data:text/html,*", + include: "data:text/html*", contentScriptWhen: "ready", contentScript: "self.postMessage('#1');", onAttach: function onAttach(worker) { @@ -395,7 +427,7 @@ exports.testAutomaticDestroy = function(test) { test.waitUntilDone(); let loader = Loader(module); - let pageMod = loader.require("page-mod").PageMod({ + let pageMod = loader.require("sdk/page-mod").PageMod({ include: "about:*", contentScriptWhen: "start", onAttach: function(w) { @@ -407,7 +439,7 @@ exports.testAutomaticDestroy = function(test) { loader.unload(); // Then create a second tab to ensure that it is correctly destroyed - let tabs = require("tabs"); + let tabs = require("sdk/tabs"); tabs.open({ url: "about:", onReady: function onReady(tab) { @@ -419,13 +451,203 @@ exports.testAutomaticDestroy = function(test) { } +exports['test attachment to tabs only'] = function(test) { + test.waitUntilDone(); + + let { PageMod } = require('sdk/page-mod'); + let openedTab = null; // Tab opened in openTabWithIframe() + let workerCount = 0; + + let mod = PageMod({ + include: 'data:text/html*', + contentScriptWhen: 'start', + contentScript: '', + onAttach: function onAttach(worker) { + if (worker.tab === openedTab) { + if (++workerCount == 3) { + test.pass('Succesfully applied to tab documents and its iframe'); + worker.destroy(); + mod.destroy(); + test.done(); + } + } + else { + test.fail('page-mod attached to a non-tab document'); + } + } + }); + + function openHiddenFrame() { + console.info('Open iframe in hidden window'); + let hiddenFrames = require('sdk/frame/hidden-frame'); + let hiddenFrame = hiddenFrames.add(hiddenFrames.HiddenFrame({ + onReady: function () { + let element = this.element; + element.addEventListener('DOMContentLoaded', function onload() { + element.removeEventListener('DOMContentLoaded', onload, false); + hiddenFrames.remove(hiddenFrame); + openToplevelWindow(); + }, false); + element.setAttribute('src', 'data:text/html;charset=utf-8,foo'); + } + })); + } + + function openToplevelWindow() { + console.info('Open toplevel window'); + let win = open('data:text/html;charset=utf-8,bar'); + win.addEventListener('DOMContentLoaded', function onload() { + win.removeEventListener('DOMContentLoaded', onload, false); + win.close(); + openBrowserIframe(); + }, false); + } + + function openBrowserIframe() { + console.info('Open iframe in browser window'); + let window = require('sdk/deprecated/window-utils').activeBrowserWindow; + let document = window.document; + let iframe = document.createElement('iframe'); + iframe.setAttribute('type', 'content'); + iframe.setAttribute('src', 'data:text/html;charset=utf-8,foobar'); + iframe.addEventListener('DOMContentLoaded', function onload() { + iframe.removeEventListener('DOMContentLoaded', onload, false); + iframe.parentNode.removeChild(iframe); + openTabWithIframes(); + }, false); + document.documentElement.appendChild(iframe); + } + + // Only these three documents will be accepted by the page-mod + function openTabWithIframes() { + console.info('Open iframes in a tab'); + let subContent = '<iframe src="data:text/html;charset=utf-8,sub frame" />' + let content = '<iframe src="data:text/html,' + + encodeURIComponent(subContent) + '" />'; + require('sdk/tabs').open({ + url: 'data:text/html;charset=utf-8,' + encodeURIComponent(content), + onOpen: function onOpen(tab) { + openedTab = tab; + } + }); + } + + openHiddenFrame(); +}; + +exports['test111 attachTo [top]'] = function(test) { + test.waitUntilDone(); + + let { PageMod } = require('sdk/page-mod'); + + let subContent = '<iframe src="data:text/html;charset=utf-8,sub frame" />' + let content = '<iframe src="data:text/html;charset=utf-8,' + + encodeURIComponent(subContent) + '" />'; + let topDocumentURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(content) + + let workerCount = 0; + + let mod = PageMod({ + include: 'data:text/html*', + contentScriptWhen: 'start', + contentScript: 'self.postMessage(document.location.href);', + attachTo: ['top'], + onAttach: function onAttach(worker) { + if (++workerCount == 1) { + worker.on('message', function (href) { + test.assertEqual(href, topDocumentURL, + "worker on top level document only"); + worker.destroy(); + mod.destroy(); + test.done(); + }); + } + else { + test.fail('page-mod attached to a non-top document'); + } + } + }); + + require('sdk/tabs').open(topDocumentURL); +}; + +exports['test111 attachTo [frame]'] = function(test) { + test.waitUntilDone(); + + let { PageMod } = require('sdk/page-mod'); + + let subFrameURL = 'data:text/html;charset=utf-8,subframe'; + let subContent = '<iframe src="' + subFrameURL + '" />'; + let frameURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(subContent); + let content = '<iframe src="' + frameURL + '" />'; + let topDocumentURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(content) + + let workerCount = 0, messageCount = 0; + + function onMessage(href) { + if (href == frameURL) + test.pass("worker on first frame"); + else if (href == subFrameURL) + test.pass("worker on second frame"); + else + test.fail("worker on unexpected document: " + href); + this.destroy(); + if (++messageCount == 2) { + mod.destroy(); + test.done(); + } + } + let mod = PageMod({ + include: 'data:text/html*', + contentScriptWhen: 'start', + contentScript: 'self.postMessage(document.location.href);', + attachTo: ['frame'], + onAttach: function onAttach(worker) { + if (++workerCount <= 2) { + worker.on('message', onMessage); + } + else { + test.fail('page-mod attached to a non-frame document'); + } + } + }); + + require('sdk/tabs').open(topDocumentURL); +}; + +exports.testContentScriptOptionsOption = function(test) { + test.waitUntilDone(); + + let callbackDone = null; + testPageMod(test, "about:", [{ + include: "about:*", + contentScript: "self.postMessage( [typeof self.options.d, self.options] );", + contentScriptWhen: "end", + contentScriptOptions: {a: true, b: [1,2,3], c: "string", d: function(){ return 'test'}}, + onAttach: function(worker) { + worker.on('message', function(msg) { + test.assertEqual( msg[0], 'undefined', 'functions are stripped from contentScriptOptions' ); + test.assertEqual( typeof msg[1], 'object', 'object as contentScriptOptions' ); + test.assertEqual( msg[1].a, true, 'boolean in contentScriptOptions' ); + test.assertEqual( msg[1].b.join(), '1,2,3', 'array and numbers in contentScriptOptions' ); + test.assertEqual( msg[1].c, 'string', 'string in contentScriptOptions' ); + callbackDone(); + }); + } + }], + function(win, done) { + callbackDone = done; + } + ); +}; + exports.testPageModCss = function(test) { let [pageMod] = testPageMod(test, - 'data:text/html,<div style="background: silver">css test</div>', [{ + 'data:text/html;charset=utf-8,<div style="background: silver">css test</div>', [{ include: "data:*", contentStyle: "div { height: 100px; }", contentStyleFile: - require("self").data.url("pagemod-css-include-file.css") + require("sdk/self").data.url("pagemod-css-include-file.css") }], function(win, done) { let div = win.document.querySelector("div"); @@ -446,16 +668,16 @@ exports.testPageModCss = function(test) { exports.testPageModCssList = function(test) { let [pageMod] = testPageMod(test, - 'data:text/html,<div style="width:320px; max-width: 480px!important">css test</div>', [{ + 'data:text/html;charset=utf-8,<div style="width:320px; max-width: 480px!important">css test</div>', [{ include: "data:*", contentStyleFile: [ // Highlight evaluation order in this list - "data:text/css,div { border: 1px solid black; }", - "data:text/css,div { border: 10px solid black; }", + "data:text/css;charset=utf-8,div { border: 1px solid black; }", + "data:text/css;charset=utf-8,div { border: 10px solid black; }", // Highlight evaluation order between contentStylesheet & contentStylesheetFile - "data:text/css,div { height: 1000px; }", + "data:text/cs;charset=utf-8s,div { height: 1000px; }", // Highlight precedence between the author and user style sheet - "data:text/css,div { width: 200px; max-width: 640px!important}", + "data:text/css;charset=utf-8,div { width: 200px; max-width: 640px!important}", ], contentStyle: [ "div { height: 10px; }", @@ -497,7 +719,7 @@ exports.testPageModCssList = function(test) { exports.testPageModCssDestroy = function(test) { let [pageMod] = testPageMod(test, - 'data:text/html,<div style="width:200px">css test</div>', [{ + 'data:text/html;charset=utf-8,<div style="width:200px">css test</div>', [{ include: "data:*", contentStyle: "div { width: 100px!important; }" }], @@ -524,3 +746,173 @@ exports.testPageModCssDestroy = function(test) { } ); }; + +exports.testPageModCssAutomaticDestroy = function(test) { + test.waitUntilDone(); + let loader = Loader(module); + + let pageMod = loader.require("page-mod").PageMod({ + include: "data:*", + contentStyle: "div { width: 100px!important; }" + }); + + tabs.open({ + url: "data:text/html;charset=utf-8,<div style='width:200px'>css test</div>", + + onReady: function onReady(tab) { + let browserWindow = windowUtils.activeBrowserWindow; + let win = getTabContentWindow(getActiveTab(browserWindow)); + + let div = win.document.querySelector("div"), + style = win.getComputedStyle(div); + + test.assertEqual( + style.width, + "100px", + "PageMod contentStyle worked" + ); + + loader.unload(); + + test.assertEqual( + style.width, + "200px", + "PageMod contentStyle is removed after loader's unload" + ); + + tab.close(); + test.done(); + } + }); +}; + + +exports.testPageModTimeout = function(test) { + test.waitUntilDone(); + let tab = null + let loader = Loader(module); + let { PageMod } = loader.require("page-mod"); + + let mod = PageMod({ + include: "data:*", + contentScript: Isolate(function() { + var id = setTimeout(function() { + self.port.emit("fired", id) + }, 10) + self.port.emit("scheduled", id); + }), + onAttach: function(worker) { + worker.port.on("scheduled", function(id) { + test.pass("timer was scheduled") + worker.port.on("fired", function(data) { + test.assertEqual(id, data, "timer was fired") + tab.close() + worker.destroy() + loader.unload() + test.done() + }) + }) + } + }); + + tabs.open({ + url: "data:text/html;charset=utf-8,timeout", + onReady: function($) { tab = $ } + }) +} + + +exports.testPageModcancelTimeout = function(test) { + test.waitUntilDone(); + let tab = null + let loader = Loader(module); + let { PageMod } = loader.require("page-mod"); + + let mod = PageMod({ + include: "data:*", + contentScript: Isolate(function() { + var id1 = setTimeout(function() { + self.port.emit("failed") + }, 10) + var id2 = setTimeout(function() { + self.port.emit("timeout") + }, 100) + clearTimeout(id1) + }), + onAttach: function(worker) { + worker.port.on("failed", function() { + test.fail("cancelled timeout fired") + }) + worker.port.on("timeout", function(id) { + test.pass("timer was scheduled") + tab.close() + worker.destroy() + loader.unload() + test.done() + }) + } + }); + + tabs.open({ + url: "data:text/html;charset=utf-8,cancell timeout", + onReady: function($) { tab = $ } + }) +} + +exports.testBug803529 = function(test) { + test.waitUntilDone(); + + let subIFrame = '<iframe src="data:text/html;charset=utf-8,sub frame" />' + let iFrame = '<iframe src="data:text/html;charset=utf-8,' + encodeURIComponent(subIFrame) + '" />'; + let url = 'data:text/html;charset=utf-8,' + encodeURIComponent(iFrame) + + let counter = 0; + let tab = openTab(getMostRecentBrowserWindow(), url); + let window = getTabContentWindow(tab); + + function wait4Iframes() { + if (window.document.readyState != "complete" || + getFrames(window).length != 2) { + return; + } + + let pagemod = pageMod.PageMod({ + include: ["*", "data:*"], + attachTo: ["existing", "frame"], + contentScriptWhen: 'ready', + onAttach: function(mod) { + if (++counter != 2) return; + test.pass('page mod attached to iframe'); + timer.setTimeout(function() { + pagemod.destroy(); + closeTab(tab); + test.done(); + }, 0); + } + }); + } + + window.addEventListener("load", wait4Iframes, false); +}; + +exports.testIFramePostMessage = function(test) { + test.waitUntilDone(); + + tabs.open({ + url: data.url("test-iframe.html"), + onReady: function(tab) { + var worker = tab.attach({ + contentScriptFile: data.url('test-iframe.js'), + contentScript: ' var iframePath = \'' + data.url('test-iframe-postmessage.html') + '\'', + onMessage: function(msg) { + test.assertEqual(msg.first, 'a string'); + test.assert(msg.second[1], "array"); + test.assertEqual(typeof msg.third, 'object'); + + worker.destroy(); + tab.close(function() test.done()); + } + }); + } + }); +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-worker.js b/tools/addon-sdk-1.12/test/test-page-worker.js index 5fc3bec..469c19b 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-page-worker.js +++ b/tools/addon-sdk-1.12/test/test-page-worker.js @@ -3,10 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ let tests = {}, Pages, Page; -const { Loader } = require('./helpers'); +const { Loader } = require('sdk/test/loader'); const ERR_DESTROYED = - "The page has been destroyed and can no longer be used."; + "Couldn't find the worker to receive this message. " + + "The script may not be initialized yet, or may already have been unloaded."; tests.testSimplePageCreation = function(test) { test.waitUntilDone(); @@ -23,16 +24,16 @@ tests.testSimplePageCreation = function(test) { }); } -/* - * Tests that we can't be tricked by document overloads as we have access - * to wrapped nodes +/* + * Tests that we can't be tricked by document overloads as we have access + * to wrapped nodes */ tests.testWrappedDOM = function(test) { test.waitUntilDone(); let page = Page({ allow: { script: true }, - contentURL: "data:text/html,<script>document.getElementById=3;window.scrollTo=3;</script>", + contentURL: "data:text/html;charset=utf-8,<script>document.getElementById=3;window.scrollTo=3;</script>", contentScript: "window.addEventListener('load', function () " + "self.postMessage([typeof(document.getElementById), " + "typeof(window.scrollTo)]), true)", @@ -58,7 +59,7 @@ tests.testUnwrappedDOM = function(test) { let page = Page({ allow: { script: true }, - contentURL: "data:text/html,<script>document.getElementById=3;window.scrollTo=3;</script>", + contentURL: "data:text/html;charset=utf-8,<script>document.getElementById=3;window.scrollTo=3;</script>", contentScript: "window.addEventListener('load', function () " + "self.postMessage([typeof(unsafeWindow.document.getElementById), " + "typeof(unsafeWindow.scrollTo)]), true)", @@ -94,8 +95,8 @@ tests.testConstructorAndDestructor = function(test) { test.waitUntilDone(); let loader = Loader(module); - let Pages = loader.require("page-worker"); - let global = loader.sandbox("page-worker"); + let Pages = loader.require("sdk/page-worker"); + let global = loader.sandbox("sdk/page-worker"); let pagesReady = 0; @@ -131,7 +132,7 @@ tests.testAutoDestructor = function(test) { test.waitUntilDone(); let loader = Loader(module); - let Pages = loader.require("page-worker"); + let Pages = loader.require("sdk/page-worker"); let page = Pages.Page({ contentScript: "self.postMessage('')", @@ -162,7 +163,7 @@ tests.testValidateOptions = function(test) { tests.testContentAndAllowGettersAndSetters = function(test) { test.waitUntilDone(); - let content = "data:text/html,<script>window.localStorage.allowScript=3;</script>"; + let content = "data:text/html;charset=utf-8,<script>window.localStorage.allowScript=3;</script>"; let page = Page({ contentURL: content, contentScript: "self.postMessage(window.localStorage.allowScript)", @@ -178,8 +179,8 @@ tests.testContentAndAllowGettersAndSetters = function(test) { page.removeListener('message', step0); page.on('message', step1); page.allow = { script: false }; - page.contentURL = content = - "data:text/html,<script>window.localStorage.allowScript='f'</script>"; + page.contentURL = content = + "data:text/html;charset=utf-8,<script>window.localStorage.allowScript='f'</script>"; } function step1(message) { @@ -190,7 +191,7 @@ tests.testContentAndAllowGettersAndSetters = function(test) { page.on('message', step2); page.allow = { script: true }; page.contentURL = content = - "data:text/html,<script>window.localStorage.allowScript='g'</script>"; + "data:text/html;charset=utf-8,<script>window.localStorage.allowScript='g'</script>"; } function step2(message) { @@ -200,8 +201,8 @@ tests.testContentAndAllowGettersAndSetters = function(test) { page.removeListener('message', step2); page.on('message', step3); page.allow.script = false; - page.contentURL = content = - "data:text/html,<script>window.localStorage.allowScript=3</script>"; + page.contentURL = content = + "data:text/html;charset=utf-8,<script>window.localStorage.allowScript=3</script>"; } function step3(message) { @@ -211,8 +212,8 @@ tests.testContentAndAllowGettersAndSetters = function(test) { page.removeListener('message', step3); page.on('message', step4); page.allow.script = true; - page.contentURL = content = - "data:text/html,<script>window.localStorage.allowScript=4</script>"; + page.contentURL = content = + "data:text/html;charset=utf-8,<script>window.localStorage.allowScript=4</script>"; } function step4(message) { @@ -264,8 +265,8 @@ tests.testLoadContentPage = function(test) { // and the rest of whose items are arguments to pass it. test[message.shift()].apply(test, message); }, - contentURL: require("self").data.url("test-page-worker.html"), - contentScriptFile: require("self").data.url("test-page-worker.js"), + contentURL: require("sdk/self").data.url("test-page-worker.html"), + contentScriptFile: require("sdk/self").data.url("test-page-worker.js"), contentScriptWhen: "ready" }); @@ -280,7 +281,7 @@ tests.testAllowScriptDefault = function(test) { test.assert(message, "Script is allowed to run by default."); test.done(); }, - contentURL: "data:text/html,<script>document.documentElement.setAttribute('foo', 3);</script>", + contentURL: "data:text/html;charset=utf-8,<script>document.documentElement.setAttribute('foo', 3);</script>", contentScript: "self.postMessage(document.documentElement.getAttribute('foo'))", contentScriptWhen: "ready" }); @@ -296,7 +297,7 @@ tests.testAllowScript = function(test) { test.done(); }, allow: { script: true }, - contentURL: "data:text/html,<script>document.documentElement.setAttribute('foo', 3);</script>", + contentURL: "data:text/html;charset=utf-8,<script>document.documentElement.setAttribute('foo', 3);</script>", contentScript: "self.postMessage(document.documentElement.hasAttribute('foo') && " + " document.documentElement.getAttribute('foo') == 3)", contentScriptWhen: "ready" @@ -306,7 +307,7 @@ tests.testAllowScript = function(test) { tests.testPingPong = function(test) { test.waitUntilDone(); let page = Page({ - contentURL: 'data:text/html,ping-pong', + contentURL: 'data:text/html;charset=utf-8,ping-pong', contentScript: 'self.on("message", function(message) self.postMessage("pong"));' + 'self.postMessage("ready");', onMessage: function(message) { @@ -328,6 +329,23 @@ tests.testMultipleDestroys = function(test) { test.pass("Multiple destroys should not cause an error"); }; +exports.testContentScriptOptionsOption = function(test) { + test.waitUntilDone(); + + let page = new Page({ + contentScript: "self.postMessage( [typeof self.options.d, self.options] );", + contentScriptWhen: "end", + contentScriptOptions: {a: true, b: [1,2,3], c: "string", d: function(){ return 'test'}}, + onMessage: function(msg) { + test.assertEqual( msg[0], 'undefined', 'functions are stripped from contentScriptOptions' ); + test.assertEqual( typeof msg[1], 'object', 'object as contentScriptOptions' ); + test.assertEqual( msg[1].a, true, 'boolean in contentScriptOptions' ); + test.assertEqual( msg[1].b.join(), '1,2,3', 'array and numbers in contentScriptOptions' ); + test.assertEqual( msg[1].c, 'string', 'string in contentScriptOptions' ); + test.done(); + } + }); +}; function isDestroyed(page) { try { @@ -343,7 +361,7 @@ function isDestroyed(page) { let pageWorkerSupported = true; try { - Pages = require("page-worker"); + Pages = require("sdk/page-worker"); Page = Pages.Page; } catch (ex if ex.message == [ diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-panel.js b/tools/addon-sdk-1.12/test/test-panel.js index e05400e..bdce83d 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-panel.js +++ b/tools/addon-sdk-1.12/test/test-panel.js @@ -3,9 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ let { Cc, Ci } = require("chrome"); -let panels = require('panel'); +let panels = require('sdk/panel'); let tests = {}, panels, Panel; -const { Loader } = require('./helpers'); +const { Loader } = require('sdk/test/loader'); +const timer = require("sdk/timers"); tests.testPanel = function(test) { test.waitUntilDone(); @@ -97,12 +98,12 @@ tests.testDocumentReload = function(test) { "</script>"; let messageCount = 0; let panel = Panel({ - contentURL: "data:text/html," + encodeURIComponent(content), + contentURL: "data:text/html;charset=utf-8," + encodeURIComponent(content), contentScript: "self.postMessage(window.location.href)", onMessage: function (message) { messageCount++; if (messageCount == 1) { - test.assertMatches(message, /data:text\/html,/, "First document had a content script"); + test.assertMatches(message, /data:text\/html/, "First document had a content script"); } else if (messageCount == 2) { test.assertEqual(message, "about:blank", "Second document too"); @@ -139,7 +140,7 @@ tests.testParentResizeHack = function(test) { "</script>" + "Try to resize browser window"; let panel = Panel({ - contentURL: "data:text/html," + encodeURIComponent(content), + contentURL: "data:text/html;charset=utf-8," + encodeURIComponent(content), contentScript: "self.on('message', function(message){" + " if (message=='resize') " + " unsafeWindow.contentResize();" + @@ -150,7 +151,7 @@ tests.testParentResizeHack = function(test) { }, onShow: function () { panel.postMessage('resize'); - require("timer").setTimeout(function () { + timer.setTimeout(function () { test.assertEqual(previousWidth,browserWindow.outerWidth,"Size doesn't change by calling resizeTo/By/..."); test.assertEqual(previousHeight,browserWindow.outerHeight,"Size doesn't change by calling resizeTo/By/..."); panel.destroy(); @@ -178,8 +179,8 @@ tests.testResizePanel = function(test) { let browserWindow = Cc["@mozilla.org/appshell/window-mediator;1"]. getService(Ci.nsIWindowMediator). getMostRecentWindow("navigator:browser"); - - + + function onFocus() { browserWindow.removeEventListener("focus", onFocus, true); @@ -259,7 +260,7 @@ tests.testAnchorAndArrow = function(test) { let count = 0; function newPanel(tab, anchor) { let panel = panels.Panel({ - contentURL: "data:text/html,<html><body style='padding: 0; margin: 0; " + + contentURL: "data:text/html;charset=utf-8,<html><body style='padding: 0; margin: 0; " + "background: gray; text-align: center;'>Anchor: " + anchor.id + "</body></html>", width: 200, @@ -277,10 +278,10 @@ tests.testAnchorAndArrow = function(test) { }); panel.show(anchor); } - - let tabs= require("tabs"); - let url = 'data:text/html,' + - '<html><head><title>foo</title></head><body>' + + + let tabs= require("sdk/tabs"); + let url = 'data:text/html;charset=utf-8,' + + '<html><head><title>foo</title></head><body>' + '<style>div {background: gray; position: absolute; width: 300px; ' + 'border: 2px solid black;}</style>' + '<div id="tl" style="top: 0px; left: 0px;">Top Left</div>' + @@ -288,7 +289,7 @@ tests.testAnchorAndArrow = function(test) { '<div id="bl" style="bottom: 0px; left: 0px;">Bottom Left</div>' + '<div id="br" style="bottom: 0px; right: 0px;">Bottom right</div>' + '</body></html>'; - + tabs.open({ url: url, onReady: function(tab) { @@ -304,9 +305,9 @@ tests.testAnchorAndArrow = function(test) { newPanel(tab, anchor); } }); - - - + + + }; tests.testPanelTextColor = function(test) { @@ -314,7 +315,7 @@ tests.testPanelTextColor = function(test) { let html = "<html><head><style>body {color: yellow}</style></head>" + "<body><p>Foo</p></body></html>"; let panel = Panel({ - contentURL: "data:text/html," + encodeURI(html), + contentURL: "data:text/html;charset=utf-8," + encodeURI(html), contentScript: "self.port.emit('color', " + "window.getComputedStyle(document.body.firstChild, null). " + " getPropertyValue('color'));" @@ -363,7 +364,7 @@ function makeEventOrderTest(options) { panel.on(event, function() { test.assertEqual(event, expectedEvents.shift()); if (cb) - require("timer").setTimeout(cb, 1); + timer.setTimeout(cb, 1); }); return {then: expect}; } @@ -375,14 +376,14 @@ function makeEventOrderTest(options) { tests.testAutomaticDestroy = function(test) { let loader = Loader(module); - let panel = loader.require("panel").Panel({ + let panel = loader.require("sdk/panel").Panel({ contentURL: "about:buildconfig", - contentScript: + contentScript: "self.port.on('event', function() self.port.emit('event-back'));" }); - + loader.unload(); - + panel.port.on("event-back", function () { test.fail("Panel should have been destroyed on module unload"); }); @@ -425,7 +426,7 @@ tests.testContentURLOption = function(test) { "contentURL is the string to which it was set."); } - let dataURL = "data:text/html," + encodeURIComponent(HTML_CONTENT); + let dataURL = "data:text/html;charset=utf-8," + encodeURIComponent(HTML_CONTENT); let (panel = Panel({ contentURL: dataURL })) { test.pass("contentURL accepts a data: URL."); } @@ -440,10 +441,29 @@ tests.testContentURLOption = function(test) { "Panel throws an exception if contentURL is not a URL."); }; +exports.testContentScriptOptionsOption = function(test) { + test.waitUntilDone(); + + let loader = Loader(module); + let panel = loader.require("sdk/panel").Panel({ + contentScript: "self.postMessage( [typeof self.options.d, self.options] );", + contentScriptWhen: "end", + contentScriptOptions: {a: true, b: [1,2,3], c: "string", d: function(){ return 'test'}}, + onMessage: function(msg) { + test.assertEqual( msg[0], 'undefined', 'functions are stripped from contentScriptOptions' ); + test.assertEqual( typeof msg[1], 'object', 'object as contentScriptOptions' ); + test.assertEqual( msg[1].a, true, 'boolean in contentScriptOptions' ); + test.assertEqual( msg[1].b.join(), '1,2,3', 'array and numbers in contentScriptOptions' ); + test.assertEqual( msg[1].c, 'string', 'string in contentScriptOptions' ); + test.done(); + } + }); +}; + let panelSupported = true; try { - panels = require("panel"); + panels = require("sdk/panel"); Panel = panels.Panel; } catch(ex if ex.message == [ diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-passwords-utils.js b/tools/addon-sdk-1.12/test/test-passwords-utils.js index ab758ed..3773090 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-passwords-utils.js +++ b/tools/addon-sdk-1.12/test/test-passwords-utils.js @@ -4,7 +4,7 @@ "use strict"; -const { store, search, remove } = require("passwords/utils"); +const { store, search, remove } = require("sdk/passwords/utils"); exports["test store requires `password` field"] = function(assert) { assert.throws(function() { diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-passwords.js b/tools/addon-sdk-1.12/test/test-passwords.js index bfb137a..04e2181 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-passwords.js +++ b/tools/addon-sdk-1.12/test/test-passwords.js @@ -1,10 +1,9 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -"use strict"; - -const { store, search, remove } = require("passwords"); +const { store, search, remove } = require("sdk/passwords"); exports["test store requires `password` field"] = function(assert, done) { store({ diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-plain-text-console.js b/tools/addon-sdk-1.12/test/test-plain-text-console.js index 40fb519..ce41b07 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-plain-text-console.js +++ b/tools/addon-sdk-1.12/test/test-plain-text-console.js @@ -13,56 +13,56 @@ exports.testPlainTextConsole = function(test) { return last; } - var Console = require("plain-text-console").PlainTextConsole; + var Console = require("sdk/console/plain-text").PlainTextConsole; var con = new Console(print); test.pass("PlainTextConsole instantiates"); con.log('testing', 1, [2, 3, 4]); - test.assertEqual(lastPrint(), "info: testing 1 2,3,4\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing 1 2,3,4\n", "PlainTextConsole.log() must work."); con.info('testing', 1, [2, 3, 4]); - test.assertEqual(lastPrint(), "info: testing 1 2,3,4\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing 1 2,3,4\n", "PlainTextConsole.info() must work."); con.warn('testing', 1, [2, 3, 4]); - test.assertEqual(lastPrint(), "warning: testing 1 2,3,4\n", + test.assertEqual(lastPrint(), "warning: " + require("sdk/self").name + ": testing 1 2,3,4\n", "PlainTextConsole.warn() must work."); con.error('testing', 1, [2, 3, 4]); - test.assertEqual(lastPrint(), "error: testing 1 2,3,4\n", + test.assertEqual(lastPrint(), "error: " + require("sdk/self").name + ": testing 1 2,3,4\n", "PlainTextConsole.error() must work."); con.debug('testing', 1, [2, 3, 4]); - test.assertEqual(lastPrint(), "debug: testing 1 2,3,4\n", + test.assertEqual(lastPrint(), "debug: " + require("sdk/self").name + ": testing 1 2,3,4\n", "PlainTextConsole.debug() must work."); con.log('testing', undefined); - test.assertEqual(lastPrint(), "info: testing undefined\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing undefined\n", "PlainTextConsole.log() must stringify undefined."); con.log('testing', null); - test.assertEqual(lastPrint(), "info: testing null\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing null\n", "PlainTextConsole.log() must stringify null."); con.log("testing", { toString: function() "obj.toString()" }); - test.assertEqual(lastPrint(), "info: testing obj.toString()\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing obj.toString()\n", "PlainTextConsole.log() must stringify custom toString."); con.log("testing", { toString: function() { throw "fail!"; } }); - test.assertEqual(lastPrint(), "info: testing <toString() error>\n", + test.assertEqual(lastPrint(), "info: " + require("sdk/self").name + ": testing <toString() error>\n", "PlainTextConsole.log() must stringify custom bad toString."); con.exception(new Error("blah")); var tbLines = prints[0].split("\n"); - test.assertEqual(tbLines[0], "error: An exception occurred."); + test.assertEqual(tbLines[0], "error: " + require("sdk/self").name + ": An exception occurred."); test.assertEqual(tbLines[1], "Traceback (most recent call last):"); test.assertEqual(tbLines.slice(-2)[0], "Error: blah"); prints = []; con.trace(); tbLines = prints[0].split("\n"); - test.assertEqual(tbLines[0], "info: Traceback (most recent call last):"); + test.assertEqual(tbLines[0], "info: " + require("sdk/self").name + ": Traceback (most recent call last):"); test.assertEqual(tbLines.slice(-2)[0].trim(), "con.trace();"); }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-preferences-service.js b/tools/addon-sdk-1.12/test/test-preferences-service.js index 857357e..89cb2f5 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-preferences-service.js +++ b/tools/addon-sdk-1.12/test/test-preferences-service.js @@ -1,11 +1,15 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; -const prefs = require("preferences-service"); +const prefs = require("sdk/preferences/service"); +const Branch = prefs.Branch; const { Cc, Ci, Cu } = require("chrome"); const BundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService); +const specialChars = "!@#$%^&*()_-=+[]{}~`\'\"<>,./?;:"; + exports.testReset = function(test) { prefs.reset("test_reset_pref"); test.assertEqual(prefs.has("test_reset_pref"), false); @@ -13,14 +17,15 @@ exports.testReset = function(test) { prefs.set("test_reset_pref", 5); test.assertEqual(prefs.has("test_reset_pref"), true); test.assertEqual(prefs.isSet("test_reset_pref"), true); + test.assertEqual(prefs.keys("test_reset_pref").toString(), "test_reset_pref"); }; exports.testGetAndSet = function(test) { let svc = Cc["@mozilla.org/preferences-service;1"]. getService(Ci.nsIPrefService). getBranch(null); - svc.setCharPref("test_get_string_pref", "a normal string"); - test.assertEqual(prefs.get("test_get_string_pref"), "a normal string", + svc.setCharPref("test_set_get_pref", "a normal string"); + test.assertEqual(prefs.get("test_set_get_pref"), "a normal string", "preferences-service should read from " + "application-wide preferences service"); @@ -28,6 +33,10 @@ exports.testGetAndSet = function(test) { test.assertEqual(prefs.get("test_set_get_pref.integer"), 1, "set/get integer preference should work"); + test.assertEqual( + prefs.keys("test_set_get_pref").sort().toString(), + ["test_set_get_pref.integer","test_set_get_pref"].sort().toString()); + prefs.set("test_set_get_number_pref", 42); test.assertRaises( function() { prefs.set("test_set_get_number_pref", 3.14159); }, @@ -91,6 +100,16 @@ exports.testGetAndSet = function(test) { }); }; +exports.testPrefClass = function(test) { + var branch = Branch("test_foo"); + + test.assertEqual(branch.test, undefined, "test_foo.test is undefined"); + branch.test = true; + test.assertEqual(branch.test, true, "test_foo.test is true"); + delete branch.test; + test.assertEqual(branch.test, undefined, "test_foo.test is undefined"); +}; + exports.testGetSetLocalized = function(test) { let prefName = "general.useragent.locale"; @@ -110,3 +129,15 @@ exports.testGetSetLocalized = function(test) { // Undo our modification prefs.reset(prefName); } + +// TEST: setting and getting preferences with special characters work +exports.testSpecialChars = function(test) { + let chars = specialChars.split(''); + const ROOT = "test."; + + chars.forEach(function(char) { + let rand = Math.random() + ""; + prefs.set(ROOT+char, rand); + test.assertEqual(prefs.get(ROOT+char), rand, "setting pref with a name that is a special char, " + char + ", worked!"); + }); +}; diff --git a/tools/addon-sdk-1.12/test/test-preferences-target.js b/tools/addon-sdk-1.12/test/test-preferences-target.js new file mode 100644 index 0000000..b2bb077 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-preferences-target.js @@ -0,0 +1,42 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { PrefsTarget } = require('sdk/preferences/event-target'); +const { get, set, reset } = require('sdk/preferences/service'); +const { Loader } = require('sdk/test/loader'); +const { setTimeout } = require('sdk/timers'); + +const root = PrefsTarget(); + +exports.testPrefsTarget = function(test) { + test.waitUntilDone(); + + let loader = Loader(module); + let pt = loader.require('sdk/preferences/event-target').PrefsTarget({}); + let name = 'test'; + + test.assertEqual(get(name, ''), '', 'test pref is blank'); + + pt.once(name, function() { + test.assertEqual(pt.prefs[name], 2, 'test pref is 2'); + + pt.once(name, function() { + test.fail('should not have heard a pref change'); + }); + loader.unload(); + root.once(name, function() { + test.pass('test pref was changed'); + reset(name); + + // NOTE: using setTimeout to make sure that the other listener had + // a chance to fail + // end test + setTimeout(function() test.done()); + }); + set(name, 3); + }); + + pt.prefs[name] = 2; +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-private-browsing.js b/tools/addon-sdk-1.12/test/test-private-browsing.js index 1d60f6b..de73892 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-private-browsing.js +++ b/tools/addon-sdk-1.12/test/test-private-browsing.js @@ -1,20 +1,20 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; -let pb = require("private-browsing"); -let {Cc,Ci} = require("chrome"); -const { Loader } = require('./helpers'); +let { Cc,Ci } = require("chrome"); +const timer = require("sdk/timers"); +const { LoaderWithHookedConsole, pb } = require("private-browsing-helper"); let pbService; // Currently, only Firefox implements the private browsing service. -if (require("xul-app").is("Firefox")) { +if (require("sdk/system/xul-app").is("Firefox")) { pbService = Cc["@mozilla.org/privatebrowsing;1"]. getService(Ci.nsIPrivateBrowsingService); } if (pbService) { - // tests that isActive has the same value as the private browsing service // expects exports.testGetIsActive = function (test) { @@ -73,12 +73,12 @@ if (pbService) { pb.activate(); pb.deactivate(); }; - + exports.testAutomaticUnload = function(test) { test.waitUntilDone(); // Create another private browsing instance and unload it - let loader = Loader(module); - let pb2 = loader.require("private-browsing"); + let { loader, errors } = LoaderWithHookedConsole(); + let pb2 = loader.require("sdk/private-browsing"); let called = false; pb2.on("start", function onStart() { called = true; @@ -90,7 +90,7 @@ if (pbService) { // is correctly destroyed pb.activate(); pb.once("start", function onStart() { - require("timer").setTimeout(function () { + timer.setTimeout(function () { test.assert(!called, "First private browsing instance is destroyed and inactive"); @@ -163,7 +163,7 @@ if (pbService) { }; exports["test activate private mode via handler"] = function(test) { - const tabs = require("tabs"); + const tabs = require("sdk/tabs"); test.waitUntilDone(); function onReady(tab) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-promise.js b/tools/addon-sdk-1.12/test/test-promise.js index fc7706f..744baeb 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-promise.js +++ b/tools/addon-sdk-1.12/test/test-promise.js @@ -5,7 +5,7 @@ 'use strict'; -var core = require('api-utils/promise'), +var core = require('sdk/core/promise'), defer = core.defer, resolve = core.resolve, reject = core.reject, promised = core.promised @@ -308,4 +308,20 @@ exports['test promised are greedy'] = function(assert, done) { done() } +exports['test arrays should not flatten'] = function(assert, done) { + var a = defer() + var b = defer() + + var combine = promised(function(str, arr) { + assert.equal(str, 'Hello', 'Array was not flattened') + assert.deepEqual(arr, [ 'my', 'friend' ]) + }) + + combine(a.promise, b.promise).then(done) + + + a.resolve('Hello') + b.resolve([ 'my', 'friend' ]) +} + require("test").run(exports) diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-querystring.js b/tools/addon-sdk-1.12/test/test-querystring.js index 30b2729..9c016cf 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-querystring.js +++ b/tools/addon-sdk-1.12/test/test-querystring.js @@ -22,7 +22,7 @@ "use strict"; // test using assert -var qs = require('api-utils/querystring'); +var qs = require('sdk/querystring'); // folding block, commented to pass gjslint // {{{ diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-registry.js b/tools/addon-sdk-1.12/test/test-registry.js index c5820fb..13c127b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-registry.js +++ b/tools/addon-sdk-1.12/test/test-registry.js @@ -6,7 +6,7 @@ exports['test:add'] = function(test) { function Class() {} - let fixture = require('utils/registry').Registry(Class); + let fixture = require('sdk/util/registry').Registry(Class); let isAddEmitted = false; fixture.on('add', function(item) { test.assert( @@ -30,7 +30,7 @@ exports['test:add'] = function(test) { exports['test:remove'] = function(test) { function Class() {} - let fixture = require('utils/registry').Registry(Class); + let fixture = require('sdk/util/registry').Registry(Class); fixture.on('remove', function(item) { test.assert( item instanceof Class, @@ -55,7 +55,7 @@ exports['test:remove'] = function(test) { exports['test:items'] = function(test) { function Class() {} - let fixture = require('utils/registry').Registry(Class), + let fixture = require('sdk/util/registry').Registry(Class), actual, times = 0; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-request.js b/tools/addon-sdk-1.12/test/test-request.js index 42425d7..8d81ae2 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-request.js +++ b/tools/addon-sdk-1.12/test/test-request.js @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { Request } = require("addon-kit/request"); -const { pathFor } = require("api-utils/system"); -const { startServerAsync } = require("api-utils/httpd"); -const file = require("api-utils/file"); +const { Request } = require("sdk/request"); +const { pathFor } = require("sdk/system"); +const { startServerAsync } = require("sdk/test/httpd"); +const file = require("sdk/io/file"); const basePath = pathFor("TmpD") const port = 8099; @@ -34,7 +34,7 @@ exports.testOptionsValidator = function(test) { exports.testContentValidator = function(test) { test.waitUntilDone(); Request({ - url: "data:text/html,response", + url: "data:text/html;charset=utf-8,response", content: { 'key1' : null, 'key2' : 'some value' }, onComplete: function(response) { test.assertEqual(response.text, "response?key1=null&key2=some+value"); @@ -315,12 +315,14 @@ function assertDeepEqual(test, obj1, obj2, msg) { return o1 == o2; let e = true; - for (let [key, val] in Iterator(o1)) { + for (let key in o1) { + let val = o1[key]; e = e && key in o2 && equal(o2[key], val); if (!e) break; } - for (let [key, val] in Iterator(o2)) { + for (let key in o2) { + let val = o2[key] e = e && key in o1 && equal(o1[key], val); if (!e) break; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-require.js b/tools/addon-sdk-1.12/test/test-require.js index 7508883..d7e790e 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-require.js +++ b/tools/addon-sdk-1.12/test/test-require.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const traceback = require("traceback"); +const traceback = require("sdk/console/traceback"); exports.test_no_args = function(test) { var passed = false; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-sandbox.js b/tools/addon-sdk-1.12/test/test-sandbox.js index fb7a1da..4f2de96 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-sandbox.js +++ b/tools/addon-sdk-1.12/test/test-sandbox.js @@ -2,7 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const { sandbox, load, evaluate } = require('api-utils/sandbox'); +const { sandbox, load, evaluate } = require('sdk/loader/sandbox'); +const xulApp = require("sdk/system/xul-app"); const fixturesURI = module.uri.split('test-sandbox.js')[0] + 'fixtures/'; @@ -19,9 +20,16 @@ exports['test basics'] = function(assert) { exports['test non-privileged'] = function(assert) { let fixture = sandbox('http://example.com'); - assert.throws(function() { - evaluate(fixture, 'Compo' + 'nents.utils'); - }, 'Access to components is restricted'); + if (xulApp.versionInRange(xulApp.platformVersion, "15.0a1", "18.*")) { + let rv = evaluate(fixture, 'Compo' + 'nents.utils'); + assert.equal(rv, undefined, + "Components's attributes are undefined in content sandboxes"); + } + else { + assert.throws(function() { + evaluate(fixture, 'Compo' + 'nents.utils'); + }, 'Access to components is restricted'); + } fixture.sandbox = sandbox; assert.throws(function() { evaluate(fixture, sandbox('http://foo.com')); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-selection.js b/tools/addon-sdk-1.12/test/test-selection.js index 06feb7e..9985ca4 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-selection.js +++ b/tools/addon-sdk-1.12/test/test-selection.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -let timer = require("timer"); +let timer = require("sdk/timers"); let {Cc,Ci} = require("chrome"); // Arbitrary delay needed to avoid weird behavior. @@ -34,8 +34,8 @@ function selectTextarea(window, from, to) { } function primeTestCase(html, test, callback) { - let tabBrowser = require("tab-browser"); - let dataURL = "data:text/html," + encodeURI(html); + let tabBrowser = require("sdk/deprecated/tab-browser"); + let dataURL = "data:text/html;charset=utf-8," + encodeURI(html); let tracker = tabBrowser.whenContentLoaded( function(window) { if (window.document.location.href != dataURL) @@ -60,7 +60,7 @@ const HTML_SINGLE = '<html><body>' + DIV1 + '</body></html>'; // Tests of contiguous exports.testContiguousMultiple = function testContiguousMultiple(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_MULTIPLE, test, function(window, test) { selectAllDivs(window); test.assertEqual(selection.isContiguous, false, @@ -71,7 +71,7 @@ exports.testContiguousMultiple = function testContiguousMultiple(test) { }; exports.testContiguousSingle = function testContiguousSingle(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { selectAllDivs(window); test.assertEqual(selection.isContiguous, true, @@ -83,7 +83,7 @@ exports.testContiguousSingle = function testContiguousSingle(test) { exports.testContiguousWithoutSelection = function testContiguousWithoutSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { test.assertEqual(selection.isContiguous, false, "selection.isContiguous without selection works."); @@ -96,7 +96,7 @@ exports.testContiguousWithoutSelection = * Test that setting the contiguous property has no effect. */ /*exports.testSetContiguous = function testSetContiguous(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_MULTIPLE, test, function(window, test) { selectAllDivs(window); try { @@ -116,7 +116,7 @@ exports.testContiguousWithoutSelection = // HTML tests exports.testGetHTMLSingleSelection = function testGetHTMLSingleSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { selectAllDivs(window); test.assertEqual(selection.html, DIV1, "get html selection works"); @@ -131,7 +131,7 @@ exports.testGetHTMLSingleSelection = function testGetHTMLSingleSelection(test) { the appropriate order. In the meantime, add a comment to that effect here */ exports.testGetHTMLMultipleSelection = function testGetHTMLMultipleSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_MULTIPLE, test, function(window, test) { selectAllDivs(window); let assertions = false; @@ -148,7 +148,7 @@ exports.testGetHTMLMultipleSelection = }; exports.testGetHTMLNull = function testGetHTMLNull(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { test.assertEqual(selection.html, null, "get html null works"); }); @@ -157,7 +157,7 @@ exports.testGetHTMLNull = function testGetHTMLNull(test) { }; exports.testGetHTMLWeird = function testGetHTMLWeird(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); // If the getter is used when there are contiguous selections, the first // selection should be returned primeTestCase(HTML_MULTIPLE, test, function(window, test) { @@ -170,7 +170,7 @@ exports.testGetHTMLWeird = function testGetHTMLWeird(test) { exports.testGetHTMLNullInTextareaSelection = function testGetHTMLNullInTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_FIELD, test, function(window, test) { selectTextarea(window); @@ -184,7 +184,7 @@ exports.testGetHTMLNullInTextareaSelection = const REPLACEMENT_HTML = "<b>Lorem ipsum dolor sit amet</b>"; exports.testSetHTMLSelection = function testSetHTMLSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { selectAllDivs(window); selection.html = REPLACEMENT_HTML; @@ -196,7 +196,7 @@ exports.testSetHTMLSelection = function testSetHTMLSelection(test) { }; exports.testSetHTMLException = function testSetHTMLException(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { try { selection.html = REPLACEMENT_HTML; @@ -221,7 +221,7 @@ const TEXT_FIELD = "<html><body><textarea>" + TEXT1 + "</textarea></body></html> exports.testSetHTMLinTextareaSelection = function testSetHTMLinTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_FIELD, test, function(window, test) { selectTextarea(window); @@ -240,7 +240,7 @@ exports.testSetHTMLinTextareaSelection = exports.testGetTextSingleSelection = function testGetTextSingleSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_SINGLE, test, function(window, test) { selectAllDivs(window); test.assertEqual(selection.text, TEXT1, "get text selection works"); @@ -251,7 +251,7 @@ exports.testGetTextSingleSelection = exports.testGetTextMultipleSelection = function testGetTextMultipleSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_MULTIPLE, test, function(window, test) { selectAllDivs(window); let assertions = false; @@ -268,7 +268,7 @@ exports.testGetTextMultipleSelection = }; exports.testGetTextNull = function testGetTextNull(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_SINGLE, test, function(window, test) { test.assertEqual(selection.text, null, "get text null works"); }); @@ -277,7 +277,7 @@ exports.testGetTextNull = function testGetTextNull(test) { }; exports.testGetTextWeird = function testGetTextWeird(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); // If the getter is used when there are contiguous selections, the first // selection should be returned primeTestCase(TEXT_MULTIPLE, test, function(window, test) { @@ -290,7 +290,7 @@ exports.testGetTextWeird = function testGetTextWeird(test) { exports.testGetTextNullInTextareaSelection = function testGetTextInTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_FIELD, test, function(window, test) { test.assertEqual(selection.text, null, "get text null in textarea works") @@ -301,7 +301,7 @@ exports.testGetTextNullInTextareaSelection = exports.testGetTextInTextareaSelection = function testGetTextInTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_FIELD, test, function(window, test) { selectTextarea(window); @@ -315,7 +315,7 @@ exports.testGetTextInTextareaSelection = const REPLACEMENT_TEXT = "Lorem ipsum dolor sit amet"; exports.testSetTextSelection = function testSetTextSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_SINGLE, test, function(window, test) { selectAllDivs(window); selection.text = REPLACEMENT_TEXT; @@ -326,7 +326,7 @@ exports.testSetTextSelection = function testSetTextSelection(test) { }; exports.testSetHTMLException = function testSetHTMLException(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_SINGLE, test, function(window, test) { try { selection.text = REPLACEMENT_TEXT; @@ -342,7 +342,7 @@ exports.testSetHTMLException = function testSetHTMLException(test) { exports.testSetTextInTextareaSelection = function testSetTextInTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(TEXT_FIELD, test, function(window, test) { selectTextarea(window); @@ -359,7 +359,7 @@ exports.testSetTextInTextareaSelection = // Iterator tests exports.testIterator = function testIterator(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); let selectionCount = 0; primeTestCase(TEXT_MULTIPLE, test, function(window, test) { selectAllDivs(window); @@ -373,7 +373,7 @@ exports.testIterator = function testIterator(test) { exports.testIteratorWithTextareaSelection = function testIteratorWithTextareaSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); let selectionCount = 0; primeTestCase(TEXT_FIELD, test, function(window, test) { @@ -392,7 +392,7 @@ exports.testIteratorWithTextareaSelection = /* function sendSelectionSetEvent(window) { - const Ci = Components.interfaces; + const Ci = Components['interfaces']; let utils = window.QueryInterface(Ci.nsIInterfaceRequestor). getInterface(Ci.nsIDOMWindowUtils); if (!utils.sendSelectionSetEvent(0, 1, false)) @@ -404,7 +404,7 @@ function sendSelectionSetEvent(window) { // testOnSelect() requires nsIDOMWindowUtils, which is only available in // Firefox 3.7+. exports.testOnSelect = function testOnSelect(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); let callbackCount = 0; primeTestCase(TEXT_SINGLE, test, function(window, test) { selection.onSelect = function() {callbackCount++}; @@ -423,7 +423,7 @@ exports.testOnSelect = function testOnSelect(test) { // available in Firefox 3.7+. exports.testOnSelectExceptionNoBubble = function testOnSelectTextSelection(test) { - let selection = require("selection"); + let selection = require("sdk/selection"); primeTestCase(HTML_SINGLE, test, function(window, test) { selection.onSelect = function() { throw new Error("Exception thrown in testOnSelectExceptionNoBubble"); @@ -441,18 +441,17 @@ exports.testOnSelectExceptionNoBubble = // throw. In that case, remove all tests above from exports, and add one dummy // test that passes. try { - require("selection"); + require("sdk/selection"); } catch (err) { // This bug should be mentioned in the error message. let bug = "https://bugzilla.mozilla.org/show_bug.cgi?id=560716"; if (err.message.indexOf(bug) < 0) throw err; - for (let [prop, val] in Iterator(exports)) { - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; + + module.exports = { + testAppNotSupported: function (test) { + test.pass("the selection module does not support this application."); + } } - exports.testAppNotSupported = function (test) { - test.pass("The selection module does not support this application."); - }; } diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-self.js b/tools/addon-sdk-1.12/test/test-self.js index 2f0e093..6a4b530 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-self.js +++ b/tools/addon-sdk-1.12/test/test-self.js @@ -8,7 +8,7 @@ const {Cc, Ci, Cu, Cm, components} = require('chrome'); Cu.import("resource://gre/modules/AddonManager.jsm", this); exports.testSelf = function(test) { - var self = require("self"); + var self = require("sdk/self"); var source = self.data.load("test-content-symbiont.js"); test.assert(source.match(/test-content-symbiont/), "self.data.load() works"); @@ -27,14 +27,17 @@ exports.testSelf = function(test) { // When tests are run on just the api-utils package, self.name is // api-utils. When they're run as 'cfx testall', self.name is testpkgs. - test.assert((self.name == "api-utils") || (self.name == "testpkgs"), - "self.name is api-utils or testpkgs"); + test.assert(self.name == "addon-sdk", "self.name is addon-sdk"); + + // loadReason may change here, as we change the way tests addons are installed + test.assertEqual(self.loadReason, "startup", + "self.loadReason is always `startup` on test runs"); }; exports.testSelfID = function(test) { test.waitUntilDone(); - var self = require("self"); + var self = require("sdk/self"); // We can't assert anything about the ID inside the unit test right now, // because the ID we get depends upon how the test was invoked. The idea // is that it is supposed to come from the main top-level package's diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-set-exports.js b/tools/addon-sdk-1.12/test/test-set-exports.js index 5221237..5221237 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-set-exports.js +++ b/tools/addon-sdk-1.12/test/test-set-exports.js diff --git a/tools/addon-sdk-1.12/test/test-simple-prefs.js b/tools/addon-sdk-1.12/test/test-simple-prefs.js new file mode 100644 index 0000000..920af33 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-simple-prefs.js @@ -0,0 +1,231 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const { Loader } = require("sdk/test/loader"); +const { setTimeout } = require("sdk/timers"); +const { notify } = require("sdk/deprecated/observer-service"); +const { id } = require("sdk/self"); +const simplePrefs = require("sdk/simple-prefs"); +const { prefs: sp } = simplePrefs; + +const specialChars = "!@#$%^&*()_-=+[]{}~`\'\"<>,./?;:"; + +exports.testIterations = function(test) { + sp["test"] = true; + sp["test.test"] = true; + let prefAry = []; + for (var name in sp ) { + prefAry.push(name); + } + test.assert("test" in sp); + test.assert(!sp.getPropertyDescriptor); + test.assert(Object.prototype.hasOwnProperty.call(sp, "test")); + test.assertEqual(["test", "test.test"].toString(), prefAry.sort().toString(), "for (x in y) part 1/2 works"); + test.assertEqual(["test", "test.test"].toString(), Object.keys(sp).sort().toString(), "Object.keys works"); + + delete sp["test"]; + delete sp["test.test"]; + let prefAry = []; + for (var name in sp ) { + prefAry.push(name); + } + test.assertEqual([].toString(), prefAry.toString(), "for (x in y) part 2/2 works"); +} + +exports.testSetGetBool = function(test) { + test.assertEqual(sp.test, undefined, "Value should not exist"); + sp.test = true; + test.assert(sp.test, "Value read should be the value previously set"); +}; + +// TEST: setting and getting preferences with special characters work +exports.testSpecialChars = function(test) { + let chars = specialChars.split(""); + let len = chars.length; + + let count = 0; + chars.forEach(function(char) { + let rand = Math.random() + ""; + simplePrefs.on(char, function onPrefChanged() { + simplePrefs.removeListener(char, onPrefChanged); + test.assertEqual(sp[char], rand, "setting pref with a name that is a special char, " + char + ", worked!"); + + // end test + if (++count == len) + test.done(); + }) + sp[char] = rand; + }); +}; + +exports.testSetGetInt = function(test) { + test.assertEqual(sp["test-int"], undefined, "Value should not exist"); + sp["test-int"] = 1; + test.assertEqual(sp["test-int"], 1, "Value read should be the value previously set"); +}; + +exports.testSetComplex = function(test) { + try { + sp["test-complex"] = {test: true}; + test.fail("Complex values are not allowed"); + } + catch (e) { + test.pass("Complex values are not allowed"); + } +}; + +exports.testSetGetString = function(test) { + test.assertEqual(sp["test-string"], undefined, "Value should not exist"); + sp["test-string"] = "test"; + test.assertEqual(sp["test-string"], "test", "Value read should be the value previously set"); +}; + +exports.testHasAndRemove = function(test) { + sp.test = true; + test.assert(("test" in sp), "Value exists"); + delete sp.test; + test.assertEqual(sp.test, undefined, "Value should be undefined"); +}; + +exports.testPrefListener = function(test) { + test.waitUntilDone(); + + let listener = function(prefName) { + simplePrefs.removeListener('test-listener', listener); + test.assertEqual(prefName, "test-listen", "The prefs listener heard the right event"); + test.done(); + }; + + simplePrefs.on("test-listen", listener); + + sp["test-listen"] = true; + + // Wildcard listen + let toSet = ['wildcard1','wildcard.pref2','wildcard.even.longer.test']; + let observed = []; + + let wildlistener = function(prefName) { + if (toSet.indexOf(prefName) > -1) observed.push(prefName); + }; + + simplePrefs.on('',wildlistener); + + toSet.forEach(function(pref) { + sp[pref] = true; + }); + + test.assert((observed.length == 3 && toSet.length == 3), + "Wildcard lengths inconsistent" + JSON.stringify([observed.length, toSet.length])); + + toSet.forEach(function(pref,ii) { + test.assertEqual(observed[ii], pref, "Wildcard observed " + pref); + }); + + simplePrefs.removeListener('',wildlistener); + +}; + +exports.testBtnListener = function(test) { + test.waitUntilDone(); + + let name = "test-btn-listen"; + simplePrefs.on(name, function listener() { + simplePrefs.removeListener(name, listener); + test.pass("Button press event was heard"); + test.done(); + }); + notify((id + "-cmdPressed"), "", name); +}; + +exports.testPrefRemoveListener = function(test) { + test.waitUntilDone(); + + let counter = 0; + + let listener = function() { + test.pass("The prefs listener was not removed yet"); + + if (++counter > 1) + test.fail("The prefs listener was not removed"); + + simplePrefs.removeListener("test-listen2", listener); + + sp["test-listen2"] = false; + + setTimeout(function() { + test.pass("The prefs listener was removed"); + test.done(); + }, 250); + }; + + simplePrefs.on("test-listen2", listener); + + // emit change + sp["test-listen2"] = true; +}; + +// Bug 710117: Test that simple-pref listeners are removed on unload +exports.testPrefUnloadListener = function(test) { + test.waitUntilDone(); + + let loader = Loader(module); + let sp = loader.require("sdk/simple-prefs"); + let counter = 0; + + let listener = function() { + test.assertEqual(++counter, 1, "This listener should only be called once"); + + loader.unload(); + + // this may not execute after unload, but definitely shouldn't fire listener + sp.prefs["test-listen3"] = false; + // this should execute, but also definitely shouldn't fire listener + require("sdk/simple-prefs").prefs["test-listen3"] = false; + + test.done(); + }; + + sp.on("test-listen3", listener); + + // emit change + sp.prefs["test-listen3"] = true; +}; + + +// Bug 710117: Test that simple-pref listeners are removed on unload +exports.testPrefUnloadWildcardListener = function(test) { + test.waitUntilDone(); + let testpref = "test-wildcard-unload-listener"; + let loader = Loader(module); + let sp = loader.require("simple-prefs"); + let counter = 0; + + let listener = function() { + test.assertEqual(++counter, 1, "This listener should only be called once"); + + loader.unload(); + + // this may not execute after unload, but definitely shouldn't fire listener + sp.prefs[testpref] = false; + // this should execute, but also definitely shouldn't fire listener + require("simple-prefs").prefs[testpref] = false; + + test.done(); + }; + + sp.on("", listener); + // emit change + sp.prefs[testpref] = true; +}; + + +// Bug 732919 - JSON.stringify() fails on simple-prefs.prefs +exports.testPrefJSONStringification = function(test) { + var sp = require("sdk/simple-prefs").prefs; + test.assertEqual( + Object.keys(sp).join(), + Object.keys(JSON.parse(JSON.stringify(sp))).join(), + "JSON stringification should work."); +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-storage.js b/tools/addon-sdk-1.12/test/test-simple-storage.js index 25d0770..2202bed 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-storage.js +++ b/tools/addon-sdk-1.12/test/test-simple-storage.js @@ -4,39 +4,39 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const file = require("file"); -const prefs = require("preferences-service"); +const file = require("sdk/io/file"); +const prefs = require("sdk/preferences/service"); const QUOTA_PREF = "extensions.addon-sdk.simple-storage.quota"; let {Cc,Ci} = require("chrome"); -const { Loader } = require("./helpers"); -const options = require("@packaging"); +const { Loader } = require("sdk/test/loader"); +const { id } = require("sdk/self"); let storeFile = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci.nsIProperties). get("ProfD", Ci.nsIFile); storeFile.append("jetpack"); -storeFile.append(options.jetpackID); +storeFile.append(id); storeFile.append("simple-storage"); storeFile.append("store.json"); let storeFilename = storeFile.path; -function manager(loader) loader.sandbox("simple-storage").manager; +function manager(loader) loader.sandbox("sdk/simple-storage").manager; exports.testSetGet = function (test) { test.waitUntilDone(); // Load the module once, set a value. let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { test.assert(file.exists(storeFilename), "Store file should exist"); // Load the module again and make sure the value stuck. loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { file.remove(storeFilename); test.done(); @@ -81,12 +81,12 @@ exports.testSetGetRootNumber = function (test) { exports.testSetGetRootObject = function (test) { setGetRoot(test, { foo: 1, bar: 2 }, function (obj1, obj2) { - for (let [prop, val] in Iterator(obj1)) { - if (!(prop in obj2) || obj2[prop] !== val) + for (let prop in obj1) { + if (!(prop in obj2) || obj2[prop] !== obj1[prop]) return false; } - for (let [prop, val] in Iterator(obj2)) { - if (!(prop in obj1) || obj1[prop] !== val) + for (let prop in obj2) { + if (!(prop in obj1) || obj1[prop] !== obj2[prop]) return false; } return true; @@ -103,7 +103,7 @@ exports.testSetGetRootUndefined = function (test) { exports.testEmpty = function (test) { let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); loader.unload(); test.assert(!file.exists(storeFilename), "Store file should not exist"); }; @@ -113,7 +113,7 @@ exports.testMalformed = function (test) { stream.write("i'm not json"); stream.close(); let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); let empty = true; for (let key in ss.storage) { empty = false; @@ -129,7 +129,7 @@ exports.testQuotaExceededHandle = function (test) { prefs.set(QUOTA_PREF, 18); let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); ss.on("OverQuota", function () { test.pass("OverQuota was emitted as expected"); test.assertEqual(this, ss, "`this` should be simple storage"); @@ -137,7 +137,7 @@ exports.testQuotaExceededHandle = function (test) { manager(loader).jsonStore.onWrite = function () { loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); let numProps = 0; for (let prop in ss.storage) numProps++; @@ -164,11 +164,11 @@ exports.testQuotaExceededNoHandle = function (test) { prefs.set(QUOTA_PREF, 5); let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); test.assertEqual(ss.storage, val, "Value should have persisted: " + ss.storage); ss.storage = "some very long string that is very long"; @@ -180,7 +180,7 @@ exports.testQuotaExceededNoHandle = function (test) { loader.unload(); loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); test.assertEqual(ss.storage, val, "Over-quota value should not have been written, " + "old value should have persisted: " + ss.storage); @@ -203,7 +203,7 @@ exports.testQuotaUsage = function (test) { prefs.set(QUOTA_PREF, quota); let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); // {"a":1} (7 bytes) ss.storage = { a: 1 }; @@ -227,12 +227,12 @@ exports.testQuotaUsage = function (test) { exports.testUninstall = function (test) { test.waitUntilDone(); let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function () { test.assert(file.exists(storeFilename), "Store file should exist"); loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); loader.unload("uninstall"); test.assert(!file.exists(storeFilename), "Store file should be removed"); test.done(); @@ -246,13 +246,13 @@ exports.testSetNoSetRead = function (test) { // Load the module, set a value. let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { test.assert(file.exists(storeFilename), "Store file should exist"); // Load the module again but don't access ss.storage. loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { test.fail("Nothing should be written since `storage` was not accessed."); }; @@ -260,7 +260,7 @@ exports.testSetNoSetRead = function (test) { // Load the module a third time and make sure the value stuck. loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function (storage) { file.remove(storeFilename); test.done(); @@ -282,13 +282,13 @@ function setGetRoot(test, val, compare) { // Load the module once, set a value. let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function () { test.assert(file.exists(storeFilename), "Store file should exist"); // Load the module again and make sure the value stuck. loader = Loader(module); - ss = loader.require("simple-storage"); + ss = loader.require("sdk/simple-storage"); manager(loader).jsonStore.onWrite = function () { file.remove(storeFilename); test.done(); @@ -305,7 +305,7 @@ function setGetRootError(test, val, msg) { let pred = "storage must be one of the following types: " + "array, boolean, null, number, object, string"; let loader = Loader(module); - let ss = loader.require("simple-storage"); + let ss = loader.require("sdk/simple-storage"); test.assertRaises(function () ss.storage = val, pred, msg); loader.unload(); } diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-browser.js b/tools/addon-sdk-1.12/test/test-tab-browser.js index 31c5656..7475f13 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-browser.js +++ b/tools/addon-sdk-1.12/test/test-tab-browser.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var timer = require("timer"); +var timer = require("sdk/timers"); var {Cc,Ci} = require("chrome"); function onBrowserLoad(callback, event) { @@ -10,7 +10,7 @@ function onBrowserLoad(callback, event) { this.removeEventListener("load", onBrowserLoad, true); let browsers = this.document.getElementsByTagName("tabbrowser"); try { - require("timer").setTimeout(function (window) { + timer.setTimeout(function (window) { callback(window, browsers[0]); }, 10, this); } catch (e) { console.exception(e); } @@ -33,7 +33,7 @@ function openBrowserWindow(callback, url) { // Helper for calling code at window close function closeBrowserWindow(window, callback) { - require("timer").setTimeout(function() { + timer.setTimeout(function() { window.addEventListener("unload", function onUnload() { window.removeEventListener("unload", onUnload, false); callback(); @@ -61,10 +61,10 @@ function closeTwoWindows(window1, window2, callback) { exports.testAddTab = function(test) { test.waitUntilDone(); openBrowserWindow(function(window, browser) { - const tabBrowser = require("tab-browser"); + const tabBrowser = require("sdk/deprecated/tab-browser"); let cache = []; - let windowUtils = require("window-utils"); + let windowUtils = require("sdk/deprecated/window-utils"); new windowUtils.WindowTracker({ onTrack: function(win) { cache.push(win); @@ -76,14 +76,14 @@ exports.testAddTab = function(test) { let startWindowCount = cache.length; // Test 1: add a tab - let firstUrl = "data:text/html,one"; + let firstUrl = "data:text/html;charset=utf-8,one"; tabBrowser.addTab(firstUrl, { onLoad: function(e) { let win1 = cache[startWindowCount - 1]; test.assertEqual(win1.content.location, firstUrl, "URL of new tab in first window matches"); // Test 2: add a tab in a new window - let secondUrl = "data:text/html,two"; + let secondUrl = "data:text/html;charset=utf-8,two"; tabBrowser.addTab(secondUrl, { inNewWindow: true, onLoad: function(e) { @@ -109,7 +109,7 @@ exports.testAddTab = function(test) { exports.testTrackerWithDelegate = function(test) { test.waitUntilDone(); - const tabBrowser = require("tab-browser"); + const tabBrowser = require("sdk/deprecated/tab-browser"); var delegate = { state: "initializing", @@ -119,7 +119,7 @@ exports.testTrackerWithDelegate = function(test) { } else if (this.state == "waiting for browser window to open") { this.state = "waiting for browser window to close"; - require("timer").setTimeout(function() { + timer.setTimeout(function() { closeBrowserWindow(browser.ownerDocument.defaultView, function() { test.assertEqual(delegate.state, "deinitializing"); tb.unload(); @@ -148,7 +148,7 @@ exports.testTrackerWithDelegate = function(test) { exports.testWhenContentLoaded = function(test) { test.waitUntilDone(); - const tabBrowser = require("tab-browser"); + const tabBrowser = require("sdk/deprecated/tab-browser"); var tracker = tabBrowser.whenContentLoaded( function(window) { @@ -163,13 +163,13 @@ exports.testWhenContentLoaded = function(test) { openBrowserWindow(function(browserWindow, browser) { var html = '<div id="foo">bar</div>'; - browser.addTab("data:text/html," + html); + browser.addTab("data:text/html;charset=utf-8," + html); }); }; exports.testTrackerWithoutDelegate = function(test) { test.waitUntilDone(); - const tabBrowser = require("tab-browser"); + const tabBrowser = require("sdk/deprecated/tab-browser"); openBrowserWindow(function(browserWindow, browser) { var tb = new tabBrowser.Tracker(); @@ -198,7 +198,7 @@ exports.testTrackerWithoutDelegate = function(test) { exports.testTabTracker = function(test) { test.waitUntilDone(); - const tabBrowser = require("tab-browser"); + const tabBrowser = require("sdk/deprecated/tab-browser"); openBrowserWindow(function(browserWindow, browser) { var delegate = { @@ -214,9 +214,9 @@ exports.testTabTracker = function(test) { let tabTracker = tabBrowser.TabTracker(delegate); let tracked = delegate.tracked; - let url1 = "data:text/html,1"; - let url2 = "data:text/html,2"; - let url3 = "data:text/html,3"; + let url1 = "data:text/html;charset=utf-8,1"; + let url2 = "data:text/html;charset=utf-8,2"; + let url3 = "data:text/html;charset=utf-8,3"; let tabCount = 0; function tabLoadListener(e) { @@ -232,7 +232,7 @@ exports.testTabTracker = function(test) { test.assertEqual(delegate.tracked, tracked + 3, "delegate tracked tabs matched count"); tabTracker.unload(); closeBrowserWindow(browserWindow, function() { - require("timer").setTimeout(function() test.done(), 0); + timer.setTimeout(function() test.done(), 0); }); } } @@ -252,12 +252,12 @@ exports.testTabTracker = function(test) { exports.testActiveTab = function(test) { test.waitUntilDone(); openBrowserWindow(function(browserWindow, browser) { - const tabBrowser = require("tab-browser"); - const TabModule = require("tab-browser").TabModule; + const tabBrowser = require("sdk/deprecated/tab-browser"); + const TabModule = require("sdk/deprecated/tab-browser").TabModule; let tm = new TabModule(browserWindow); test.assertEqual(tm.length, 1); - let url1 = "data:text/html,foo"; - let url2 = "data:text/html,bar"; + let url1 = "data:text/html;charset=utf-8,foo"; + let url2 = "data:text/html;charset=utf-8,bar"; function tabURL(tab) tab.ownerDocument.defaultView.content.location.toString() @@ -291,7 +291,7 @@ exports.testActiveTab = function(test) { // TabModule tests exports.testEventsAndLengthStayInModule = function(test) { test.waitUntilDone(); - let TabModule = require("tab-browser").TabModule; + let TabModule = require("sdk/deprecated/tab-browser").TabModule; openTwoWindows(function(window1, window2) { let tm1 = new TabModule(window1); @@ -315,7 +315,7 @@ exports.testEventsAndLengthStayInModule = function(test) { tm1.onOpen = function() ++counter1 && onOpenListener(); tm2.onOpen = function() ++counter2 && onOpenListener(); - let url = "data:text/html,default"; + let url = "data:text/html;charset=utf-8,default"; tm1.open(url); tm1.open(url); @@ -327,49 +327,70 @@ exports.testEventsAndLengthStayInModule = function(test) { exports.testTabModuleActiveTab_getterAndSetter = function(test) { test.waitUntilDone(); - let TabModule = require("tab-browser").TabModule; + let TabModule = require("sdk/deprecated/tab-browser").TabModule; openTwoWindows(function(window1, window2) { let tm1 = new TabModule(window1); let tm2 = new TabModule(window2); - let tab1 = null; + // First open two tabs per window tm1.open({ - url: "data:text/html,<title>window1,tab1</title>", - onOpen: function(tab) tab1 = tab, + url: "data:text/html;charset=utf-8,<title>window1,tab1</title>", + onOpen: function(tab1) { + tm1.open({ + url: "data:text/html;charset=utf-8,<title>window1,tab2</title>", + onOpen: function (tab2) { + tm2.open({ + url: "data:text/html;charset=utf-8,<title>window2,tab1</title>", + onOpen: function (tab3) { + tm2.open({ + url: "data:text/html;charset=utf-8,<title>window2,tab2</title>", + onOpen: function(tab4) { + onTabsOpened(tab1, tab2, tab3, tab4); + } + }); + } + }); + } + }); + } }); - tm1.open("data:text/html,<title>window1,tab2</title>"); - - tm1.onActivate = function onActivate() { - tm1.onActivate.remove(onActivate); - require("timer").setTimeout(function() { - test.assertEqual(tm1.activeTab.title, "window1,tab1", "activeTab setter works"); - closeTwoWindows(window1, window2, function() test.done()); - }, 1000); - } - - tm2.open("data:text/html,<title>window2,tab1</title>"); - tm2.open({ - url: "data:text/html,<title>window2,tab2</title>", - onOpen: function(tab4) { - test.assertEqual(tm1.activeTab.title, "window1,tab2", "Correct active tab on window 1"); - test.assertEqual(tm2.activeTab.title, "window2,tab2", "Correct active tab on window 2"); - tm1.activeTab = tab1; - tm1.activeTab = tab4; // Setting activeTab from another window should have no effect + // Then try to activate tabs, but wait for all of them to be activated after + // being opened + function onTabsOpened(tab1, tab2, tab3, tab4) { + test.assertEqual(tm1.activeTab.title, "window1,tab2", + "Correct active tab on window 1"); + test.assertEqual(tm2.activeTab.title, "window2,tab2", + "Correct active tab on window 2"); + + tm1.onActivate = function onActivate() { + tm1.onActivate.remove(onActivate); + timer.setTimeout(function() { + test.assertEqual(tm1.activeTab.title, "window1,tab1", + "activeTab setter works (window 1)"); + test.assertEqual(tm2.activeTab.title, "window2,tab2", + "activeTab is ignored with tabs from another window"); + closeTwoWindows(window1, window2, function() test.done()); + }, 1000); } - }); + + tm1.activeTab = tab1; + // Setting activeTab from another window should have no effect: + tm1.activeTab = tab4; + } + }); } // test tabs iterator exports.testTabModuleTabsIterator = function(test) { test.waitUntilDone(); - let TabModule = require("tab-browser").TabModule; + let TabModule = require("sdk/deprecated/tab-browser").TabModule; openBrowserWindow(function(window) { let tm1 = new TabModule(window); - let url = "data:text/html,default"; + let url = "data:text/html;charset=utf-8,default"; tm1.open(url); tm1.open(url); tm1.open({ @@ -388,11 +409,11 @@ exports.testTabModuleTabsIterator = function(test) { // inNewWindow parameter is ignored on single-window modules exports.testTabModuleCantOpenInNewWindow = function(test) { test.waitUntilDone(); - let TabModule = require("tab-browser").TabModule; + let TabModule = require("sdk/deprecated/tab-browser").TabModule; openBrowserWindow(function(window) { let tm = new TabModule(window); - let url = "data:text/html,default"; + let url = "data:text/html;charset=utf-8,default"; tm.open({ url: url, inNewWindow: true, @@ -408,13 +429,13 @@ exports.testTabModuleCantOpenInNewWindow = function(test) { // window won't duplicate events fired on each module exports.testModuleListenersDontInteract = function(test) { test.waitUntilDone(); - let TabModule = require("tab-browser").TabModule; + let TabModule = require("sdk/deprecated/tab-browser").TabModule; openBrowserWindow(function(window) { let tm1 = new TabModule(window); let tm2 = new TabModule(window); - let url = "data:text/html,foo"; + let url = "data:text/html;charset=utf-8,foo"; let eventCount = 0, eventModule1 = 0, eventModule2 = 0; @@ -476,18 +497,17 @@ function activeWindow() { // throw. In that case, remove all tests above from exports, and add one dummy // test that passes. try { - require("tab-browser"); + require("sdk/deprecated/tab-browser"); } catch (err) { // This bug should be mentioned in the error message. let bug = "https://bugzilla.mozilla.org/show_bug.cgi?id=560716"; if (err.message.indexOf(bug) < 0) throw err; - for (let [prop, val] in Iterator(exports)) { - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; - } - exports.testAppNotSupported = function (test) { - test.pass("the tab-browser module does not support this application."); + + module.exports = { + testAppNotSupported: function (test) { + test.pass("the tab-browser module does not support this application."); + } }; } diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-observer.js b/tools/addon-sdk-1.12/test/test-tab-observer.js index 3a506fa..8b45c19 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab-observer.js +++ b/tools/addon-sdk-1.12/test/test-tab-observer.js @@ -4,15 +4,15 @@ "use strict"; -const { openTab, closeTab } = require("api-utils/tabs/utils"); -const { Loader } = require("./helpers"); -const { setTimeout } = require("timer"); +const { openTab, closeTab } = require("sdk/tabs/utils"); +const { Loader } = require("sdk/test/loader"); +const { setTimeout } = require("sdk/timers"); exports["test unload tab observer"] = function(assert, done) { let loader = Loader(module); - let window = loader.require("api-utils/window-utils").activeBrowserWindow; - let observer = loader.require("api-utils/tabs/observer").observer; + let window = loader.require("sdk/deprecated/window-utils").activeBrowserWindow; + let observer = loader.require("sdk/tabs/observer").observer; let opened = 0; let closed = 0; @@ -20,13 +20,13 @@ exports["test unload tab observer"] = function(assert, done) { observer.on("close", function onClose(window) { closed++; }); // Open and close tab to trigger observers. - closeTab(openTab(window, "data:text/html,tab-1")); + closeTab(openTab(window, "data:text/html;charset=utf-8,tab-1")); // Unload the module so that all listeners set by observer are removed. loader.unload(); // Open and close tab once again. - closeTab(openTab(window, "data:text/html,tab-2")); + closeTab(openTab(window, "data:text/html;charset=utf-8,tab-2")); // Enqueuing asserts to make sure that assertion is not performed early. setTimeout(function () { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab.js b/tools/addon-sdk-1.12/test/test-tab.js index 2324fa7..280266c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-tab.js +++ b/tools/addon-sdk-1.12/test/test-tab.js @@ -2,9 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const tabAPI = require("tabs/tab"); -const tabs = require("tabs"); // From addon-kit -const windowUtils = require("window-utils"); +const tabAPI = require('sdk/tabs/tab'); +const tabs = require("sdk/tabs"); // From addon-kit +const windowUtils = require("sdk/deprecated/window-utils"); +const { getTabForWindow } = require('sdk/tabs/helpers'); // The primary test tab var primaryTab; @@ -17,20 +18,20 @@ var iframeWin; exports.testGetTabForWindow = function(test) { test.waitUntilDone(); - - test.assertEqual(tabAPI.getTabForWindow(windowUtils.activeWindow), null, + + test.assertEqual(getTabForWindow(windowUtils.activeWindow), null, "getTabForWindow return null on topwindow"); - test.assertEqual(tabAPI.getTabForWindow(windowUtils.activeBrowserWindow), null, + test.assertEqual(getTabForWindow(windowUtils.activeBrowserWindow), null, "getTabForWindow return null on topwindow"); - + let subSubDocument = encodeURIComponent( 'Sub iframe<br/>'+ - '<iframe id="sub-sub-iframe" src="data:text/html,SubSubIframe" />'); + '<iframe id="sub-sub-iframe" src="data:text/html;charset=utf-8,SubSubIframe" />'); let subDocument = encodeURIComponent( 'Iframe<br/>'+ - '<iframe id="sub-iframe" src="data:text/html,'+subSubDocument+'" />'); - let url = 'data:text/html,' + encodeURIComponent( - 'Content<br/><iframe id="iframe" src="data:text/html,'+subDocument+'" />'); + '<iframe id="sub-iframe" src="data:text/html;charset=utf-8,'+subSubDocument+'" />'); + let url = 'data:text/html;charset=utf-8,' + encodeURIComponent( + 'Content<br/><iframe id="iframe" src="data:text/html;charset=utf-8,'+subDocument+'" />'); // Open up a new tab in the background. // @@ -41,8 +42,8 @@ exports.testGetTabForWindow = function(test) { url: "about:mozilla", onReady: function(tab) { auxTab = tab; step2(url, test);}, onActivate: function(tab) { step3(test); } - }); -} + }); +}; function step2(url, test) { @@ -51,12 +52,12 @@ function step2(url, test) { onReady: function(tab) { primaryTab = tab; let window = windowUtils.activeBrowserWindow.content; - - let matchedTab = tabAPI.getTabForWindow(window); - test.assertEqual(matchedTab, tab, + + let matchedTab = getTabForWindow(window); + test.assertEqual(matchedTab, tab, "We are able to find the tab with his content window object"); - - let timer = require("timer"); + + let timer = require("sdk/timers"); function waitForFrames() { let iframe = window.document.getElementById("iframe"); if (!iframe) { @@ -76,17 +77,17 @@ function step2(url, test) { return; } let subSubIframeWin = subSubIframe.contentWindow; - - matchedTab = tabAPI.getTabForWindow(iframeWin); - test.assertEqual(matchedTab, tab, + + matchedTab = getTabForWindow(iframeWin); + test.assertEqual(matchedTab, tab, "We are able to find the tab with an iframe window object"); - - matchedTab = tabAPI.getTabForWindow(subIframeWin); - test.assertEqual(matchedTab, tab, + + matchedTab = getTabForWindow(subIframeWin); + test.assertEqual(matchedTab, tab, "We are able to find the tab with a sub-iframe window object"); - - matchedTab = tabAPI.getTabForWindow(subSubIframeWin); - test.assertEqual(matchedTab, tab, + + matchedTab = getTabForWindow(subSubIframeWin); + test.assertEqual(matchedTab, tab, "We are able to find the tab with a sub-sub-iframe window object"); // Put our primary tab in the background and test again. @@ -100,7 +101,7 @@ function step2(url, test) { function step3(test) { - let matchedTab = tabAPI.getTabForWindow(iframeWin); + let matchedTab = getTabForWindow(iframeWin); test.assertEqual(matchedTab, primaryTab, "We get the correct tab even when it's in the background"); diff --git a/tools/addon-sdk-1.12/test/test-tabs-common.js b/tools/addon-sdk-1.12/test/test-tabs-common.js new file mode 100644 index 0000000..3d65143 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-tabs-common.js @@ -0,0 +1,296 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Loader } = require('sdk/test/loader'); +const { browserWindows } = require('sdk/windows'); +const tabs = require('sdk/tabs'); + +const URL = 'data:text/html;charset=utf-8,<html><head><title>#title#</title></head></html>'; + +// TEST: tab count +exports.testTabCounts = function(test) { + test.waitUntilDone(); + + tabs.open({ + url: 'about:blank', + onReady: function(tab) { + let count1 = 0, + count2 = 0; + for each(let window in browserWindows) { + count1 += window.tabs.length; + for each(let tab in window.tabs) { + count2 += 1; + } + } + + test.assert(tabs.length > 1, 'tab count is > 1'); + test.assertEqual(count1, tabs.length, 'tab count by length is correct'); + test.assertEqual(count2, tabs.length, 'tab count by iteration is correct'); + + // end test + tab.close(function() test.done()); + } + }); +}; + +// TEST: tab.activate() +exports.testActiveTab_setter_alt = function(test) { + test.waitUntilDone(); + + let url = URL.replace("#title#", "testActiveTab_setter_alt"); + let tab1URL = URL.replace("#title#", "tab1"); + + tabs.open({ + url: tab1URL, + onReady: function(activeTab) { + let activeTabURL = tabs.activeTab.url; + + tabs.open({ + url: url, + inBackground: true, + onReady: function onReady(tab) { + test.assertEqual(tabs.activeTab.url, activeTabURL, "activeTab url has not changed"); + test.assertEqual(tab.url, url, "url of new background tab matches"); + + tab.once('activate', function onActivate(eventTab) { + test.assertEqual(tabs.activeTab.url, url, "url after activeTab setter matches"); + test.assertEqual(eventTab, tab, "event argument is the activated tab"); + test.assertEqual(eventTab, tabs.activeTab, "the tab is the active one"); + + activeTab.close(function() { + tab.close(function() { + // end test + test.done(); + }); + }); + }); + + tab.activate(); + } + }); + } + }); +}; + +// TEST: tab.close() +exports.testTabClose_alt = function(test) { + test.waitUntilDone(); + + let url = URL.replace('#title#', 'TabClose_alt'); + let tab1URL = URL.replace('#title#', 'tab1'); + + tabs.open({ + url: tab1URL, + onReady: function(tab1) { + // make sure that our tab is not active first + test.assertNotEqual(tabs.activeTab.url, url, "tab is not the active tab"); + + tabs.open({ + url: url, + onReady: function(tab) { + test.assertEqual(tab.url, url, "tab is now the active tab"); + test.assertEqual(tabs.activeTab.url, url, "tab is now the active tab"); + + // another tab should be activated on close + tabs.once('activate', function() { + test.assertNotEqual(tabs.activeTab.url, url, "tab is no longer the active tab"); + + // end test + tab1.close(function() test.done()); + }); + + tab.close(); + } + }); + } + }); +}; + +exports.testAttachOnOpen_alt = function (test) { + // Take care that attach has to be called on tab ready and not on tab open. + test.waitUntilDone(); + + tabs.open({ + url: "data:text/html;charset=utf-8,foobar", + onOpen: function (tab) { + let worker = tab.attach({ + contentScript: 'self.postMessage(document.location.href); ', + onMessage: function (msg) { + test.assertEqual(msg, "about:blank", + "Worker document url is about:blank on open"); + worker.destroy(); + tab.close(function() test.done()); + } + }); + } + }); +}; + +exports.testAttachOnMultipleDocuments_alt = function (test) { + // Example of attach that process multiple tab documents + test.waitUntilDone(); + + let firstLocation = "data:text/html;charset=utf-8,foobar"; + let secondLocation = "data:text/html;charset=utf-8,bar"; + let thirdLocation = "data:text/html;charset=utf-8,fox"; + let onReadyCount = 0; + let worker1 = null; + let worker2 = null; + let detachEventCount = 0; + + tabs.open({ + url: firstLocation, + onReady: function (tab) { + onReadyCount++; + if (onReadyCount == 1) { + worker1 = tab.attach({ + contentScript: 'self.on("message", ' + + ' function () self.postMessage(document.location.href)' + + ');', + onMessage: function (msg) { + test.assertEqual(msg, firstLocation, + "Worker url is equal to the 1st document"); + tab.url = secondLocation; + }, + onDetach: function () { + detachEventCount++; + test.pass("Got worker1 detach event"); + test.assertRaises(function () { + worker1.postMessage("ex-1"); + }, + /Couldn't find the worker/, + "postMessage throw because worker1 is destroyed"); + checkEnd(); + } + }); + worker1.postMessage("new-doc-1"); + } + else if (onReadyCount == 2) { + worker2 = tab.attach({ + contentScript: 'self.on("message", ' + + ' function () self.postMessage(document.location.href)' + + ');', + onMessage: function (msg) { + test.assertEqual(msg, secondLocation, + "Worker url is equal to the 2nd document"); + tab.url = thirdLocation; + }, + onDetach: function () { + detachEventCount++; + test.pass("Got worker2 detach event"); + test.assertRaises(function () { + worker2.postMessage("ex-2"); + }, + /Couldn't find the worker/, + "postMessage throw because worker2 is destroyed"); + checkEnd(tab); + } + }); + worker2.postMessage("new-doc-2"); + } + else if (onReadyCount == 3) { + tab.close(); + } + } + }); + + function checkEnd(tab) { + if (detachEventCount != 2) + return; + + test.pass("Got all detach events"); + + // end test + test.done(); + } +}; + +exports.testAttachWrappers_alt = function (test) { + // Check that content script has access to wrapped values by default + test.waitUntilDone(); + + let document = "data:text/html;charset=utf-8,<script>var globalJSVar = true; " + + " document.getElementById = 3;</script>"; + let count = 0; + + tabs.open({ + url: document, + onReady: function (tab) { + let worker = tab.attach({ + contentScript: 'try {' + + ' self.postMessage(!("globalJSVar" in window));' + + ' self.postMessage(typeof window.globalJSVar == "undefined");' + + '} catch(e) {' + + ' self.postMessage(e.message);' + + '}', + onMessage: function (msg) { + test.assertEqual(msg, true, "Worker has wrapped objects ("+count+")"); + if (count++ == 1) + tab.close(function() test.done()); + } + }); + } + }); +}; + +// TEST: activeWindow getter and activeTab getter on tab 'activate' event +exports.testActiveWindowActiveTabOnActivate_alt = function(test) { + test.waitUntilDone(); + + let activateCount = 0; + let newTabs = []; + let tabs = browserWindows.activeWindow.tabs; + + tabs.on('activate', function onActivate(tab) { + test.assertEqual(tabs.activeTab, tab, + "the active window's active tab is the tab provided"); + + if (++activateCount == 2) { + tabs.removeListener('activate', onActivate); + + newTabs.forEach(function(tab) { + tab.close(function() { + if (--activateCount == 0) { + // end test + test.done(); + } + }); + }); + } + else if (activateCount > 2) { + test.fail("activateCount is greater than 2 for some reason.."); + } + }); + + tabs.open({ + url: URL.replace("#title#", "tabs.open1"), + onOpen: function(tab) newTabs.push(tab) + }); + tabs.open({ + url: URL.replace("#title#", "tabs.open2"), + onOpen: function(tab) newTabs.push(tab) + }); +}; + +// TEST: tab properties +exports.testTabContentTypeAndReload = function(test) { + test.waitUntilDone(); + + let url = "data:text/html;charset=utf-8,<html><head><title>foo</title></head><body>foo</body></html>"; + let urlXML = "data:text/xml;charset=utf-8,<foo>bar</foo>"; + tabs.open({ + url: url, + onReady: function(tab) { + if (tab.url === url) { + test.assertEqual(tab.contentType, "text/html"); + tab.url = urlXML; + } + else { + test.assertEqual(tab.contentType, "text/xml"); + tab.close(function() test.done()); + } + } + }); +}; diff --git a/tools/addon-sdk-1.12/test/test-tabs.js b/tools/addon-sdk-1.12/test/test-tabs.js new file mode 100644 index 0000000..cad8931 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-tabs.js @@ -0,0 +1,11 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +if (require("sdk/system/xul-app").is("Firefox")) { + module.exports = require("./tabs/test-firefox-tabs"); +} +else if (require("sdk/system/xul-app").is("Fennec")) { + module.exports = require("./tabs/test-fennec-tabs"); +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-text-streams.js b/tools/addon-sdk-1.12/test/test-text-streams.js index f5aec98..36a01c8 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-text-streams.js +++ b/tools/addon-sdk-1.12/test/test-text-streams.js @@ -4,9 +4,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const file = require("file"); -const { pathFor } = require("api-utils/system"); -const { Loader } = require("./helpers"); +const file = require("sdk/io/file"); +const { pathFor } = require("sdk/system"); +const { Loader } = require("sdk/test/loader"); const STREAM_CLOSED_ERROR = "The stream is closed and cannot be used."; @@ -141,7 +141,7 @@ exports.testWriteAsync = function (test) { exports.testUnload = function (test) { let loader = Loader(module); - let file = loader.require("file"); + let file = loader.require("sdk/io/file"); let filename = dataFileFilename("temp"); let stream = file.open(filename, "w"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-timer.js b/tools/addon-sdk-1.12/test/test-timer.js index bf6917c..2c7d846 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-timer.js +++ b/tools/addon-sdk-1.12/test/test-timer.js @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var timer = require("timer"); -const { Loader } = require("./helpers"); +var timer = require("sdk/timers"); +const { Loader } = require("sdk/test/loader"); exports.testSetTimeout = function(test) { timer.setTimeout(function() { @@ -111,7 +111,7 @@ exports.testParamedClearInterval = function(test) { exports.testUnload = function(test) { var loader = Loader(module); - var sbtimer = loader.require("timer"); + var sbtimer = loader.require("sdk/timers"); var myFunc = function myFunc() { test.fail("myFunc() should not be called in testUnload"); diff --git a/tools/addon-sdk-1.12/test/test-tmp-file.js b/tools/addon-sdk-1.12/test/test-tmp-file.js new file mode 100644 index 0000000..187f9e7 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-tmp-file.js @@ -0,0 +1,24 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const tmp = require("sdk/test/tmp-file"); +const file = require("sdk/io/file"); + +const testFolderURL = module.uri.split('test-tmp-file.js')[0]; + +exports.testCreateFromString = function (test) { + let expectedContent = "foo"; + let path = tmp.createFromString(expectedContent); + let content = file.read(path); + test.assertEqual(content, expectedContent, + "Temporary file contains the expected content"); +} + +exports.testCreateFromURL = function (test) { + let url = testFolderURL + "test-tmp-file.txt"; + let path = tmp.createFromURL(url); + let content = file.read(path); + test.assertEqual(content, "foo", + "Temporary file contains the expected content"); +} diff --git a/tools/addon-sdk-1.12/test/test-tmp-file.txt b/tools/addon-sdk-1.12/test/test-tmp-file.txt new file mode 100644 index 0000000..1910281 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-tmp-file.txt @@ -0,0 +1 @@ +foo
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traceback.js b/tools/addon-sdk-1.12/test/test-traceback.js index e4d1737..df310d1 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traceback.js +++ b/tools/addon-sdk-1.12/test/test-traceback.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var traceback = require("traceback"); +var traceback = require("sdk/console/traceback"); var {Cc,Ci,Cr,Cu} = require("chrome"); function throwNsIException() { @@ -16,7 +16,7 @@ function throwError() { } exports.testFormatDoesNotFetchRemoteFiles = function(test) { - var observers = require("observer-service"); + var observers = require("sdk/deprecated/observer-service"); ["http", "https"].forEach( function(scheme) { var httpRequests = 0; @@ -66,7 +66,7 @@ exports.testFromExceptionWithError = function(test) { test.fail("an exception should've been thrown"); } catch (e if e instanceof Error) { var tb = traceback.fromException(e); - var xulApp = require("xul-app"); + var xulApp = require("sdk/system/xul-app"); test.assertEqual(tb.slice(-1)[0].funcName, "throwError"); } }; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traits-core.js b/tools/addon-sdk-1.12/test/test-traits-core.js index c2bf4df..8ab2edd 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traits-core.js +++ b/tools/addon-sdk-1.12/test/test-traits-core.js @@ -120,7 +120,7 @@ function Conflict(name) { function testMethod() {}; const { trait, compose, resolve, required, override, create } = - require('traits/core'); + require('sdk/deprecated/traits/core'); exports['test:empty trait'] = function(test) { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traits.js b/tools/addon-sdk-1.12/test/test-traits.js index 8b88f94..8e01a70 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-traits.js +++ b/tools/addon-sdk-1.12/test/test-traits.js @@ -4,7 +4,7 @@ "use strict"; -const { Trait } = require('traits'); +const { Trait } = require('sdk/deprecated/traits'); exports['test:simple compose'] = function(test) { let List = Trait.compose({ diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-type.js b/tools/addon-sdk-1.12/test/test-type.js index d5b5775..99e11de 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-type.js +++ b/tools/addon-sdk-1.12/test/test-type.js @@ -4,7 +4,7 @@ "use strict" -var utils = require("type"); +var utils = require("sdk/lang/type"); exports["test function"] = function (assert) { assert.ok(utils.isFunction(function(){}), "value is function"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-unit-test.js b/tools/addon-sdk-1.12/test/test-unit-test.js index 8ee99a4..d6a1451 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-unit-test.js +++ b/tools/addon-sdk-1.12/test/test-unit-test.js @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const timer = require("timer"); -const { Loader } = require("./helpers"); +const timer = require("sdk/timers"); +const { Loader } = require("sdk/test/loader"); var setupCalled = false, teardownCalled = false; @@ -116,7 +116,7 @@ exports.testWaitUntilErrorInCallback = function(test) { exports.testWaitUntilTimeoutInCallback = function(test) { test.waitUntilDone(1000); - let runner = new (require("unit-test").TestRunner)({ + let runner = new (require("sdk/deprecated/unit-test").TestRunner)({ console: { calls: 0, error: function(msg) { @@ -139,6 +139,9 @@ exports.testWaitUntilTimeoutInCallback = function(test) { " assertion callback: '" + arguments[1] + "'"); } }, + info: function (msg) { + test.assertEqual(msg, "executing 'wait4ever'"); + }, trace: function () {} } }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-unload.js b/tools/addon-sdk-1.12/test/test-unload.js index e05b4e0..1bbb64e 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-unload.js +++ b/tools/addon-sdk-1.12/test/test-unload.js @@ -4,14 +4,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var unload = require("unload"); -var { Loader } = require("./helpers"); +var unload = require("sdk/system/unload"); +var { Loader } = require("sdk/test/loader"); exports.testUnloading = function(test) { - var loader = Loader(module); - var ul = loader.require("unload"); + var loader = Loader(module, { + console: Object.create(console, { + exception: { value: function(error) { + exceptions.push(error); + }} + }) + }); + var exceptions = []; + var ul = loader.require("sdk/system/unload"); var unloadCalled = 0; - var errorsReported = 0; function unload() { unloadCalled++; throw new Error("error"); @@ -23,10 +29,10 @@ exports.testUnloading = function(test) { function unload2() { unloadCalled++; } ul.when(unload2); - loader.unload(undefined, function onError() { errorsReported++; }); + loader.unload(); test.assertEqual(unloadCalled, 2, "Unloader functions are called on unload."); - test.assertEqual(errorsReported, 1, + test.assertEqual(exceptions.length, 1, "One unload handler threw exception"); }; @@ -58,9 +64,9 @@ exports.testEnsure = function(test) { */ exports.testEnsureWithTraits = function(test) { - let { Trait } = require("traits"); + let { Trait } = require("sdk/deprecated/traits"); let loader = Loader(module); - let ul = loader.require("unload"); + let ul = loader.require("sdk/system/unload"); let called = 0; let composedCalled = 0; @@ -114,9 +120,9 @@ exports.testEnsureWithTraits = function(test) { exports.testEnsureWithTraitsPrivate = function(test) { - let { Trait } = require("traits"); + let { Trait } = require("sdk/deprecated/traits"); let loader = Loader(module); - let ul = loader.require("unload"); + let ul = loader.require("sdk/system/unload"); let called = 0; let privateObj = null; @@ -145,7 +151,7 @@ exports.testEnsureWithTraitsPrivate = function(test) { exports.testReason = function (test) { var reason = "Reason doesn't actually have to be anything in particular."; var loader = Loader(module); - var ul = loader.require("unload"); + var ul = loader.require("sdk/system/unload"); ul.when(function (rsn) { test.assertEqual(rsn, reason, "when() reason should be reason given to loader"); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-url.js b/tools/addon-sdk-1.12/test/test-url.js index f217400..3b5cec2 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-url.js +++ b/tools/addon-sdk-1.12/test/test-url.js @@ -2,7 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var url = require("url"); +var url = require("sdk/url"); +var { packed } = require("sdk/self"); exports.testResolve = function(test) { test.assertEqual(url.URL("bar", "http://www.foo.com/").toString(), @@ -78,11 +79,6 @@ exports.testParseFTPWithUserPass = function(test) { test.assertEqual(info.userPass, "user:pass"); }; -// rootURI is jar:file://...!/ if we're packed, and file://.../ if we're -// unpacked. url.toFilename() is not required to work for the contents of -// packed XPIs -var unpacked = (require("@packaging").rootURI.indexOf("file:") == 0); - exports.testToFilename = function(test) { test.assertRaises( function() { url.toFilename("resource://nonexistent"); }, @@ -90,7 +86,7 @@ exports.testToFilename = function(test) { "url.toFilename() on nonexistent resources should throw" ); - if (unpacked) + if (!packed) test.assertMatches(url.toFilename(module.uri), /.*test-url\.js$/, "url.toFilename() on resource: URIs should work"); @@ -126,7 +122,7 @@ exports.testToFilename = function(test) { }; exports.testFromFilename = function(test) { - var profileDirName = require("system").pathFor("ProfD"); + var profileDirName = require("sdk/system").pathFor("ProfD"); var fileUrl = url.fromFilename(profileDirName); test.assertEqual(url.URL(fileUrl).scheme, 'file', 'url.toFilename() should return a file: url'); @@ -151,11 +147,11 @@ exports.testURL = function(test) { "h:foo", "toString should roundtrip"); // test relative + base - test.assertEqual(URL("mypath", "http://foo").toString(), + test.assertEqual(URL("mypath", "http://foo").toString(), "http://foo/mypath", "relative URL resolved to base"); // test relative + no base - test.assertRaises(function() URL("path").toString(), + test.assertRaises(function() URL("path").toString(), "malformed URI: path", "no base for relative URI should throw"); @@ -202,3 +198,58 @@ exports.testStringInterface = function(test) { test.assertEqual(a.trimRight(), EM.trimRight(), "trimRight on URL works."); test.assertEqual(a.trimLeft(), EM.trimLeft(), "trimLeft on URL works."); } + +exports.testDataURLwithouthURI = function (test) { + const { DataURL } = url; + + let dataURL = new DataURL(); + + test.assertEqual(dataURL.base64, false, "base64 is false for empty uri") + test.assertEqual(dataURL.data, "", "data is an empty string for empty uri") + test.assertEqual(dataURL.mimeType, "", "mimeType is an empty string for empty uri") + test.assertEqual(Object.keys(dataURL.parameters).length, 0, "parameters is an empty object for empty uri"); + + test.assertEqual(dataURL.toString(), "data:,"); +} + +exports.testDataURLwithMalformedURI = function (test) { + const { DataURL } = url; + + test.assertRaises(function() { + let dataURL = new DataURL("http://www.mozilla.com/"); + }, + "Malformed Data URL: http://www.mozilla.com/", + "DataURL raises an exception for malformed data uri" + ); +} + +exports.testDataURLparse = function (test) { + const { DataURL } = url; + + let dataURL = new DataURL("data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E"); + + test.assertEqual(dataURL.base64, false, "base64 is false for non base64 data uri") + test.assertEqual(dataURL.data, "<h1>Hello!</h1>", "data is properly decoded") + test.assertEqual(dataURL.mimeType, "text/html", "mimeType is set properly") + test.assertEqual(Object.keys(dataURL.parameters).length, 1, "one parameters specified"); + test.assertEqual(dataURL.parameters["charset"], "US-ASCII", "charset parsed"); + + test.assertEqual(dataURL.toString(), "data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E"); +} + +exports.testDataURLparseBase64 = function (test) { + const { DataURL } = url; + const { decode } = require("sdk/base64"); + + let text = "Awesome!"; + let b64text = "QXdlc29tZSE="; + let dataURL = new DataURL("data:text/plain;base64," + b64text); + + test.assertEqual(dataURL.base64, true, "base64 is true for base64 encoded data uri") + test.assertEqual(dataURL.data, text, "data is properly decoded") + test.assertEqual(dataURL.mimeType, "text/plain", "mimeType is set properly") + test.assertEqual(Object.keys(dataURL.parameters).length, 1, "one parameters specified"); + test.assertEqual(dataURL.parameters["base64"], "", "parameter set without value"); + + test.assertEqual(dataURL.toString(), "data:text/plain;base64," + encodeURIComponent(b64text)); +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-uuid.js b/tools/addon-sdk-1.12/test/test-uuid.js index 5670023..3c9a4be 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-uuid.js +++ b/tools/addon-sdk-1.12/test/test-uuid.js @@ -4,7 +4,7 @@ "use strict"; -const { uuid } = require('api-utils/uuid'); +const { uuid } = require('sdk/util/uuid'); exports['test generate uuid'] = function(assert) { let signature = /{[0-9a-f\-]+}/ diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-widget.js b/tools/addon-sdk-1.12/test/test-widget.js index 5d3475b..78bc9f9 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-widget.js +++ b/tools/addon-sdk-1.12/test/test-widget.js @@ -5,11 +5,12 @@ "use strict"; const {Cc,Ci} = require("chrome"); -const { Loader } = require('./helpers'); -const widgets = require("widget"); -const url = require("url"); -const windowUtils = require("window-utils"); -const tabBrowser = require("tab-browser"); +const { Loader } = require('sdk/test/loader'); +const widgets = require("sdk/widget"); +const url = require("sdk/url"); +const windowUtils = require("sdk/deprecated/window-utils"); +const tabBrowser = require("sdk/deprecated/tab-browser"); +const timer = require("sdk/timers"); exports.testConstructor = function(test) { test.waitUntilDone(30000); @@ -41,7 +42,7 @@ exports.testConstructor = function(test) { // Test automatic widget destroy on unload let loader = Loader(module); - let widgetsFromLoader = loader.require("widget"); + let widgetsFromLoader = loader.require("sdk/widget"); let widgetStartCount = widgetCount(); let w = widgetsFromLoader.Widget({ id: "fooID", label: "foo", content: "bar" }); test.assertEqual(widgetCount(), widgetStartCount + 1, "widget has been correctly added"); @@ -130,7 +131,7 @@ exports.testConstructor = function(test) { // Test concurrent widget module instances on addon-bar hiding let loader = Loader(module); - let anotherWidgetsInstance = loader.require("widget"); + let anotherWidgetsInstance = loader.require("sdk/widget"); test.assert(container().collapsed, "UI is hidden when no widgets"); AddonsMgrListener.onInstalling(); let w1 = widgets.Widget({id: "foo", label: "foo", content: "bar"}); @@ -181,7 +182,7 @@ exports.testConstructor = function(test) { if (!tests.length) test.done(); else - require("timer").setTimeout(tests.shift(), 0); + timer.setTimeout(tests.shift(), 0); } function doneTest() nextTest(); @@ -217,7 +218,7 @@ exports.testConstructor = function(test) { tests.push(function testImageURLWidget() testSingleWidget({ id: "image", label: "image url widget", - contentURL: require("self").data.url("test.html"), + contentURL: require("sdk/self").data.url("test.html"), contentScript: "self.postMessage({title: document.title, " + "tag: document.body.firstElementChild.tagName, " + "content: document.body.firstElementChild.innerHTML});", @@ -235,7 +236,7 @@ exports.testConstructor = function(test) { tests.push(function testWebURIWidget() testSingleWidget({ id: "web", label: "web uri widget", - contentURL: require("self").data.url("test.html"), + contentURL: require("sdk/self").data.url("test.html"), contentScript: "self.postMessage({title: document.title, " + "tag: document.body.firstElementChild.tagName, " + "content: document.body.firstElementChild.innerHTML});", @@ -301,7 +302,7 @@ exports.testConstructor = function(test) { tests.push(function testOnclickEventImage() testSingleWidget({ id: "click", label: "click test widget - image", - contentURL: require("self").data.url("moz_favicon.ico"), + contentURL: require("sdk/self").data.url("moz_favicon.ico"), contentScript: "var evt = document.createEvent('HTMLEvents'); " + "evt.initEvent('click', true, true ); " + "document.body.firstElementChild.dispatchEvent(evt);", @@ -317,7 +318,7 @@ exports.testConstructor = function(test) { tests.push(function testOnmouseoverEventImage() testSingleWidget({ id: "mouseover", label: "mouseover test widget - image", - contentURL: require("self").data.url("moz_favicon.ico"), + contentURL: require("sdk/self").data.url("moz_favicon.ico"), contentScript: "var evt = document.createEvent('HTMLEvents'); " + "evt.initEvent('mouseover', true, true ); " + "document.body.firstElementChild.dispatchEvent(evt);", @@ -333,7 +334,7 @@ exports.testConstructor = function(test) { tests.push(function testOnmouseoutEventImage() testSingleWidget({ id: "mouseout", label: "mouseout test widget - image", - contentURL: require("self").data.url("moz_favicon.ico"), + contentURL: require("sdk/self").data.url("moz_favicon.ico"), contentScript: "var evt = document.createEvent('HTMLEvents'); " + "evt.initEvent('mouseout', true, true ); " + "document.body.firstElementChild.dispatchEvent(evt);", @@ -378,8 +379,8 @@ exports.testConstructor = function(test) { })); // test updating widget contentURL - let url1 = "data:text/html,<body>foodle</body>"; - let url2 = "data:text/html,<body>nistel</body>"; + let url1 = "data:text/html;charset=utf-8,<body>foodle</body>"; + let url2 = "data:text/html;charset=utf-8,<body>nistel</body>"; tests.push(function testUpdatingContentURL() testSingleWidget({ id: "content", @@ -527,7 +528,7 @@ exports.testConstructor = function(test) { contentScript: "self.port.on('event', function () self.port.emit('event'))" }; let widget = testSingleWidget(w1Opts); - let windows = require("windows").browserWindows; + let windows = require("sdk/windows").browserWindows; // 2/ Retrieve a WidgetView for the initial browser window let acceptDetach = false; @@ -577,28 +578,36 @@ exports.testConstructor = function(test) { tests.push(function testAddonBarHide() { // Hide the addon-bar browserWindow.setToolbarVisibility(container(), false); + test.assert(container().collapsed, + "1st window starts with an hidden addon-bar"); // Then open a browser window and verify that the addon-bar remains hidden tabBrowser.addTab("about:blank", { inNewWindow: true, onLoad: function(e) { - let browserWindow = e.target.defaultView; - let doc = browserWindow.document; - function container2() doc.getElementById("addon-bar"); + let browserWindow2 = e.target.defaultView; + let doc2 = browserWindow2.document; + function container2() doc2.getElementById("addon-bar"); function widgetCount2() container2() ? container2().childNodes.length : 0; let widgetStartCount2 = widgetCount2(); + test.assert(container2().collapsed, + "2nd window starts with an hidden addon-bar"); let w1Opts = {id:"first", label: "first widget", content: "first content"}; let w1 = testSingleWidget(w1Opts); - test.assertEqual(widgetCount2(), widgetStartCount2 + 1, "2nd window has correct number of child elements after widget creation"); - + test.assertEqual(widgetCount2(), widgetStartCount2 + 1, + "2nd window has correct number of child elements after" + + "widget creation"); w1.destroy(); - test.assertEqual(widgetCount2(), widgetStartCount2, "2nd window has correct number of child elements after widget destroy"); + test.assertEqual(widgetCount2(), widgetStartCount2, + "2nd window has correct number of child elements after" + + "widget destroy"); test.assert(container().collapsed, "1st window has an hidden addon-bar"); test.assert(container2().collapsed, "2nd window has an hidden addon-bar"); + // Reset addon-bar visibility before exiting this test browserWindow.setToolbarVisibility(container(), true); - closeBrowserWindow(browserWindow, function() { + closeBrowserWindow(browserWindow2, function() { doneTest(); }); }}); @@ -657,7 +666,7 @@ exports.testConstructor = function(test) { }; exports.testPanelWidget1 = function testPanelWidget1(test) { - const widgets = require("widget"); + const widgets = require("sdk/widget"); let widget1 = widgets.Widget({ id: "panel1", @@ -667,8 +676,8 @@ exports.testPanelWidget1 = function testPanelWidget1(test) { "evt.initEvent('click', true, true ); " + "document.body.dispatchEvent(evt);", contentScriptWhen: "end", - panel: require("panel").Panel({ - contentURL: "data:text/html,<body>Look ma, a panel!</body>", + panel: require("sdk/panel").Panel({ + contentURL: "data:text/html;charset=utf-8,<body>Look ma, a panel!</body>", onShow: function() { widget1.destroy(); test.pass("panel displayed on click"); @@ -680,7 +689,7 @@ exports.testPanelWidget1 = function testPanelWidget1(test) { }; exports.testPanelWidget2 = function testPanelWidget2(test) { - const widgets = require("widget"); + const widgets = require("sdk/widget"); test.assertRaises( function() { widgets.Widget({ @@ -695,7 +704,7 @@ exports.testPanelWidget2 = function testPanelWidget2(test) { }; exports.testPanelWidget3 = function testPanelWidget3(test) { - const widgets = require("widget"); + const widgets = require("sdk/widget"); let onClickCalled = false; let widget3 = widgets.Widget({ id: "panel3", @@ -709,8 +718,8 @@ exports.testPanelWidget3 = function testPanelWidget3(test) { onClickCalled = true; this.panel.show(); }, - panel: require("panel").Panel({ - contentURL: "data:text/html,<body>Look ma, a panel!</body>", + panel: require("sdk/panel").Panel({ + contentURL: "data:text/html;charset=utf-8,<body>Look ma, a panel!</body>", onShow: function() { test.assert( onClickCalled, @@ -727,7 +736,7 @@ exports.testPanelWidget3 = function testPanelWidget3(test) { exports.testWidgetMessaging = function testWidgetMessaging(test) { test.waitUntilDone(); let origMessage = "foo"; - const widgets = require("widget"); + const widgets = require("sdk/widget"); let widget = widgets.Widget({ id: "foo", label: "foo", @@ -748,7 +757,7 @@ exports.testWidgetMessaging = function testWidgetMessaging(test) { exports.testWidgetViews = function testWidgetViews(test) { test.waitUntilDone(); - const widgets = require("widget"); + const widgets = require("sdk/widget"); let widget = widgets.Widget({ id: "foo", label: "foo", @@ -772,7 +781,7 @@ exports.testWidgetViews = function testWidgetViews(test) { exports.testWidgetViewsUIEvents = function testWidgetViewsUIEvents(test) { test.waitUntilDone(); - const widgets = require("widget"); + const widgets = require("sdk/widget"); let view = null; let widget = widgets.Widget({ id: "foo", @@ -789,7 +798,7 @@ exports.testWidgetViewsUIEvents = function testWidgetViewsUIEvents(test) { onClick: function (eventView) { test.assertEqual(view, eventView, "event first argument is equal to the WidgetView"); - let view2 = widget.getView(require("windows").browserWindows.activeWindow); + let view2 = widget.getView(require("sdk/windows").browserWindows.activeWindow); test.assertEqual(view, view2, "widget.getView return the same WidgetView"); widget.destroy(); @@ -800,7 +809,7 @@ exports.testWidgetViewsUIEvents = function testWidgetViewsUIEvents(test) { exports.testWidgetViewsCustomEvents = function testWidgetViewsCustomEvents(test) { test.waitUntilDone(); - const widgets = require("widget"); + const widgets = require("sdk/widget"); let widget = widgets.Widget({ id: "foo", label: "foo", @@ -824,14 +833,14 @@ exports.testWidgetViewsCustomEvents = function testWidgetViewsCustomEvents(test) exports.testWidgetViewsTooltip = function testWidgetViewsTooltip(test) { test.waitUntilDone(); - const widgets = require("widget"); + const widgets = require("sdk/widget"); let widget = new widgets.Widget({ id: "foo", label: "foo", content: "foo" }); - let view = widget.getView(require("windows").browserWindows.activeWindow); + let view = widget.getView(require("sdk/windows").browserWindows.activeWindow); widget.tooltip = null; test.assertEqual(view.tooltip, "foo", "view tooltip defaults to base widget label"); @@ -844,8 +853,8 @@ exports.testWidgetViewsTooltip = function testWidgetViewsTooltip(test) { exports.testWidgetMove = function testWidgetMove(test) { test.waitUntilDone(); - let windowUtils = require("window-utils"); - let widgets = require("widget"); + let windowUtils = require("sdk/deprecated/window-utils"); + let widgets = require("sdk/widget"); let browserWindow = windowUtils.activeBrowserWindow; let doc = browserWindow.document; @@ -893,7 +902,7 @@ exports.testWidgetWithPound = function testWidgetWithPound(test) { test.waitUntilDone(); function getWidgetContent(widget) { - let windowUtils = require("window-utils"); + let windowUtils = require("sdk/deprecated/window-utils"); let browserWindow = windowUtils.activeBrowserWindow; let doc = browserWindow.document; let widgetNode = doc.querySelector('toolbaritem[label="' + widget.label + '"]'); @@ -901,7 +910,7 @@ exports.testWidgetWithPound = function testWidgetWithPound(test) { return widgetNode.firstChild.contentDocument.body.innerHTML; } - let widgets = require("widget"); + let widgets = require("sdk/widget"); let count = 0; let widget = widgets.Widget({ id: "1", @@ -922,6 +931,102 @@ exports.testWidgetWithPound = function testWidgetWithPound(test) { }); }; +exports.testContentScriptOptionsOption = function(test) { + test.waitUntilDone(); + + let widget = require("sdk/widget").Widget({ + id: "fooz", + label: "fooz", + content: "fooz", + contentScript: "self.postMessage( [typeof self.options.d, self.options] );", + contentScriptWhen: "end", + contentScriptOptions: {a: true, b: [1,2,3], c: "string", d: function(){ return 'test'}}, + onMessage: function(msg) { + test.assertEqual( msg[0], 'undefined', 'functions are stripped from contentScriptOptions' ); + test.assertEqual( typeof msg[1], 'object', 'object as contentScriptOptions' ); + test.assertEqual( msg[1].a, true, 'boolean in contentScriptOptions' ); + test.assertEqual( msg[1].b.join(), '1,2,3', 'array and numbers in contentScriptOptions' ); + test.assertEqual( msg[1].c, 'string', 'string in contentScriptOptions' ); + widget.destroy(); + test.done(); + } + }); +}; + +exports.testOnAttachWithoutContentScript = function(test) { + test.waitUntilDone(); + + let widget = require("sdk/widget").Widget({ + id: "onAttachNoCS", + label: "onAttachNoCS", + content: "onAttachNoCS", + onAttach: function (view) { + test.pass("received attach event"); + widget.destroy(); + test.done(); + } + }); +}; + +exports.testPostMessageOnAttach = function(test) { + test.waitUntilDone(); + + let widget = require("sdk/widget").Widget({ + id: "onAttach", + label: "onAttach", + content: "onAttach", + // 1) Send a message immediatly after `attach` event + onAttach: function (view) { + view.postMessage("ok"); + }, + // 2) Listen to it and forward it back to the widget + contentScript: "self.on('message', self.postMessage);", + // 3) Listen to this forwarded message + onMessage: function (msg) { + test.assertEqual( msg, "ok", "postMessage works on `attach` event"); + widget.destroy(); + test.done(); + } + }); +}; + +exports.testPostMessageOnLocationChange = function(test) { + test.waitUntilDone(); + + let attachEventCount = 0; + let messagesCount = 0; + let widget = require("sdk/widget").Widget({ + id: "onLocationChange", + label: "onLocationChange", + content: "onLocationChange", + contentScript: "new " + function ContentScriptScope() { + // Emit an event when content script is applied in order to know when + // the first document is loaded so that we can load the 2nd one + self.postMessage("ready"); + // And forward any incoming message back to the widget to see if + // messaging is working on 2nd document + self.on("message", self.postMessage); + }, + onMessage: function (msg) { + messagesCount++; + if (messagesCount == 1) { + test.assertEqual(msg, "ready", "First document is loaded"); + widget.content = "location changed"; + } + else if (messagesCount == 2) { + test.assertEqual(msg, "ready", "Second document is loaded"); + widget.postMessage("ok"); + } + else if (messagesCount == 3) { + test.assertEqual(msg, "ok", + "We receive the message sent to the 2nd document"); + widget.destroy(); + test.done(); + } + } + }); +}; + exports.testNavigationBarWidgets = function testNavigationBarWidgets(test) { test.waitUntilDone(); @@ -929,55 +1034,93 @@ exports.testNavigationBarWidgets = function testNavigationBarWidgets(test) { let w2 = widgets.Widget({id: "2nd", label: "2nd widget", content: "2"}); let w3 = widgets.Widget({id: "3rd", label: "3rd widget", content: "3"}); - // Hack to move 2nd and 3rd widgets manually to the navigation bar, in 5th - // position, i.e. after search box. 3rd widget will be in 5th and 2nd in 6th. + // First wait for all 3 widgets to be added to the current browser window + let firstAttachCount = 0; + function onAttachFirstWindow(widget) { + if (++firstAttachCount<3) + return; + onWidgetsReady(); + } + w1.once("attach", onAttachFirstWindow); + w2.once("attach", onAttachFirstWindow); + w3.once("attach", onAttachFirstWindow); + function getWidgetNode(toolbar, position) { return toolbar.getElementsByTagName("toolbaritem")[position]; } - let browserWindow = windowUtils.activeBrowserWindow; - let doc = browserWindow.document; - let addonBar = doc.getElementById("addon-bar"); - let w2Toolbaritem = getWidgetNode(addonBar, 1); - let w3ToolbarItem = getWidgetNode(addonBar, 2); - let navBar = doc.getElementById("nav-bar"); - navBar.insertItem(w2Toolbaritem.id, navBar.childNodes[6], null, false); - navBar.insertItem(w3ToolbarItem.id, navBar.childNodes[6], null, false); - // Widget and Firefox codes rely on this `currentset` attribute, - // so ensure it is correctly saved - navBar.setAttribute("currentset", navBar.currentSet); - doc.persist(navBar.id, "currentset"); - // Update addonbar too as we removed widget from there. - // Otherwise, widgets may still be added to this toolbar. - addonBar.setAttribute("currentset", addonBar.currentSet); - doc.persist(addonBar.id, "currentset"); - - tabBrowser.addTab("about:blank", { inNewWindow: true, onLoad: function(e) { - let browserWindow = e.target.defaultView; + function openBrowserWindow() { + let ww = Cc["@mozilla.org/embedcomp/window-watcher;1"]. + getService(Ci.nsIWindowWatcher); + let urlString = Cc["@mozilla.org/supports-string;1"]. + createInstance(Ci.nsISupportsString); + urlString.data = "about:blank"; + return ww.openWindow(null, "chrome://browser/content/browser.xul", + "_blank", "chrome,all,dialog=no", urlString); + } + + // Then move them before openeing a new browser window + function onWidgetsReady() { + // Hack to move 2nd and 3rd widgets manually to the navigation bar right after + // the search box. + let browserWindow = windowUtils.activeBrowserWindow; let doc = browserWindow.document; - let navBar = doc.getElementById("nav-bar"); let addonBar = doc.getElementById("addon-bar"); + let w2ToolbarItem = getWidgetNode(addonBar, 1); + let w3ToolbarItem = getWidgetNode(addonBar, 2); + let navBar = doc.getElementById("nav-bar"); + let searchBox = doc.getElementById("search-container"); + // Insert 3rd at the right of search box by adding it before its right sibling + navBar.insertItem(w3ToolbarItem.id, searchBox.nextSibling, null, false); + // Then insert 2nd before 3rd + navBar.insertItem(w2ToolbarItem.id, w3ToolbarItem, null, false); + // Widget and Firefox codes rely on this `currentset` attribute, + // so ensure it is correctly saved + navBar.setAttribute("currentset", navBar.currentSet); + doc.persist(navBar.id, "currentset"); + // Update addonbar too as we removed widget from there. + // Otherwise, widgets may still be added to this toolbar. + addonBar.setAttribute("currentset", addonBar.currentSet); + doc.persist(addonBar.id, "currentset"); + + // Wait for all widget to be attached to this new window before checking + // their position + let attachCount = 0; + let browserWindow2; + function onAttach(widget) { + if (++attachCount < 3) + return; + let doc = browserWindow2.document; + let addonBar = doc.getElementById("addon-bar"); + let searchBox = doc.getElementById("search-container"); + + // Ensure that 1st is in addon bar + test.assertEqual(getWidgetNode(addonBar, 0).getAttribute("label"), w1.label); + // And that 2nd and 3rd keep their original positions in navigation bar, + // i.e. right after search box + test.assertEqual(searchBox.nextSibling.getAttribute("label"), w2.label); + test.assertEqual(searchBox.nextSibling.nextSibling.getAttribute("label"), w3.label); - // Ensure that 1st is in addon bar - test.assertEqual(getWidgetNode(addonBar, 0).getAttribute("label"), w1.label); - // And that 2nd and 3rd keep their original positions in navigation bar - test.assertEqual(navBar.childNodes[5].getAttribute("label"), w3.label); - test.assertEqual(navBar.childNodes[6].getAttribute("label"), w2.label); + w1.destroy(); + w2.destroy(); + w3.destroy(); - w1.destroy(); - w2.destroy(); - w3.destroy(); + closeBrowserWindow(browserWindow2, function() { + test.done(); + }); + } + w1.on("attach", onAttach); + w2.on("attach", onAttach); + w3.on("attach", onAttach); - closeBrowserWindow(browserWindow, function() { - test.done(); - }); - }}); + browserWindow2 = openBrowserWindow(browserWindow); + } }; /******************* helpers *********************/ // Helper for calling code at window close function closeBrowserWindow(window, callback) { - require("timer").setTimeout(function() { + timer.setTimeout(function() { window.addEventListener("unload", function onUnload() { window.removeEventListener("unload", onUnload, false); callback(); @@ -992,19 +1135,18 @@ function closeBrowserWindow(window, callback) { // throw. In that case, remove all tests above from exports, and add one dummy // test that passes. try { - require("widget"); + require("sdk/widget"); } catch (err) { // This bug should be mentioned in the error message. let bug = "https://bugzilla.mozilla.org/show_bug.cgi?id=560716"; if (err.message.indexOf(bug) < 0) throw err; - for (let [prop, val] in Iterator(exports)) { - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; + + module.exports = { + testAppNotSupported: function (test) { + test.pass("the widget module does not support this application."); + } } - exports.testAppNotSupported = function (test) { - test.pass("widget does not support this application."); - }; } diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-loader.js b/tools/addon-sdk-1.12/test/test-window-loader.js index 0a5ab84..b8fecce 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-loader.js +++ b/tools/addon-sdk-1.12/test/test-window-loader.js @@ -3,8 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; -const { WindowLoader } = require('windows/loader'), - { Trait } = require('traits'); +const { WindowLoader } = require('sdk/windows/loader'), + { Trait } = require('sdk/deprecated/traits'); const Loader = Trait.compose( WindowLoader, diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-observer.js b/tools/addon-sdk-1.12/test/test-window-observer.js index 687df04..4a6264a 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-observer.js +++ b/tools/addon-sdk-1.12/test/test-window-observer.js @@ -4,15 +4,17 @@ "use strict"; -const { Loader } = require("./helpers"); +const { Loader } = require("sdk/test/loader"); +const timer = require("sdk/timers"); exports["test unload window observer"] = function(assert, done) { // Hacky way to be able to create unloadable modules via makeSandboxedLoader. let loader = Loader(module); - let utils = loader.require("api-utils/window-utils"); - let { isBrowser, activeBrowserWindow: activeWindow } = utils; - let observer = loader.require("api-utils/windows/observer").observer; + let utils = loader.require("sdk/deprecated/window-utils"); + let { activeBrowserWindow: activeWindow } = utils; + let { isBrowser } = require('sdk/window/utils'); + let observer = loader.require("sdk/windows/observer").observer; let opened = 0; let closed = 0; @@ -38,7 +40,7 @@ exports["test unload window observer"] = function(assert, done) { activeWindow.open().close(); // Enqueuing asserts to make sure that assertion is not performed early. - require("timer").setTimeout(function () { + timer.setTimeout(function () { assert.equal(1, opened, "observer open was called before unload only"); assert.equal(1, closed, "observer close was called before unload only"); done(); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils.js b/tools/addon-sdk-1.12/test/test-window-utils.js index 9985458..c93b0d4 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils.js +++ b/tools/addon-sdk-1.12/test/test-window-utils.js @@ -4,14 +4,14 @@ "use strict"; -var windowUtils = require("api-utils/window-utils"); -var timer = require("api-utils/timer"); +var windowUtils = require("sdk/deprecated/window-utils"); +var timer = require("sdk/timers"); var { Cc, Ci } = require("chrome"); -var { Loader } = require("./helpers"); +var { Loader, unload } = require("sdk/test/loader"); function toArray(iterator) { let array = []; - for each (let item in iterator()) + for each (let item in iterator) array.push(item); return array; } @@ -23,7 +23,7 @@ function makeEmptyWindow() { ' type="text/css"?>' + '<window xmlns="' + xulNs + '" windowtype="test:window">' + '</window>'); - var url = "data:application/vnd.mozilla.xul+xml," + escape(blankXul); + var url = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + escape(blankXul); var features = ["chrome", "width=10", "height=10"]; var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"] @@ -57,19 +57,20 @@ exports['test close on unload'] = function(assert) { }; let loader = Loader(module); - loader.require("window-utils").closeOnUnload(fakeWindow); + loader.require("sdk/deprecated/window-utils").closeOnUnload(fakeWindow); assert.equal(fakeWindow._listeners.length, 1, "unload listener added on closeOnUnload()"); assert.equal(timesClosed, 0, "window not closed when registered."); - loader.require("unload").send(); + loader.unload(); assert.equal(timesClosed, 1, "window closed on module unload."); assert.equal(fakeWindow._listeners.length, 0, "unload event listener removed on module unload"); timesClosed = 0; - loader.require("window-utils").closeOnUnload(fakeWindow); + loader = Loader(module); + loader.require("sdk/deprecated/window-utils").closeOnUnload(fakeWindow); assert.equal(timesClosed, 0, "window not closed when registered."); fakeWindow.close(); @@ -77,10 +78,9 @@ exports['test close on unload'] = function(assert) { "window closed when close() called."); assert.equal(fakeWindow._listeners.length, 0, "unload event listener removed on window close"); - loader.require("unload").send(); + loader.unload(); assert.equal(timesClosed, 1, "window not closed again on module unload."); - loader.unload(); }; exports['test window watcher'] = function(assert, done) { @@ -318,4 +318,33 @@ exports['test active window'] = function(assert, done) { nextTest(); }; +exports['test windowIterator'] = function(assert, done) { + // make a new window + let window = makeEmptyWindow(); + + // make sure that the window hasn't loaded yet + assert.notEqual( + window.document.readyState, + "complete", + "window hasn't loaded yet."); + + // this window should only appear in windowIterator() while its loading + assert.ok(toArray(windowUtils.windowIterator()).indexOf(window) === -1, + "window isn't in windowIterator()"); + + // Then it should be in windowIterator() + window.addEventListener("load", function onload() { + window.addEventListener("load", onload, false); + assert.ok(toArray(windowUtils.windowIterator()).indexOf(window) !== -1, + "window is now in windowIterator(false)"); + + // Wait for the window unload before ending test + window.addEventListener("unload", function onunload() { + window.addEventListener("unload", onunload, false); + done(); + }, false); + window.close(); + }, false); +} + require("test").run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils2.js b/tools/addon-sdk-1.12/test/test-window-utils2.js index 62f34f9..a169746 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-window-utils2.js +++ b/tools/addon-sdk-1.12/test/test-window-utils2.js @@ -5,16 +5,9 @@ 'use strict'; const { Ci } = require('chrome'); -const { open, backgroundify, - getXULWindow, getBaseWindow } = require('api-utils/window/utils'); -const windowUtils = require('api-utils/window-utils'); - -function windows(iterator) { - let array = []; - for each (let item in windowUtils.windowIterator()) - array.push(item); - return array; -} +const { open, backgroundify, windows, + getXULWindow, getBaseWindow } = require('sdk/window/utils'); +const windowUtils = require('sdk/deprecated/window-utils'); exports['test get nsIBaseWindow from nsIDomWindow'] = function(assert) { let active = windowUtils.activeBrowserWindow; @@ -35,13 +28,13 @@ exports['test get nsIXULWindow from nsIDomWindow'] = function(assert) { }; exports['test top window creation'] = function(assert) { - let window = open('data:text/html,Hello top window'); + let window = open('data:text/html;charset=utf-8,Hello top window'); assert.ok(~windows().indexOf(window), 'window was opened'); window.close(); }; exports['test new top window with options'] = function(assert) { - let window = open('data:text/html,Hi custom top window', { + let window = open('data:text/html;charset=utf-8,Hi custom top window', { name: 'test', features: { height: 100, width: 200, toolbar: true } }); @@ -54,7 +47,7 @@ exports['test new top window with options'] = function(assert) { }; exports['test backgroundify'] = function(assert) { - let window = open('data:text/html,backgroundy'); + let window = open('data:text/html;charset=utf-8,backgroundy'); assert.ok(~windows().indexOf(window), 'window is in the list of windows'); let backgroundy = backgroundify(window); diff --git a/tools/addon-sdk-1.12/test/test-windows-common.js b/tools/addon-sdk-1.12/test/test-windows-common.js new file mode 100644 index 0000000..05cd8bf --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-windows-common.js @@ -0,0 +1,59 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Loader } = require('sdk/test/loader'); +const { browserWindows } = require('sdk/windows'); + +// TEST: browserWindows Iterator +exports.testBrowserWindowsIterator = function(test) { + let activeWindowCount = 0; + let windows = []; + let i = 0; + for each (let window in browserWindows) { + if (window === browserWindows.activeWindow) + activeWindowCount++; + + test.assertEqual(windows.indexOf(window), -1, 'window not already in iterator'); + test.assertEqual(browserWindows[i++], window, 'browserWindows[x] works'); + windows.push(window); + } + test.assertEqual(activeWindowCount, 1, 'activeWindow was found in the iterator'); + + i = 0; + for (let j in browserWindows) { + test.assertEqual(j, i++, 'for (x in browserWindows) works'); + } +}; + +exports.testWindowTabsObject_alt = function(test) { + test.waitUntilDone(); + + let window = browserWindows.activeWindow; + window.tabs.open({ + url: "data:text/html;charset=utf-8,<title>tab 2</title>", + inBackground: true, + onReady: function onReady(tab) { + test.assertEqual(tab.title, "tab 2", "Correct new tab title"); + test.assertNotEqual(window.tabs.activeTab, tab, "Correct active tab"); + + // end test + tab.close(test.done()); + } + }); +}; + +// TEST: browserWindows.activeWindow +exports.testWindowActivateMethod_simple = function(test) { + let window = browserWindows.activeWindow; + let tab = window.tabs.activeTab; + + window.activate(); + + test.assertEqual(browserWindows.activeWindow, window, + "Active window is active after window.activate() call"); + test.assertEqual(window.tabs.activeTab, tab, + "Active tab is active after window.activate() call"); + +}; diff --git a/tools/addon-sdk-1.12/test/test-windows-private-browsing.js b/tools/addon-sdk-1.12/test/test-windows-private-browsing.js new file mode 100644 index 0000000..13bef93 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-windows-private-browsing.js @@ -0,0 +1,35 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Cc, Ci } = require('chrome'); +const { browserWindows } = require('sdk/windows'); +const { pb, pbUtils } = require('private-browsing-helper'); + +const wm = Cc['@mozilla.org/appshell/window-mediator;1']. + getService(Ci.nsIWindowMediator); + +if (pbUtils.isWindowPBEnabled(wm.getMostRecentWindow('navigator:browser'))) { + exports.testPerWindowPrivateBrowsing_getter = function(test) { + let activeWindow = wm. + getMostRecentWindow('navigator:browser'); + + // is per-window PB implemented? + let currentState = activeWindow.gPrivateBrowsingUI.privateWindow; + + pbUtils.setMode(false, activeWindow); + + test.assertEqual(activeWindow.gPrivateBrowsingUI.privateWindow, + browserWindows.activeWindow.isPrivateBrowsing, + 'Active window is not in PB mode'); + + pbUtils.setMode(true, activeWindow); + + test.assertEqual(activeWindow.gPrivateBrowsingUI.privateWindow, + browserWindows.activeWindow.isPrivateBrowsing, + 'Active window is in PB mode'); + + pbUtils.setMode(currentState, activeWindow); + }; +}
\ No newline at end of file diff --git a/tools/addon-sdk-1.12/test/test-windows.js b/tools/addon-sdk-1.12/test/test-windows.js new file mode 100644 index 0000000..064a0f6 --- /dev/null +++ b/tools/addon-sdk-1.12/test/test-windows.js @@ -0,0 +1,11 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +if (require("sdk/system/xul-app").is("Firefox")) { + module.exports = require("./windows/test-firefox-windows"); +} +else if (require("sdk/system/xul-app").is("Fennec")) { + module.exports = require("./windows/test-fennec-windows"); +} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xhr.js b/tools/addon-sdk-1.12/test/test-xhr.js index ad47e54..6cf585b 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xhr.js +++ b/tools/addon-sdk-1.12/test/test-xhr.js @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var xhr = require("xhr"); -var timer = require("timer"); -var { Loader } = require("./helpers"); -var xulApp = require("xul-app"); +var xhr = require("sdk/net/xhr"); +var timer = require("sdk/timers"); +var { Loader } = require("sdk/test/loader"); +var xulApp = require("sdk/system/xul-app"); /* Test is intentionally disabled until platform bug 707256 is fixed. exports.testAbortedXhr = function(test) { @@ -21,7 +21,7 @@ exports.testLocalXhr = function(test) { req.overrideMimeType("text/plain"); req.open("GET", module.uri); req.onreadystatechange = function() { - if (req.readyState == 4 && req.status == 0) { + if (req.readyState == 4 && (req.status == 0 || req.status == 200)) { test.assertMatches(req.responseText, /onreadystatechange/, "XMLHttpRequest should get local files"); @@ -39,7 +39,7 @@ exports.testLocalXhr = function(test) { exports.testUnload = function(test) { var loader = Loader(module); - var sbxhr = loader.require("xhr"); + var sbxhr = loader.require("sdk/net/xhr"); var req = new sbxhr.XMLHttpRequest(); req.overrideMimeType("text/plain"); req.open("GET", module.uri); @@ -54,12 +54,19 @@ exports.testResponseHeaders = function(test) { req.overrideMimeType("text/plain"); req.open("GET", module.uri); req.onreadystatechange = function() { - if (req.readyState == 4 && req.status == 0) { + if (req.readyState == 4 && (req.status == 0 || req.status == 200)) { var headers = req.getAllResponseHeaders(); if (xulApp.versionInRange(xulApp.platformVersion, "13.0a1", "*")) { - // Now that bug 608939 is FIXED, headers works correctly on files: - test.assertEqual(headers, "Content-Type: text/plain\n", - "XHR's headers are valid"); + headers = headers.split("\r\n"); + if(headers.length == 1) { + headers = headers[0].split("\n"); + } + for(let i in headers) { + if(headers[i] && headers[i].search("Content-Type") >= 0) { + test.assertEqual(headers[i], "Content-Type: text/plain", + "XHR's headers are valid"); + } + } } else { test.assert(headers === null || headers === "", diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xpcom.js b/tools/addon-sdk-1.12/test/test-xpcom.js index eda3565..17c7f1c 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xpcom.js +++ b/tools/addon-sdk-1.12/test/test-xpcom.js @@ -2,58 +2,61 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -const xpcom = require("api-utils/xpcom"); +const xpcom = require("sdk/platform/xpcom"); const { Cc, Ci, Cm, Cr } = require("chrome"); const { isCIDRegistered } = Cm.QueryInterface(Ci.nsIComponentRegistrar); -const { Loader } = require("./helpers"); +const { Class } = require("sdk/core/heritage"); +const { Loader } = require("sdk/test/loader"); exports['test Unknown implements nsISupports'] = function(assert) { - let actual = xpcom.Unknown.new(); + let actual = xpcom.Unknown(); assert.equal(actual.QueryInterface(Ci.nsISupports), actual, 'component implements nsISupports'); }; exports['test implement xpcom interfaces'] = function(assert) { - let component = xpcom.Unknown.extend({ + let WeakReference = Class({ + extends: xpcom.Unknown, interfaces: [ 'nsIWeakReference' ], QueryReferent: function() {} - }) + }); + let weakReference = WeakReference() - assert.equal(component.QueryInterface(Ci.nsISupports), - component, + assert.equal(weakReference.QueryInterface(Ci.nsISupports), + weakReference, 'component implements nsISupports'); - assert.equal(component.QueryInterface(Ci.nsIWeakReference), - component, + assert.equal(weakReference.QueryInterface(Ci.nsIWeakReference), + weakReference, 'component implements specified interface'); assert.throws(function() { component.QueryInterface(Ci.nsIObserver); }, "component does not implements interface"); - let actual = component.extend({ + let Observer = Class({ + extends: WeakReference, interfaces: [ 'nsIObserver', 'nsIRequestObserver' ], observe: function() {}, onStartRequest: function() {}, onStopRequest: function() {} }); + let observer = Observer() - assert.equal(actual.QueryInterface(Ci.nsISupports), - actual, + assert.equal(observer.QueryInterface(Ci.nsISupports), + observer, 'derived component implements nsISupports'); - assert.equal(actual.QueryInterface(Ci.nsIWeakReference), - actual, + assert.equal(observer.QueryInterface(Ci.nsIWeakReference), + observer, 'derived component implements supers interface'); - assert.equal(actual.QueryInterface(Ci.nsIObserver), - actual.QueryInterface(Ci.nsIRequestObserver), + assert.equal(observer.QueryInterface(Ci.nsIObserver), + observer.QueryInterface(Ci.nsIRequestObserver), 'derived component implements specified interfaces'); }; exports['test implement factory without contract'] = function(assert) { - let actual = xpcom.Factory.new({ - component: xpcom.Unknown.extend({ - get wrappedJSObject() this, - }) + let actual = xpcom.Factory({ + get wrappedJSObject() this, }); assert.ok(isCIDRegistered(actual.id), 'factory is regiseterd'); @@ -62,16 +65,17 @@ exports['test implement factory without contract'] = function(assert) { }; exports['test implement xpcom factory'] = function(assert) { - let Component = xpcom.Unknown.extend({ + let Component = Class({ + extends: xpcom.Unknown, interfaces: [ 'nsIObserver' ], get wrappedJSObject() this, observe: function() {} }); - let factory = xpcom.Factory.new({ + let factory = xpcom.Factory({ register: false, contract: '@jetpack/test/factory;1', - component: Component + Component: Component }); assert.ok(!isCIDRegistered(factory.id), 'factory is not registered'); @@ -80,7 +84,7 @@ exports['test implement xpcom factory'] = function(assert) { let actual = Cc[factory.contract].createInstance(Ci.nsIObserver); - assert.ok(Component.isPrototypeOf(actual.wrappedJSObject), + assert.ok(actual.wrappedJSObject instanceof Component, "createInstance returnes wrapped factory instances"); assert.notEqual(Cc[factory.contract].createInstance(Ci.nsIObserver), @@ -89,12 +93,13 @@ exports['test implement xpcom factory'] = function(assert) { }; exports['test implement xpcom service'] = function(assert) { - let actual = xpcom.Service.new({ + let actual = xpcom.Service({ contract: '@jetpack/test/service;1', register: false, - component: xpcom.Unknown.extend({ - get wrappedJSObject() this, + Component: Class({ + extends: xpcom.Unknown, interfaces: [ 'nsIObserver'], + get wrappedJSObject() this, observe: function() {}, name: 'my-service' }) @@ -115,11 +120,12 @@ exports['test implement xpcom service'] = function(assert) { function testRegister(assert, text) { - const service = xpcom.Service.new({ + const service = xpcom.Service({ description: 'test about:boop page', contract: '@mozilla.org/network/protocol/about;1?what=boop', register: false, - component: xpcom.Unknown.extend({ + Component: Class({ + extends: xpcom.Unknown, get wrappedJSObject() this, interfaces: [ 'nsIAboutModule' ], newChannel : function(aURI) { @@ -127,7 +133,7 @@ function testRegister(assert, text) { getService(Ci.nsIIOService); var channel = ios.newChannel( - "data:text/plain," + text, + "data:text/plain;charset=utf-8," + text, null, null ); @@ -181,20 +187,20 @@ exports["test re-register"] = function(assert) { exports["test unload"] = function(assert) { let loader = Loader(module); - let sbxpcom = loader.require("xpcom"); + let sbxpcom = loader.require("sdk/platform/xpcom"); - let auto = sbxpcom.Factory.new({ + let auto = sbxpcom.Factory({ contract: "@mozilla.org/test/auto-unload;1", description: "test auto", - component: sbxpcom.Unknown.extend({ name: 'auto' }) + name: "auto" }); - let manual = sbxpcom.Factory.new({ + let manual = sbxpcom.Factory({ contract: "@mozilla.org/test/manual-unload;1", description: "test manual", register: false, unregister: false, - component: sbxpcom.Unknown.extend({ name: 'manual' }) + name: "manual" }); assert.equal(isCIDRegistered(auto.id), true, 'component registered'); @@ -214,4 +220,4 @@ exports["test unload"] = function(assert) { 'component was manually unregistered on unload'); }; -require("test").run(exports) +require("test").run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xul-app.js b/tools/addon-sdk-1.12/test/test-xul-app.js index 58aa29e..c73f316 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-xul-app.js +++ b/tools/addon-sdk-1.12/test/test-xul-app.js @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var xulApp = require("xul-app"); +var xulApp = require("sdk/system/xul-app"); exports.testXulApp = function(test) { test.assertEqual(typeof(xulApp.ID), "string", diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/assert.js b/tools/addon-sdk-1.12/test/traits/assert.js index 7c385e4..5117ffb 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/assert.js +++ b/tools/addon-sdk-1.12/test/traits/assert.js @@ -4,7 +4,7 @@ "use strict"; -var BaseAssert = require("test/assert").Assert; +var BaseAssert = require("sdk/test/assert").Assert; /** * Whether or not given property descriptors are equivalent. They are diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/descriptor-tests.js b/tools/addon-sdk-1.12/test/traits/descriptor-tests.js index b775ff4..e11bc46 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/descriptor-tests.js +++ b/tools/addon-sdk-1.12/test/traits/descriptor-tests.js @@ -4,7 +4,7 @@ "use strict"; -var Trait = require("light-traits").Trait; +var Trait = require("sdk/deprecated/light-traits").Trait; var utils = require("./utils"); var Data = utils.Data; var Method = utils.Method; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/inheritance-tests.js b/tools/addon-sdk-1.12/test/traits/inheritance-tests.js index 3b311f9..9c3f8a7 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/inheritance-tests.js +++ b/tools/addon-sdk-1.12/test/traits/inheritance-tests.js @@ -4,7 +4,7 @@ "use strict"; -var Trait = require("light-traits").Trait; +var Trait = require("sdk/deprecated/light-traits").Trait; exports["test custom constructor and inherited toString"] = function(assert) { function Type() { diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/object-tests.js b/tools/addon-sdk-1.12/test/traits/object-tests.js index 6a94ff3..ea53d2d 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/object-tests.js +++ b/tools/addon-sdk-1.12/test/traits/object-tests.js @@ -4,7 +4,7 @@ "use strict"; -var Trait = require("light-traits").Trait; +var Trait = require("sdk/deprecated/light-traits").Trait; var utils = require("./utils"); var Data = utils.Data; var Method = utils.Method; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/utils.js b/tools/addon-sdk-1.12/test/traits/utils.js index 8426af7..8426af7 100644 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/traits/utils.js +++ b/tools/addon-sdk-1.12/test/traits/utils.js diff --git a/tools/addon-sdk-1.12/test/windows/test-fennec-windows.js b/tools/addon-sdk-1.12/test/windows/test-fennec-windows.js new file mode 100644 index 0000000..892d301 --- /dev/null +++ b/tools/addon-sdk-1.12/test/windows/test-fennec-windows.js @@ -0,0 +1,46 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +const { Cc, Ci } = require('chrome'); +const { setTimeout } = require('sdk/timers'); +const { Loader } = require('sdk/test/loader'); +const WM = Cc['@mozilla.org/appshell/window-mediator;1']. + getService(Ci.nsIWindowMediator); +const { browserWindows } = require('sdk/windows'); + +const ERR_MSG = 'This method is not yet supported by Fennec, consider using require("tabs") instead'; + +// TEST: browserWindows.length for Fennec +exports.testBrowserWindowsLength = function(test) { + test.assertEqual(browserWindows.length, 1, "Only one window open"); +}; + +// TEST: open & close window +exports.testOpenWindow = function(test) { + let tabCount = browserWindows.activeWindow.tabs.length; + let url = "data:text/html;charset=utf-8,<title>windows%20API%20test</title>"; + + try { + browserWindows.open({url: url}); + test.fail('Error was not thrown'); + } + catch(e) { + test.assertEqual(e.message, ERR_MSG, 'Error is thrown on windows.open'); + test.assertEqual(browserWindows.length, 1, "Only one window open"); + } +}; + +exports.testCloseWindow = function(test) { + let window = browserWindows.activeWindow; + + try { + window.close(); + test.fail('Error was not thrown'); + } + catch(e) { + test.assertEqual(e.message, ERR_MSG, 'Error is thrown on windows.close'); + test.assertEqual(browserWindows.length, 1, "Only one window open"); + } +}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-windows.js b/tools/addon-sdk-1.12/test/windows/test-firefox-windows.js index b85fec7..a0cd4f9 100644 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-windows.js +++ b/tools/addon-sdk-1.12/test/windows/test-firefox-windows.js @@ -1,23 +1,25 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; -const {Cc, Ci} = require("chrome"); -const { setTimeout } = require("timer"); -const { Loader } = require('./helpers'); -const wm = Cc["@mozilla.org/appshell/window-mediator;1"]. +const { Cc, Ci } = require('chrome'); +const { setTimeout } = require('sdk/timers'); +const { Loader } = require('sdk/test/loader'); +const wm = Cc['@mozilla.org/appshell/window-mediator;1']. getService(Ci.nsIWindowMediator); let browserWindows; -function getTestRunnerWindow() wm.getMostRecentWindow("test:runner") +function getTestRunnerWindow() wm.getMostRecentWindow("test:runner"); +// TEST: open & close window exports.testOpenAndCloseWindow = function(test) { test.waitUntilDone(); test.assertEqual(browserWindows.length, 1, "Only one window open"); browserWindows.open({ - url: "data:text/html,<title>windows API test</title>", + url: "data:text/html;charset=utf-8,<title>windows API test</title>", onOpen: function(window) { test.assertEqual(this, browserWindows, "The 'this' object is the windows object."); @@ -39,26 +41,26 @@ exports.testOpenAndCloseWindow = function(test) { }; exports.testAutomaticDestroy = function(test) { - test.waitUntilDone(); + let windows = browserWindows; // Create a second windows instance that we will unload let called = false; let loader = Loader(module); - let windows2 = loader.require("windows").browserWindows; + let windows2 = loader.require("sdk/windows").browserWindows; windows2.on("open", function() { called = true; }); - + loader.unload(); - + // Fire a windows event and check that this unloaded instance is inactive windows.open({ - url: "data:text/html,foo", + url: "data:text/html;charset=utf-8,foo", onOpen: function(window) { setTimeout(function () { - test.assert(!called, + test.assert(!called, "Unloaded windows instance is destroyed and inactive"); window.close(function () { test.done(); @@ -66,7 +68,37 @@ exports.testAutomaticDestroy = function(test) { }); } }); - +}; + +exports.testWindowTabsObject = function(test) { + test.waitUntilDone(); + + browserWindows.open({ + url: "data:text/html;charset=utf-8,<title>tab 1</title>", + onOpen: function onOpen(window) { + test.assertEqual(window.tabs.length, 1, "Only 1 tab open"); + + window.tabs.open({ + url: "data:text/html;charset=utf-8,<title>tab 2</title>", + inBackground: true, + onReady: function onReady(newTab) { + test.assertEqual(window.tabs.length, 2, "New tab open"); + test.assertEqual(newTab.title, "tab 2", "Correct new tab title"); + test.assertEqual(window.tabs.activeTab.title, "tab 1", "Correct active tab"); + + let i = 1; + for each (let tab in window.tabs) + test.assertEqual(tab.title, "tab " + i++, "Correct title"); + + window.close(); + } + }); + }, + onClose: function onClose(window) { + test.assertEqual(window.tabs.length, 0, "No more tabs on closed window"); + test.done(); + } + }); }; exports.testOnOpenOnCloseListeners = function(test) { @@ -128,46 +160,15 @@ exports.testOnOpenOnCloseListeners = function(test) { windows.open({ - url: "data:text/html,foo", + url: "data:text/html;charset=utf-8,foo", onOpen: function(window) { window.close(verify); } }); }; -exports.testWindowTabsObject = function(test) { - test.waitUntilDone(); - - browserWindows.open({ - url: "data:text/html,<title>tab 1</title>", - onOpen: function onOpen(window) { - test.assertEqual(window.tabs.length, 1, "Only 1 tab open"); - - window.tabs.open({ - url: "data:text/html,<title>tab 2</title>", - inBackground: true, - onReady: function onReady(newTab) { - test.assertEqual(window.tabs.length, 2, "New tab open"); - test.assertEqual(newTab.title, "tab 2", "Correct new tab title"); - test.assertEqual(window.tabs.activeTab.title, "tab 1", "Correct active tab"); - - let i = 1; - for each (let tab in window.tabs) - test.assertEqual(tab.title, "tab " + i++, "Correct title"); - - window.close(); - } - }); - }, - onClose: function onClose(window) { - test.assertEqual(window.tabs.length, 0, "No more tabs on closed window"); - test.done(); - } - }); -}; - exports.testActiveWindow = function(test) { - const xulApp = require("xul-app"); + const xulApp = require("sdk/system/xul-app"); if (xulApp.versionInRange(xulApp.platformVersion, "1.9.2", "1.9.2.*")) { test.pass("This test is disabled on 3.6. For more information, see bug 598525"); return; @@ -200,16 +201,16 @@ exports.testActiveWindow = function(test) { }, function() { /** - * Bug 614079: This test fails intermittently on some specific linux + * Bug 614079: This test fails intermittently on some specific linux * environnements, without being able to reproduce it in same * distribution with same window manager. * Disable it until being able to reproduce it easily. - + // On linux, focus is not consistent, so we can't be sure // what window will be on top. - // Here when we focus "non-browser" window, - // Any Browser window may be selected as "active". - test.assert(windows.activeWindow == window2 || windows.activeWindow == window3, + // Here when we focus "non-browser" window, + // Any Browser window may be selected as "active". + test.assert(windows.activeWindow == window2 || windows.activeWindow == window3, "Non-browser windows aren't handled by this module"); */ window2.activate(); @@ -228,13 +229,13 @@ exports.testActiveWindow = function(test) { ]; windows.open({ - url: "data:text/html,<title>window 2</title>", + url: "data:text/html;charset=utf-8,<title>window 2</title>", onOpen: function(window) { window2 = window; rawWindow2 = wm.getMostRecentWindow("navigator:browser"); windows.open({ - url: "data:text/html,<title>window 3</title>", + url: "data:text/html;charset=utf-8,<title>window 3</title>", onOpen: function(window) { window.tabs.activeTab.on('ready', function onReady() { window3 = window; @@ -288,22 +289,81 @@ exports.testActiveWindow = function(test) { } }; +exports.testTrackWindows = function(test) { + test.waitUntilDone(); + + let windows = []; + let actions = []; + + let expects = [ + "activate 0", "global activate 0", "deactivate 0", "global deactivate 0", + "activate 1", "global activate 1", "deactivate 1", "global deactivate 1", + "activate 2", "global activate 2" + ]; + + function shutdown(window) { + if (this.length === 1) { + test.assertEqual(actions.join(), expects.join(), + "correct activate and deactivate sequence") + + test.done(); + } + } + + function openWindow() { + windows.push(browserWindows.open({ + url: "data:text/html;charset=utf-8,<i>Hi</i>", + + onActivate: function(window) { + let index = windows.indexOf(window); + + actions.push("activate " + index); + + if (windows.length < 3) + openWindow() + else + for each (let win in windows) + win.close(shutdown) + }, + + onDeactivate: function(window) { + let index = windows.indexOf(window); + + actions.push("deactivate " + index) + } + })); + } + + browserWindows.on("activate", function (window) { + let index = windows.indexOf(window); + + actions.push("global activate " + index) + }) + + browserWindows.on("deactivate", function (window) { + let index = windows.indexOf(window); + + actions.push("global deactivate " + index) + }) + + openWindow(); +} + // If the module doesn't support the app we're being run in, require() will // throw. In that case, remove all tests above from exports, and add one dummy // test that passes. try { - browserWindows = require("windows").browserWindows; + browserWindows = require("sdk/windows").browserWindows; } catch (err) { // This bug should be mentioned in the error message. let bug = "https://bugzilla.mozilla.org/show_bug.cgi?id=571449"; if (err.message.indexOf(bug) < 0) throw err; - for (let [prop, val] in Iterator(exports)) { - if (/^test/.test(prop) && typeof(val) === "function") - delete exports[prop]; + + module.exports = { + testAppNotSupported: function (test) { + test.pass("the windows module does not support this application."); + } } - exports.testAppNotSupported = function (test) { - test.pass("the windows module does not support this application."); - }; } diff --git a/tools/addon-sdk-1.7/examples/library-detector/data/widget.js b/tools/addon-sdk-1.7/examples/library-detector/data/widget.js deleted file mode 100755 index 293537e..0000000 --- a/tools/addon-sdk-1.7/examples/library-detector/data/widget.js +++ /dev/null @@ -1,14 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -function setLibraryInfo(element) { - self.port.emit('setLibraryInfo', element.target.title); -} - -var elements = document.getElementsByTagName('img'); - -for (var i = 0; i < elements.length; i++) { - elements[i].addEventListener('mouseover', setLibraryInfo, false); -} diff --git a/tools/addon-sdk-1.7/examples/library-detector/lib/main.js b/tools/addon-sdk-1.7/examples/library-detector/lib/main.js deleted file mode 100755 index 4380c6f..0000000 --- a/tools/addon-sdk-1.7/examples/library-detector/lib/main.js +++ /dev/null @@ -1,107 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const tabs = require('tabs'); -const widgets = require('widget'); -const data = require('self').data; -const pageMod = require('page-mod'); -const panel = require('panel'); - -const htmlContentPreamble = - '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' + - ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' + - ' <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">' + - ' <head>' + - ' <style type="text/css" media="all">' + - ' img {display: inline;}' + - ' </style>' + - ' </head>' + - ' <body>' - -const htmlContentPostamble = - ' </body>' + - '</html>' - -const icons = { - 'jQuery' : 'jquery.ico', - 'jQuery UI' : 'jquery_ui.ico', - 'MooTools' : 'mootools.png', - 'YUI' : 'yui.ico', - 'Closure' : 'closure.ico', - 'Modernizr': 'modernizr.ico', -} - -const ICON_WIDTH = 32; - -function buildIconHtml(imageName, libraryInfo) { - return '<img src="' + data.url("icons/" + imageName) + '" title="' + libraryInfo + '">'; -} - -function buildWidgetViewContent(libraryList) { - widgetContent = htmlContentPreamble; - libraryList.forEach(function(library) { - widgetContent += buildIconHtml(icons[library.name], library.name + "<br>Version: " + library.version); - }); - widgetContent += htmlContentPostamble; - return widgetContent; -} - -function updateWidgetView(tab) { - let widgetView = widget.getView(tab.window); - if (!tab.libraries) { - tab.libraries = []; - } - widgetView.content = buildWidgetViewContent(tab.libraries); - widgetView.width = tab.libraries.length * ICON_WIDTH; -} - -var widget = widgets.Widget({ - id: "library-detector", - label: "Library Detector", - content: "<html></html>", - contentScriptFile: data.url("widget.js"), - panel: panel.Panel({ - width: 240, - height: 60, - contentScript: 'self.on("message", function(libraryInfo) {' + - ' window.document.body.innerHTML = libraryInfo;' + - '});' - }), -}); - -widget.port.on('setLibraryInfo', function(libraryInfo) { - widget.panel.postMessage(libraryInfo); -}); - -pageMod.PageMod({ - include: "*", - contentScriptWhen: 'end', - contentScriptFile: (data.url('library-detector.js')), - onAttach: function(worker) { - worker.on('message', function(libraryList) { - if (!worker.tab.libraries) { - worker.tab.libraries = []; - } - libraryList.forEach(function(library) { - if (worker.tab.libraries.indexOf(library) == -1) { - worker.tab.libraries.push(library); - } - }); - if (worker.tab == tabs.activeTab) { - updateWidgetView(worker.tab); - } - }); - } -}); - -tabs.on('activate', function(tab) { - updateWidgetView(tab); -}); - -/* -For change of location -*/ -tabs.on('ready', function(tab) { - tab.libraries = []; -});
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/addon-kit/README.md b/tools/addon-sdk-1.7/packages/addon-kit/README.md deleted file mode 100644 index cfbb4df..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/README.md +++ /dev/null @@ -1,12 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The addon-kit package provides high-level APIs for add-on developers. -Most of the needs of most add-on developers should be served by the modules -found here. Modules in this packages don't require any special privileges to -run. - -The modules in the addon-kit package are relatively stable. We intend to add -new APIs here and extend existing ones, but will avoid making incompatible -changes to them unless absolutely necessary. diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/clipboard.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/clipboard.md deleted file mode 100644 index 387766e..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/clipboard.md +++ /dev/null @@ -1,62 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Dietrich Ayala [dietrich@mozilla.com] --> - -The `clipboard` module allows callers to interact with the system clipboard, -setting and retrieving its contents. - -You can optionally specify the type of the data to set and retrieve. -The following types are supported: - -* `text` (plain text) -* `html` (a string of HTML) - -If no data type is provided, then the module will detect it for you. - -Examples --------- - -Set and get the contents of the clipboard. - - let clipboard = require("clipboard"); - clipboard.set("Lorem ipsum dolor sit amet"); - let contents = clipboard.get(); - -Set the clipboard contents to some HTML. - - let clipboard = require("clipboard"); - clipboard.set("<blink>Lorem ipsum dolor sit amet</blink>", "html"); - -If the clipboard contains HTML content, open it in a new tab. - - let clipboard = require("clipboard"); - if (clipboard.currentFlavors.indexOf("html") != -1) - require("tabs").open("data:text/html," + clipboard.get("html")); - -<api name="set"> -@function - Replace the contents of the user's clipboard with the provided data. -@param data {string} - The data to put on the clipboard. -@param [datatype] {string} - The type of the data (optional). -</api> - -<api name="get"> -@function - Get the contents of the user's clipboard. -@param [datatype] {string} - Retrieve the clipboard contents only if matching this type (optional). - The function will return null if the contents of the clipboard do not match - the supplied type. -</api> - -<api name="currentFlavors"> -@property {array} - Data on the clipboard is sometimes available in multiple types. For example, - HTML data might be available as both a string of HTML (the `html` type) - and a string of plain text (the `text` type). This function returns an array - of all types in which the data currently on the clipboard is available. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/context-menu.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/context-menu.md deleted file mode 100644 index 28fb35a..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/context-menu.md +++ /dev/null @@ -1,719 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `context-menu` module lets you add items to Firefox's page context menu. - - -Introduction ------------- - -The `context-menu` API provides a simple, declarative way to add items to the -page's context menu. You can add items that perform an action when clicked, -submenus, and menu separators. - -Instead of manually adding items when particular contexts occur and then -removing them when those contexts go away, you *bind* items to contexts, and the -adding and removing is automatically handled for you. Items are bound to -contexts in much the same way that event listeners are bound to events. When -the user invokes the context menu, all of the items bound to the current context -are automatically added to the menu. If no items are bound, none are added. -Likewise, any items that were previously in the menu but are not bound to the -current context are automatically removed from the menu. You never need to -manually remove your items from the menu unless you want them to never appear -again. - -For example, if your add-on needs to add a context menu item whenever the -user visits a certain page, don't create the item when that page loads, and -don't remove it when the page unloads. Rather, create your item only once and -supply a context that matches the target URL. - - -Specifying Contexts -------------------- - -As its name implies, the context menu should be reserved for the occurrence of -specific contexts. Contexts can be related to page content or the page itself, -but they should never be external to the page. - -For example, a good use of the menu would be to show an "Edit Image" item when -the user right-clicks an image in the page. A bad use would be to show a -submenu that listed all the user's tabs, since tabs aren't related to the page -or the node the user clicked to open the menu. - -### The Page Context - -First of all, you may not need to specify a context at all. When an item does -not specify a context, the page context applies. - -The *page context* occurs when the user invokes the context menu on a -non-interactive portion of the page. Try right-clicking a blank spot in this -page, or on text. Make sure that no text is selected. The menu that appears -should contain the items "Back", "Forward", "Reload", "Stop", and so on. This -is the page context. - -The page context is appropriate when your item acts on the page as a whole. It -does not occur when the user invokes the context menu on a link, image, or other -non-text node, or while a selection exists. - -### Declarative Contexts - -You can specify some simple, declarative contexts when you create a menu item by -setting the `context` property of the options object passed to its constructor, -like this: - - var cm = require("context-menu"); - cm.Item({ - label: "My Menu Item", - context: cm.URLContext("*.mozilla.org") - }); - -These contexts may be specified by calling the following constructors. Each is -exported by the `context-menu` module. - -<table> - <tr> - <th>Constructor</th> - <th>Description</th> - </tr> - <tr> - <td><code> - PageContext() - </code></td> - <td> - The page context. - </td> - </tr> - <tr> - <td><code> - SelectionContext() - </code></td> - <td> - This context occurs when the menu is invoked on a page in which the user - has made a selection. - </td> - </tr> - <tr> - <td><code> - SelectorContext(selector) - </code></td> - <td> - This context occurs when the menu is invoked on a node that either matches - <code>selector</code>, a CSS selector, or has an ancestor that matches. - <code>selector</code> may include multiple selectors separated by commas, - e.g., <code>"a[href], img"</code>. - </td> - </tr> - <tr> - <td><code> - URLContext(matchPattern) - </code></td> - <td> - This context occurs when the menu is invoked on pages with particular - URLs. <code>matchPattern</code> is a match pattern string or an array of - match pattern strings. When <code>matchPattern</code> is an array, the - context occurs when the menu is invoked on a page whose URL matches any of - the patterns. These are the same match pattern strings that you use with - the <a href="packages/addon-kit/page-mod.html"><code>page-mod</code></a> - <code>include</code> property. - <a href="packages/api-utils/match-pattern.html">Read more about patterns</a>. - </td> - </tr> - <tr> - <td> - array - </td> - <td> - An array of any of the other types. This context occurs when all contexts - in the array occur. - </td> - </tr> -</table> - -Menu items also have a `context` property that can be used to add and remove -declarative contexts after construction. For example: - - var context = require("context-menu").SelectorContext("img"); - myMenuItem.context.add(context); - myMenuItem.context.remove(context); - -When a menu item is bound to more than one context, it appears in the menu when -all of those contexts occur. - -### In Content Scripts - -The declarative contexts are handy but not very powerful. For instance, you -might want your menu item to appear for any page that has at least one image, -but declarative contexts won't help you there. - -When you need more control control over the context in which your menu items are -shown, you can use content scripts. Like other APIs in the SDK, the -`context-menu` API uses -[content scripts](dev-guide/guides/content-scripts/index.html) to let your -add-on interact with pages in the browser. Each menu item you create in the -top-level context menu can have a content script. - -A special event named `"context"` is emitted in your content scripts whenever -the context menu is about to be shown. If you register a listener function for -this event and it returns true, the menu item associated with the listener's -content script is shown in the menu. - -For example, this item appears whenever the context menu is invoked on a page -that contains at least one image: - - require("context-menu").Item({ - label: "This Page Has Images", - contentScript: 'self.on("context", function (node) {' + - ' return !!document.querySelector("img");' + - '});' - }); - -Note that the listener function has a parameter called `node`. This is the node -in the page that the user context-clicked to invoke the menu. You can use it to -determine whether your item should be shown. - -You can both specify declarative contexts and listen for contexts in a content -script. In that case, the declarative contexts are evaluated first. If they -are not current, then your context listener is never called. - -This example takes advantage of that fact. The listener can be assured that -`node` will always be an image: - - var cm = require("context-menu"); - cm.Item({ - label: "A Mozilla Image", - context: cm.SelectorContext("img"), - contentScript: 'self.on("context", function (node) {' + - ' return /mozilla/.test(node.src);' + - '});' - }); - -Your item is shown only when all declarative contexts are current and your -context listener returns true. - - -Handling Menu Item Clicks -------------------------- - -In addition to using content scripts to listen for the `"context"` event as -described above, you can use content scripts to handle item clicks. When the -user clicks your menu item, an event named `"click"` is emitted in the item's -content script. - -Therefore, to handle an item click, listen for the `"click"` event in that -item's content script like so: - - require("context-menu").Item({ - label: "My Item", - contentScript: 'self.on("click", function (node, data) {' + - ' console.log("Item clicked!");' + - '});' - }); - -Note that the listener function has parameters called `node` and `data`. `node` -is the node that the user context-clicked to invoke the menu. You can use it -when performing some action. `data` is the `data` property of the menu item -that was clicked. Since only top-level menu items have content scripts, this -comes in handy for determining which item in a `Menu` was clicked: - - var cm = require("context-menu"); - cm.Menu({ - label: "My Menu", - contentScript: 'self.on("click", function (node, data) {' + - ' console.log("You clicked " + data);' + - '});', - items: [ - cm.Item({ label: "Item 1", data: "item1" }), - cm.Item({ label: "Item 2", data: "item2" }), - cm.Item({ label: "Item 3", data: "item3" }) - ] - }); - -Often you will need to collect some kind of information in the click listener -and perform an action unrelated to content. To communicate to the menu item -associated with the content script, the content script can call the -`postMessage` function attached to the global `self` object, passing it some -JSON-able data. The menu item's `"message"` event listener will be called with -that data. - - var cm = require("context-menu"); - cm.Item({ - label: "Edit Image", - context: cm.SelectorContext("img"), - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage(node.src);' + - '});', - onMessage: function (imgSrc) { - openImageEditor(imgSrc); - } - }); - - -Updating a Menu Item's Label ----------------------------- - -Each menu item must be created with a label, but you can change its label later -using a couple of methods. - -The simplest method is to set the menu item's `label` property. This example -updates the item's label based on the number of times it's been clicked: - - var numClicks = 0; - var myItem = require("context-menu").Item({ - label: "Click Me: " + numClicks, - contentScript: 'self.on("click", self.postMessage);', - onMessage: function () { - numClicks++; - this.label = "Click Me: " + numClicks; - // Setting myItem.label is equivalent. - } - }); - -Sometimes you might want to update the label based on the context. For -instance, if your item performs a search with the user's selected text, it would -be nice to display the text in the item to provide feedback to the user. In -these cases you can use the second method. Recall that your content scripts can -listen for the `"context"` event and if your listeners return true, the items -associated with the content scripts are shown in the menu. In addition to -returning true, your `"context"` listeners can also return strings. When a -`"context"` listener returns a string, it becomes the item's new label. - -This item implements the aforementioned search example: - - var cm = require("context-menu"); - cm.Item({ - label: "Search Google", - context: cm.SelectionContext(), - contentScript: 'self.on("context", function () {' + - ' var text = window.getSelection().toString();' + - ' if (text.length > 20)' + - ' text = text.substr(0, 20) + "...";' + - ' return "Search Google for " + text;' + - '});' - }); - -The `"context"` listener gets the window's current selection, truncating it if -it's too long, and includes it in the returned string. When the item is shown, -its label will be "Search Google for `text`", where `text` is the truncated -selection. - - -More Examples -------------- - -For conciseness, these examples create their content scripts as strings and use -the `contentScript` property. In your own add-on, you will probably want to -create your content scripts in separate files and pass their URLs using the -`contentScriptFile` property. See -[Working with Content Scripts](dev-guide/guides/content-scripts/index.html) -for more information. - -<div class="warning"> -<p>Unless your content script is extremely simple and consists only of a -static string, don't use <code>contentScript</code>: if you do, you may -have problems getting your add-on approved on AMO.</p> -<p>Instead, keep the script in a separate file and load it using -<code>contentScriptFile</code>. This makes your code easier to maintain, -secure, debug and review.</p> -</div> - -Show an "Edit Page Source" item when the user right-clicks a non-interactive -part of the page: - - require("context-menu").Item({ - label: "Edit Page Source", - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage(document.URL);' + - '});', - onMessage: function (pageURL) { - editSource(pageURL); - } - }); - -Show an "Edit Image" item when the menu is invoked on an image: - - var cm = require("context-menu"); - cm.Item({ - label: "Edit Image", - context: cm.SelectorContext("img"), - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage(node.src);' + - '});', - onMessage: function (imgSrc) { - openImageEditor(imgSrc); - } - }); - -Show an "Edit Mozilla Image" item when the menu is invoked on an image in a -mozilla.org or mozilla.com page: - - var cm = require("context-menu"); - cm.Item({ - label: "Edit Mozilla Image", - context: [ - cm.URLContext(["*.mozilla.org", "*.mozilla.com"]), - cm.SelectorContext("img") - ], - contentScript: 'self.on("click", function (node, data) {' + - ' self.postMessage(node.src);' + - '});', - onMessage: function (imgSrc) { - openImageEditor(imgSrc); - } - }); - -Show an "Edit Page Images" item when the page contains at least one image: - - var cm = require("context-menu"); - cm.Item({ - label: "Edit Page Images", - // This ensures the item only appears during the page context. - context: cm.PageContext(), - contentScript: 'self.on("context", function (node) {' + - ' var pageHasImgs = !!document.querySelector("img");' + - ' return pageHasImgs;' + - '});' + - 'self.on("click", function (node, data) {' + - ' var imgs = document.querySelectorAll("img");' + - ' var imgSrcs = [];' + - ' for (var i = 0 ; i < imgs.length; i++)' + - ' imgSrcs.push(imgs[i].src);' + - ' self.postMessage(imgSrcs);' + - '});', - onMessage: function (imgSrcs) { - openImageEditor(imgSrcs); - } - }); - -Show a "Search With" menu when the user right-clicks an anchor that searches -Google or Wikipedia with the text contained in the anchor: - - var cm = require("context-menu"); - var googleItem = cm.Item({ - label: "Google", - data: "http://www.google.com/search?q=" - }); - var wikipediaItem = cm.Item({ - label: "Wikipedia", - data: "http://en.wikipedia.org/wiki/Special:Search?search=" - }); - var searchMenu = cm.Menu({ - label: "Search With", - context: cm.SelectorContext("a[href]"), - contentScript: 'self.on("click", function (node, data) {' + - ' var searchURL = data + node.textContent;' + - ' window.location.href = searchURL;' + - '});', - items: [googleItem, wikipediaItem] - }); - - -<api name="Item"> -@class -A labeled menu item that can perform an action when clicked. -<api name="Item"> -@constructor - Creates a labeled menu item that can perform an action when clicked. -@param options {object} - An object with the following keys: - @prop label {string} - The item's label. It must either be a string or an object that implements - `toString()`. - @prop [image] {string} - The item's icon, a string URL. The URL can be remote, a reference to an - image in the add-on's `data` directory, or a data URI. - @prop [data] {string} - An optional arbitrary value to associate with the item. It must be either a - string or an object that implements `toString()`. It will be passed to - click listeners. - @prop [context] {value} - If the item is contained in the top-level context menu, this declaratively - specifies the context under which the item will appear; see Specifying - Contexts above. Ignored if the item is contained in a submenu. - @prop [contentScript] {string,array} - If the item is contained in the top-level context menu, this is the content - script or an array of content scripts that the item can use to interact with - the page. Ignored if the item is contained in a submenu. - @prop [contentScriptFile] {string,array} - If the item is contained in the top-level context menu, this is the local - file URL of the content script or an array of such URLs that the item can - use to interact with the page. Ignored if the item is contained in a - submenu. - @prop [onMessage] {function} - If the item is contained in the top-level context menu, this function will - be called when the content script calls `self.postMessage`. It will be - passed the data that was passed to `postMessage`. Ignored if the item is - contained in a submenu. -</api> - -<api name="label"> -@property {string} - The menu item's label. You can set this after creating the item to update its - label later. -</api> - -<api name="image"> -@property {string} - The item's icon, a string URL. The URL can be remote, a reference to an image - in the add-on's `data` directory, or a data URI. You can set this after - creating the item to update its image later. To remove the item's image, set - it to `null`. -</api> - -<api name="data"> -@property {string} - An optional arbitrary value to associate with the item. It must be either a - string or an object that implements `toString()`. It will be passed to - click listeners. You can set this after creating the item to update its data - later. -</api> - -<api name="context"> -@property {list} - A list of declarative contexts for which the menu item will appear in the - context menu. Contexts can be added by calling `context.add()` and removed by - called `context.remove()`. This property is meaningful only for items - contained in the top-level context menu. -</api> - -<api name="parentMenu"> -@property {Menu} - The item's parent `Menu`, or `null` if the item is contained in the top-level - context menu. This property is read-only. To add the item to a new menu, - call that menu's `addItem()` method. -</api> - -<api name="contentScript"> -@property {string,array} - The content script or the array of content scripts associated with the menu - item during creation. This property is meaningful only for items contained in - the top-level context menu. -</api> - -<api name="contentScriptFile"> -@property {string,array} - The URL of a content script or the array of such URLs associated with the menu - item during creation. This property is meaningful only for items contained in - the top-level context menu. -</api> - -<api name="destroy"> -@method - Permanently removes the item from its parent menu and frees its resources. - The item must not be used afterward. If you need to remove the item from its - parent menu but use it afterward, call `removeItem()` on the parent menu - instead. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this menu item. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the menu item's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -</api> - -<api name="Menu"> -@class -A labeled menu item that expands into a submenu. - -<api name="Menu"> -@constructor - Creates a labeled menu item that expands into a submenu. -@param options {object} - An object with the following keys: - @prop label {string} - The item's label. It must either be a string or an object that implements - `toString()`. - @prop items {array} - An array of menu items that the menu will contain. Each must be an `Item`, - `Menu`, or `Separator`. - @prop [image] {string} - The menu's icon, a string URL. The URL can be remote, a reference to an - image in the add-on's `data` directory, or a data URI. - @prop [context] {value} - If the menu is contained in the top-level context menu, this declaratively - specifies the context under which the menu will appear; see Specifying - Contexts above. Ignored if the menu is contained in a submenu. - @prop [contentScript] {string,array} - If the menu is contained in the top-level context menu, this is the content - script or an array of content scripts that the menu can use to interact with - the page. Ignored if the menu is contained in a submenu. - @prop [contentScriptFile] {string,array} - If the menu is contained in the top-level context menu, this is the local - file URL of the content script or an array of such URLs that the menu can - use to interact with the page. Ignored if the menu is contained in a - submenu. - @prop [onMessage] {function} - If the menu is contained in the top-level context menu, this function will - be called when the content script calls `self.postMessage`. It will be - passed the data that was passed to `postMessage`. Ignored if the item is - contained in a submenu. -</api> - -<api name="label"> -@property {string} - The menu's label. You can set this after creating the menu to update its - label later. -</api> - -<api name="items"> -@property {array} - An array containing the items in the menu. The array is read-only, meaning - that modifications to it will not affect the menu. However, setting this - property to a new array will replace all the items currently in the menu with - the items in the new array. -</api> - -<api name="image"> -@property {string} - The menu's icon, a string URL. The URL can be remote, a reference to an image - in the add-on's `data` directory, or a data URI. You can set this after - creating the menu to update its image later. To remove the menu's image, set - it to `null`. -</api> - -<api name="context"> -@property {list} - A list of declarative contexts for which the menu will appear in the context - menu. Contexts can be added by calling `context.add()` and removed by called - `context.remove()`. This property is meaningful only for menus contained in - the top-level context menu. -</api> - -<api name="parentMenu"> -@property {Menu} - The menu's parent `Menu`, or `null` if the menu is contained in the top-level - context menu. This property is read-only. To add the menu to a new menu, - call that menu's `addItem()` method. -</api> - -<api name="contentScript"> -@property {string,array} - The content script or the array of content scripts associated with the menu - during creation. This property is meaningful only for menus contained in the - top-level context menu. -</api> - -<api name="contentScriptFile"> -@property {string,array} - The URL of a content script or the array of such URLs associated with the menu - during creation. This property is meaningful only for menus contained in the - top-level context menu. -</api> - -<api name="addItem"> -@method - Appends a menu item to the end of the menu. If the item is already contained - in another menu or in the top-level context menu, it's automatically removed - first. -@param item {Item,Menu,Separator} - The `Item`, `Menu`, or `Separator` to add to the menu. -</api> - -<api name="removeItem"> -@method - Removes the given menu item from the menu. If the menu does not contain the - item, this method does nothing. -@param item {Item,Menu,Separator} - The menu item to remove from the menu. -</api> - -<api name="destroy"> -@method - Permanently removes the menu from its parent menu and frees its resources. - The menu must not be used afterward. If you need to remove the menu from its - parent menu but use it afterward, call `removeItem()` on the parent menu - instead. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this menu item. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the menu item's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -</api> - -<api name="Separator"> -@class -A menu separator. Separators can be contained only in `Menu`s, not in the -top-level context menu. - -<api name="Separator"> -@constructor - Creates a menu separator. -</api> - -<api name="parentMenu"> -@property {Menu} - The separator's parent `Menu`. This property is read-only. To add the - separator to a new menu, call that menu's `addItem()` method. -</api> - -<api name="destroy"> -@method - Permanently removes the separator from its parent menu and frees its - resources. The separator must not be used afterward. If you need to remove - the separator from its parent menu but use it afterward, call `removeItem()` - on the parent menu instead. -</api> - -</api> - -<api name="PageContext"> -@class -<api name="PageContext"> -@constructor - Creates a page context. See Specifying Contexts above. -</api> -</api> - -<api name="SelectionContext"> -@class -<api name="SelectionContext"> -@constructor - Creates a context that occurs when a page contains a selection. See - Specifying Contexts above. -</api> -</api> - -<api name="SelectorContext"> -@class -<api name="SelectorContext"> -@constructor - Creates a context that matches a given CSS selector. See Specifying Contexts - above. -@param selector {string} - A CSS selector. -</api> -</api> - -<api name="URLContext"> -@class -<api name="URLContext"> -@constructor - Creates a context that matches pages with particular URLs. See Specifying - Contexts above. -@param matchPattern {string,array} - A [match pattern](packages/api-utils/match-pattern.html) string or an array of - match pattern strings. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/hotkeys.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/hotkeys.md deleted file mode 100644 index b12791c..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/hotkeys.md +++ /dev/null @@ -1,78 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -Some add-ons may wish to define keyboard shortcuts for certain operations. This -module exposes an API to create those. - -<api name="Hotkey"> -@class - -Module exports `Hotkey` constructor allowing users to create a `hotkey` for the -host application. - -<api name="Hotkey"> -@constructor -Creates a hotkey who's `onPress` listener method is invoked when key combination -defined by `hotkey` is pressed. - -Please note: If more than one `hotkey` is created for the same key -combination, the listener is executed only on the last one created - -@param options {Object} - Options for the hotkey, with the following keys: - -@prop combo {String} -Any function key: `"f1, f2, ..., f24"` or key combination in the format -of `'modifier-key'`: - - "accel-s" - "meta-shift-i" - "control-alt-d" - -Modifier keynames: - -- **shift**: The Shift key. -- **alt**: The Alt key. On the Macintosh, this is the Option key. On - Macintosh this can only be used in conjunction with another modifier, - since `Alt-Letter` combinations are reserved for entering special - characters in text. -- **meta**: The Meta key. On the Macintosh, this is the Command key. -- **control**: The Control key. -- **accel**: The key used for keyboard shortcuts on the user's platform, - which is Control on Windows and Linux, and Command on Mac. Usually, this - would be the value you would use. - -@prop onPress {Function} -Function that is invoked when the key combination `hotkey` is pressed. - -</api> -<api name="destroy"> -@method -Stops this instance of `Hotkey` from reacting on the key combinations. Once -destroyed it can no longer be used. -</api> -</api> - -## Example ## - - // Define keyboard shortcuts for showing and hiding a custom panel. - var { Hotkey } = require("hotkeys"); - - var showHotKey = Hotkey({ - combo: "accel-shift-o", - onPress: function() { - showMyPanel(); - } - }); - var hideHotKey = Hotkey({ - combo: "accel-alt-shift-o", - onPress: function() { - hideMyPanel(); - } - }); - -[Mozilla keyboard planning FAQ]:http://www.mozilla.org/access/keyboard/ -[keyboard shortcuts]:https://developer.mozilla.org/en/XUL_Tutorial/Keyboard_Shortcuts diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/notifications.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/notifications.md deleted file mode 100644 index ca120ab..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/notifications.md +++ /dev/null @@ -1,64 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> - -The `notifications` module allows you to display transient, -[toaster](http://en.wikipedia.org/wiki/Toast_%28computing%29)-style -desktop messages to the user. - -This API supports desktop notifications on Windows, OS X using -[Growl](http://growl.info/), and Linux using libnotify. If the user's system -does not support desktop notifications or if its notifications service is not -running, then notifications made with this API are logged to Firefox's error -console and, if the user launched Firefox from the command line, the terminal. - -Examples --------- - -Here's a typical example. When the message is clicked, a string is logged to -the console. - - var notifications = require("notifications"); - notifications.notify({ - title: "Jabberwocky", - text: "'Twas brillig, and the slithy toves", - data: "did gyre and gimble in the wabe", - onClick: function (data) { - console.log(data); - // console.log(this.data) would produce the same result. - } - }); - -This one displays an icon that's stored in the add-on's `data` directory. (See -the [`self`](packages/addon-kit/self.html) module documentation for more information.) - - var notifications = require("notifications"); - var self = require("self"); - var myIconURL = self.data.url("myIcon.png"); - notifications.notify({ - text: "I have an icon!", - iconURL: myIconURL - }); - - -<api name="notify"> -@function - Displays a transient notification to the user. -@param options {object} - An object with the following keys. Each is optional. - @prop [title] {string} - A string to display as the message's title. - @prop [text] {string} - A string to display as the body of the message. - @prop [iconURL] {string} - The URL of an icon to display inside the message. It may be a remote URL, - a data URI, or a URL returned by the [`self`](packages/addon-kit/self.html) - module. - @prop [onClick] {function} - A function to be called when the user clicks the message. It will be passed - the value of `data`. - @prop [data] {string} - A string that will be passed to `onClick`. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/page-mod.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/page-mod.md deleted file mode 100644 index 3b6ef6b..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/page-mod.md +++ /dev/null @@ -1,412 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Nickolay Ponomarev [asqueella@gmail.com] --> -<!-- contributed by Myk Melez [myk@mozilla.org] --> -<!-- contributed by Irakli Gozalishvil [gozala@mozilla.com] --> - -Overview --------- -The page-mod module enables add-on developers to execute scripts in the context -of specific web pages. Most obviously you could use page-mod to dynamically -modify the content of certain pages. - -The module exports a constructor function `PageMod` which creates a new page -modification (or "mod" for short). - -A page mod does not modify its pages until those pages are loaded or reloaded. -In other words, if your add-on is loaded while the user's browser is open, the -user will have to reload any open pages that match the mod for the mod to affect -them. - -To stop a page mod from making any more modifications, call its `destroy` -method. - -Like all modules that interact with web content, page-mod uses content -scripts that execute in the content process and defines a messaging API to -communicate between the content scripts and the main add-on script. For more -details on content scripting see the tutorial on [interacting with web -content](dev-guide/guides/content-scripts/index.html). - -To create a PageMod the add-on developer supplies: - -* a set of rules to select the desired subset of web pages based on their URL. -Each rule is specified using the -[match-pattern](packages/api-utils/match-pattern.html) syntax. - -* a set of content scripts to execute in the context of the desired pages. - -* a value for the onAttach option: this value is a function which will be -called when a page is loaded that matches the ruleset. This is used to set up a -communication channel between the add-on code and the content script. - -All these parameters are optional except for the ruleset, which must include -at least one rule. - -The following add-on displays an alert whenever a page matching the ruleset is -loaded: - - var pageMod = require("page-mod"); - pageMod.PageMod({ - include: "*.org", - contentScript: 'window.alert("Page matches ruleset");' - }); - -If you specify a value of "ready" or "end" for `contentScriptWhen`, -as opposed to "start", -then the content script can interact with the DOM itself: - - var pageMod = require("page-mod"); - pageMod.PageMod({ - include: "*.org", - contentScriptWhen: 'end', - contentScript: 'document.body.innerHTML = ' + - ' "<h1>Page matches ruleset</h1>";' - }); - -### Using `contentScriptFile` ### - -Most of the examples in this page define content scripts as strings, -and use the `contentScript` option to assign them to page mods. - -Alternatively, you can create content scripts in separate files -under your add-on's `data` directory. Then you can use the -[`self`](packages/addon-kit/self.html) module to retrieve a URL pointing -to the file, and assign this to the page-mod's `contentScriptFile` -property. - -For example, if you save the content script -file in your `data` directory as "myScript.js", you would assign it using -code like: - - var data = require("self").data; - - var pageMod = require("page-mod"); - pageMod.PageMod({ - include: "*.org", - contentScriptWhen: 'end', - contentScriptFile: data.url("myScript.js") - }); - -<div class="warning"> -<p>Unless your content script is extremely simple and consists only of a -static string, don't use <code>contentScript</code>: if you do, you may -have problems getting your add-on approved on AMO.</p> -<p>Instead, keep the script in a separate file and load it using -<code>contentScriptFile</code>. This makes your code easier to maintain, -secure, debug and review.</p> -</div> - -### Styling web pages ### - -Sometimes adding a script to web pages is not enough, you also want to styling -them. `PageMod` provides an easy way to do that through options' `contentStyle` -and `contentStyleFile` properties: - - var data = require("self").data; - var pageMod = require("page-mod"); - - pageMod.PageMod({ - include: "*.org", - - contentStyleFile: data.url("my-page-mod.css"), - contentStyle: [ - "div { padding: 10px; border: 1px solid silver}", - "img { display: none}" - ] - }) - -It's important to note that `PageMod` will add these styles as -[user style sheet](https://developer.mozilla.org/en/CSS/Getting_Started/Cascading_and_inheritance). - -## Communicating With Content Scripts ## - -When a matching page is loaded the `PageMod` will call the function that the -add-on code supplied to `onAttach`. The `PageMod` supplies one argument to -this function: a `worker` object. - -The worker can be thought of as the add-on's end of -a communication channel between the add-on code and the content scripts that -have been attached to this page. - -Thus the add-on can pass messages to the content scripts by calling the -worker's `postMessage` function and can receive messages from the content -scripts by registering a function as a listener to the worker's `on` function. - -Note that if multiple matching pages are loaded simultaneously then each page -is loaded into its own execution context with its own copy of the content -scripts. In this case `onAttach` is called once for each loaded page, and the -add-on code will have a separate worker for each page: - -![Multiple workers](static-files/media/multiple-workers.jpg) - -This is demonstrated in the following example: - - var pageMod = require("page-mod"); - var tabs = require("tabs"); - - var workers = []; - - pageMod.PageMod({ - include: ["http://www.mozilla*"], - contentScriptWhen: 'end', - contentScript: "onMessage = function onMessage(message) {" + - " window.alert(message);};", - onAttach: function onAttach(worker) { - if (workers.push(worker) == 3) { - workers[0].postMessage("The first worker!"); - workers[1].postMessage("The second worker!"); - workers[2].postMessage("The third worker!"); - } - } - }); - - tabs.open("http://www.mozilla.com"); - tabs.open("http://www.mozilla.org"); - tabs.open("http://www.mozilla-europe.org"); - -Here we specify a ruleset to match any URLs starting with -"http://www.mozilla". When a page matches we add the supplied worker to -an array, and when we have three workers in the array we send a message to -each worker in turn, telling it the order in which it was attached. The -worker just displays the message in an alert box. - -This shows that separate pages execute in separate contexts and that each -context has its own communication channel with the add-on script. - -Note though that while there is a separate worker for each execution context, -the worker is shared across all the content scripts associated with a single -execution context. In the following example we pass two content scripts into -the `PageMod`: these content scripts will share a worker instance. - -In the example each content script identifies itself to the add-on script -by sending it a message using the global `postMessage` function. In the -`onAttach` function the add-on code logs the fact that a new page is -attached and registers a listener function that simply logs the message: - - - var pageMod = require("page-mod"); - var data = require("self").data; - var tabs = require("tabs"); - - pageMod.PageMod({ - include: ["http://www.mozilla*"], - contentScriptWhen: 'end', - contentScript: ["postMessage('Content script 1 is attached to '+ " + - "document.URL);", - "postMessage('Content script 2 is attached to '+ " + - "document.URL);"], - onAttach: function onAttach(worker) { - console.log("Attaching content scripts") - worker.on('message', function(data) { - console.log(data); - }); - } - }); - - tabs.open("http://www.mozilla.com"); - -The console output of this add-on is: - -<pre> - info: Attaching content scripts - info: Content script 1 is attached to http://www.mozilla.com/en-US/ - info: Content script 2 is attached to http://www.mozilla.com/en-US/ -</pre> - -### Mapping workers to tabs ### - -The [`worker`](packages/api-utils/content/worker.html) has a `tab` -property which returns the tab associated with this worker. You can use this -to access the [`tabs API`](packages/addon-kit/tabs.html) for the tab -associated with a specific page: - - var pageMod = require("page-mod"); - var tabs = require("tabs"); - - pageMod.PageMod({ - include: ["*"], - onAttach: function onAttach(worker) { - console.log(worker.tab.title); - } - }); - -### Attaching content scripts to tabs ### - -We've seen that the page mod API attaches content scripts to pages based on -their URL. Sometimes, though, we don't care about the URL: we just want -to execute a script on demand in the context of a particular tab. - -For example, we might want to run a script in the context of the currently -active tab when the user clicks a widget: to block certain content, to -change the font style, or to display the page's DOM structure. - -Using the `attach` method of the [`tab`](packages/addon-kit/tabs.html) -object, you can attach a set of content scripts to a particular tab. The -scripts are executed immediately. - -The following add-on creates a widget which, when clicked, highlights all the -`div` elements in the page loaded into the active tab: - - var widgets = require("widget"); - var tabs = require("tabs"); - - var widget = widgets.Widget({ - id: "div-show", - label: "Show divs", - contentURL: "http://www.mozilla.org/favicon.ico", - onClick: function() { - tabs.activeTab.attach({ - contentScript: - 'var divs = document.getElementsByTagName("div");' + - 'for (var i = 0; i < divs.length; ++i) {' + - 'divs[i].setAttribute("style", "border: solid red 1px;");' + - '}' - }); - } - }); - -## Destroying Workers ## - -Workers generate a `detach` event when their associated page is closed: that -is, when the tab is closed or the tab's location changes. If -you are maintaining a list of workers belonging to a page mod, you can use -this event to remove workers that are no longer valid. - -For example, if you maintain a list of workers attached to a page mod: - - var workers = []; - - var pageMod = require("page-mod").PageMod({ - include: ['*'], - contentScriptWhen: 'ready', - contentScriptFile: data.url('pagemod.js'), - onAttach: function(worker) { - workers.push(worker); - } - }); - -You can remove workers when they are no longer valid by listening to `detach`: - - var workers = []; - - function detachWorker(worker, workerArray) { - var index = workerArray.indexOf(worker); - if(index != -1) { - workerArray.splice(index, 1); - } - } - - var pageMod = require("page-mod").PageMod({ - include: ['*'], - contentScriptWhen: 'ready', - contentScriptFile: data.url('pagemod.js'), - onAttach: function(worker) { - workers.push(worker); - worker.on('detach', function () { - detachWorker(this, workers); - }); - } - }); - -<api name="PageMod"> -@class -A PageMod object. Once activated a page mod will execute the supplied content -scripts in the context of any pages matching the pattern specified by the -'include' property. -<api name="PageMod"> -@constructor -Creates a PageMod. -@param options {object} - Options for the PageMod, with the following keys: - @prop include {string,array} - A match pattern string or an array of match pattern strings. These define - the pages to which the PageMod applies. See the - [match-pattern](packages/api-utils/match-pattern.html) module for - a description of match pattern syntax. - At least one match pattern must be supplied. - - @prop [contentScriptFile] {string,array} - The local file URLs of content scripts to load. Content scripts specified - by this option are loaded *before* those specified by the `contentScript` - option. Optional. - @prop [contentScript] {string,array} - The texts of content scripts to load. Content scripts specified by this - option are loaded *after* those specified by the `contentScriptFile` option. - Optional. - @prop [contentScriptWhen="end"] {string} - When to load the content scripts. This may take one of the following - values: - - * "start": load content scripts immediately after the document - element for the page is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the page has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - - This property is optional and defaults to "end". - - @prop [contentStyleFile] {string,array} - The local file URLs of stylesheet to load. Content style specified by this - option are loaded *before* those specified by the `contentStyle` option. - Optional. - @prop [contentStyle] {string,array} - The texts of stylesheet rules to add. Content styles specified by this - option are loaded *after* those specified by the `contentStyleFile` option. - Optional. - - @prop [onAttach] {function} -A function to call when the PageMod attaches content scripts to -a matching page. The function will be called with one argument, a `worker` -object which the add-on script can use to communicate with the content scripts -attached to the page in question. - -</api> - -<api name="include"> -@property {List} -A [list](packages/api-utils/list.html) of match pattern strings. These -define the pages to which the page mod applies. See the -[match-pattern](packages/api-utils/match-pattern.html) module for a -description of match patterns. Rules can be added to the list by calling its -`add` method and removed by calling its `remove` method. - -</api> - -<api name="destroy"> -@method -Stops the page mod from making any more modifications. Once destroyed the page -mod can no longer be used. Note that modifications already made to open pages -will not be undone, except for any stylesheet added by `contentStyle` or -`contentStyleFile`, that are unregistered immediately. -</api> - -<api name="attach"> -@event -This event is emitted this event when the page-mod's content scripts are -attached to a page whose URL matches the page-mod's `include` filter. - -@argument {Worker} -The listener function is passed a [`Worker`](packages/api-utils/content/worker.html) object that can be used to communicate -with any content scripts attached to this page. -</api> - -<api name="error"> -@event -This event is emitted when an uncaught runtime error occurs in one of the page -mod's content scripts. - -@argument {Error} -Listeners are passed a single argument, the -[Error](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error) -object. -</api> - -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/page-worker.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/page-worker.md deleted file mode 100644 index 5539c25..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/page-worker.md +++ /dev/null @@ -1,325 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Felipe Gomes [felipc@gmail.com] --> - -The `page-worker` module provides a way to create a permanent, invisible page -and access its DOM. - -The module exports a constructor function `Page`, which constructs a new page -worker. A page worker may be destroyed, after which its memory is freed, and -you must create a new instance to load another page. - -You specify the page to load using the `contentURL` option to the -[`Page()` constructor](packages/addon-kit/page-worker.html#Page(options)). -This can point to a remote file: - - pageWorker = require("page-worker").Page({ - contentScript: "console.log(document.body.innerHTML);", - contentURL: "http://en.wikipedia.org/wiki/Internet" - }); - -It can also point to an HTML file which you've packaged with your add-on. -To do this, save the file in your add-on's `data` directory and create the -URL using the `data.url()` method of the -[`self`](packages/addon-kit/self.html) module: - - pageWorker = require("page-worker").Page({ - contentScript: "console.log(document.body.innerHTML);", - contentURL: require("self").data.url("myFile.html") - }); - -You can load a new page by setting the page worker's `contentURL` property. -In this example we fetch the first paragraph of a page from Wikipedia, then -the first paragraph of a different page: - - var getFirstParagraph = "var paras = document.getElementsByTagName('p');" + - "console.log(paras[0].textContent);" + - "self.port.emit('loaded');" - - pageWorker = require("page-worker").Page({ - contentScript: getFirstParagraph, - contentURL: "http://en.wikipedia.org/wiki/Chalk" - }); - - pageWorker.port.on("loaded", function() { - pageWorker.contentURL = "http://en.wikipedia.org/wiki/Cheese" - }); - -## Scripting Page-Worker Content ## - -To access the page's DOM you need to attach a script to it. In the SDK these -scripts are called "content scripts" because they're explicitly used for -interacting with web content. - -You can specify one or more content scripts to load into the page using the -`contentScript` or `contentScriptFile` options to the -[`Page()` constructor](packages/addon-kit/page-worker.html#Page(options)). -With `contentScript` you pass the script as a string, as in the examples -above. With `contentScriptFile` you pass a URL which points to a script -saved under your add-on's `data` directory. You construct the URL using -the `data.url()` method of the -[`self`](packages/addon-kit/self.html) module. - -While content scripts can access DOM content, they can't access any of the SDK -APIs, so in many cases you'll need to exchange messages between the content -script and your main add-on code for a complete solution. - -For example, the content script might read some content and send it back to -the main add-on, which could store it using the -[`simple-storage`](packages/addon-kit/simple-storage.html) API. You can -communicate with the script using either the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or (preferably, usually) the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. - -For example, this add-on loads a page from Wikipedia, and runs a content script -in it to send all the headers back to the main add-on code: - - var pageWorkers = require("page-worker"); - - // This content script sends header titles from the page to the add-on: - var script = "var elements = document.querySelectorAll('h2 > span'); " + - "for (var i = 0; i < elements.length; i++) { " + - " postMessage(elements[i].textContent) " + - "}"; - - // Create a page worker that loads Wikipedia: - pageWorkers.Page({ - contentURL: "http://en.wikipedia.org/wiki/Internet", - contentScript: script, - contentScriptWhen: "ready", - onMessage: function(message) { - console.log(message); - } - }); - -For conciseness, this example creates the content script as a string and uses -the `contentScript` property. In your own add-ons, you will probably want to -create your content scripts in separate files and pass their URLs using the -`contentScriptFile` property. - -<div class="warning"> -<p>Unless your content script is extremely simple and consists only of a -static string, don't use <code>contentScript</code>: if you do, you may -have problems getting your add-on approved on AMO.</p> -<p>Instead, keep the script in a separate file and load it using -<code>contentScriptFile</code>. This makes your code easier to maintain, -secure, debug and review.</p> -</div> - -To learn much more about content scripts, see the -[Working with Content Scripts](dev-guide/guides/content-scripts/index.html) -guide. - -<div class="experimental"> -<h3>Scripting Trusted Page Content</h3> - -**Note that the feature described in this section is experimental: we'll -very probably continue to support it, but the name of the `addon` -property might change in a future release.** - -We've already seen that you can package HTML files in your add-on's `data` -directory and load them using `page-worker`. We can call this "trusted" -content, because unlike content loaded from a source outside the -add-on, the add-on author knows exactly what it's doing. To -interact with trusted content you don't need to use content scripts: -you can just include a script from the HTML file in the normal way, using -`<script>` tags. - -Like a content script, these scripts can communicate with the add-on code -using the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. -The crucial difference is that these scripts access the `postMessage` -and `port` objects through the `addon` object, whereas content scripts -access them through the `self` object. - -So given an add-on that loads trusted content and uses content scripts -to access it, there are typically three changes you have to make, if you -want to use normal page scripts instead: - -* **in the content script**: change occurrences of `self` to `addon`. -For example, `self.port.emit("my-event")` becomes -`addon.port.emit("my-event")`. - -* **in the HTML page itself**: add a `<script>` tag to load the script. So -if your content script is saved under `data` as "my-script.js", you need -a line like `<script src="my-script.js"></script>` in the page header. - -* **in the "main.js" file**: remove the `contentScriptFile` option in -the `Page()` constructor. - -</div> - -<api name="Page"> -@class -A `Page` object loads the page specified by its `contentURL` option and -executes any content scripts that have been supplied to it in the -`contentScript` and `contentScriptFile` options. - -The page is not displayed to the user. - -The page worker is loaded as soon as the `Page` object is created and stays -loaded until its `destroy` method is called or the add-on is unloaded. - -<api name="Page"> -@constructor - Creates an uninitialized page worker instance. -@param [options] {object} - The *`options`* parameter is optional, and if given it should be an object - with any of the following keys: - @prop [contentURL] {string} - The URL of the content to load in the panel. - @prop [allow] {object} - An object with keys to configure the permissions on the page worker. The - boolean key `script` controls if scripts from the page are allowed to run. - `script` defaults to true. - @prop [contentScriptFile] {string,array} - A local file URL or an array of local file URLs of content scripts to load. - Content scripts specified by this option are loaded *before* those specified - by the `contentScript` option. See - [Working with Content Scripts](dev-guide/guides/content-scripts/index.html) - for help on setting this property. - @prop [contentScript] {string,array} - A string or an array of strings containing the texts of content scripts to - load. Content scripts specified by this option are loaded *after* those - specified by the `contentScriptFile` option. - @prop [contentScriptWhen="end"] {string} - When to load the content scripts. This may take one of the following - values: - - * "start": load content scripts immediately after the document - element for the page is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the page has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - - This property is optional and defaults to "end". - - @prop [onMessage] {function} - Use this to add a listener to the page worker's `message` event. -</api> - -<api name="port"> -@property {EventEmitter} -[EventEmitter](packages/api-utils/events.html) object that allows you to: - -* send events to the content script using the `port.emit` function -* receive events from the content script using the `port.on` function - -See the guide to -<a href="dev-guide/guides/content-scripts/using-port.html"> -communicating using <code>port</code></a> for details. -</api> - -<api name="contentURL"> -@property {string} -The URL of content to load. This can point to -local content loaded from your add-on's "data" directory or remote content. -Setting it loads the content immediately. -</api> - -<api name="allow"> -@property {object} - A object describing permissions for the content. It contains a single key - named `script` whose value is a boolean that indicates whether or not to - execute script in the content. `script` defaults to true. -</api> - -<api name="contentScriptFile"> -@property {string,array} -A local file URL or an array of local file URLs of content scripts to load. -</api> - -<api name="contentScript"> -@property {string,array} -A string or an array of strings containing the texts of content scripts to -load. -</api> - -<api name="contentScriptWhen"> -@property {string} - When to load the content scripts. This may have one of the following - values: - - * "start": load content scripts immediately after the document - element for the page is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the page has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - -</api> - -<api name="destroy"> -@method -Unloads the page worker. After you destroy a page worker, its memory is freed -and you must create a new instance if you need to load another page. -</api> - -<api name="postMessage"> -@method -Sends a message to the content scripts. -@param message {value} -The message to send. Must be JSON-able. -</api> - -<api name="on"> -@method -Registers an event listener with the page worker. See -[Working with Events](dev-guide/guides/events.html) for help with -events. -@param type {string} -The type of event to listen for. -@param listener {function} -The listener function that handles the event. -</api> - -<api name="removeListener"> -@method -Unregisters an event listener from the page worker. -@param type {string} -The type of event for which `listener` was registered. -@param listener {function} -The listener function that was registered. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this page worker. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the page worker's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a> -</api> - -<api name="error"> -@event -This event is emitted when an uncaught runtime error occurs in one of the -page worker's content scripts. - -@argument {Error} -Listeners are passed a single argument, the -[Error](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error) -object. -</api> - -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/panel.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/panel.md deleted file mode 100644 index 0a85db9..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/panel.md +++ /dev/null @@ -1,607 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Myk Melez [myk@mozilla.org] --> -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -This module exports a single constructor function `Panel` which constructs a -new panel. - -A panel is a dialog. Its content is specified as HTML and you can -execute scripts in it, so the appearance and behaviour of the panel -is limited only by what you can do using HTML, CSS and JavaScript. - -The screenshot below shows a panel whose content is built from the -list of currently open tabs: - -<img class="image-center" src="static-files/media/screenshots/panel-tabs-osx.png" -alt="Simple panel example"> - -Panels are useful for presenting temporary interfaces to users in a way that is -easier for users to ignore and dismiss than a modal dialog, since panels are -hidden the moment users interact with parts of the application interface outside -them. - -A panel's content is loaded as soon as it is created, before the panel is shown, -and the content remains loaded when a panel is hidden, so it is possible -to keep a panel around in the background, updating its content as appropriate -in preparation for the next time it is shown. - -Your add-on can receive notifications when a panel is shown or hidden by -listening to its `show` and `hide` events. - -## Panel Content ## - -The panel's content is specified as HTML, which is loaded from the URL -supplied in the `contentURL` option to the panel's constructor. - -You can load remote HTML into the panel: - - var panel = require("panel").Panel({ - width: 180, - height: 180, - contentURL: "https://en.wikipedia.org/w/index.php?title=Jetpack&useformat=mobile" - }); - - panel.show(); - -<img class="image-center" src="static-files/media/screenshots/wikipedia-jetpack-panel.png" -alt="Wikipedia Jetpack panel"> - -You can also load HTML that's been packaged with your add-on, and this is -most probably how you will create dialogs. To do this, save -the HTML in your add-on's `data` directory and load it using the `data.url()` -method exported by the -[`self`](packages/addon-kit/self.html) module, like this: - - var panel = require("panel").Panel({ - contentURL: require("self").data.url("myFile.html") - }); - - panel.show(); - -## Updating Panel Content ## - -You can update the panel's content simply by setting the panel's `contentURL` -property. - -Here's an add-on that adds two widgets to the add-on bar, one which -shows Google's mobile site and one which shows Bing's mobile site. The widgets -share a panel object, and switch between the two sites by updating the panel's -`contentURL` property: - - var panel = require("panel").Panel({ - contentURL: "about:blank", - onHide: function () { - panel.contentURL = "about:blank"; - } - }); - - require("widget").Widget({ - id: "bing", - label: "Bing", - contentURL: "http://www.bing.com/favicon.ico", - panel: panel, - onClick: function() { - panel.contentURL = "http://m.bing.com/"; - } - }); - - require("widget").Widget({ - id: "google", - label: "Google", - contentURL: "http://www.google.com/favicon.ico", - panel: panel, - onClick: function() { - panel.contentURL = "http://www.google.com/xhtml"; - } - }); - -## Scripting Panel Content ## - -You can't directly access your panel's content from your main add-on code. -To access the panel's content, you need to load a script into the panel. -In the SDK these scripts are called "content scripts" because they're -explicitly used for interacting with web content. - -While content scripts can access the content they're attached to, they can't -use the SDK's APIs. So implementing a complete solution usually means you -have to send messages between the content script and the main add-on code. - -* You can specify one or more content scripts to load into a panel using the -`contentScript` or `contentScriptFile` options to the -[`Panel()` constructor](packages/addon-kit/panel.html#Panel%28options%29). - -* You can communicate with the script using either the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or (preferably, usually) the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. - -For example, here's an add-on whose content script intercepts mouse clicks -on links inside the panel, and sends the target URL to the main add-on -code. The content script sends messages using `self.port.emit()` and the -add-on script receives them using `panel.port.on()`. - - var myScript = "window.addEventListener('click', function(event) {" + - " var t = event.target;" + - " if (t.nodeName == 'A')" + - " self.port.emit('click-link', t.toString());" + - "}, false);" - - var panel = require("panel").Panel({ - contentURL: "http://www.bbc.co.uk/mobile/index.html", - contentScript: myScript - }); - - panel.port.on("click-link", function(url) { - console.log(url); - }); - - panel.show(); - -This example uses `contentScript` to supply the script as a string. It's -usually better practice to use `contentScriptFile`, which is a URL pointing -to a script file saved under your add-on's `data` directory. - -<div class="warning"> -<p>Unless your content script is extremely simple and consists only of a -static string, don't use <code>contentScript</code>: if you do, you may -have problems getting your add-on approved on AMO.</p> -<p>Instead, keep the script in a separate file and load it using -<code>contentScriptFile</code>. This makes your code easier to maintain, -secure, debug and review.</p> -</div> - -<img class="image-right" src="static-files/media/screenshots/text-entry-panel.png" -alt="Text entry panel"> - -### Getting User Input ### - -The following add-on adds a widget which displays a panel when -clicked. The panel just contains a `<textarea>` element: when the user -presses the `return` key, the contents of the `<textarea>` is sent to the -main add-on code. - -The add-on consists of three files: - -* **`main.js`**: the main add-on code, that creates the widget and panel -* **`get-text.js`**: the content script that interacts with the panel content -* **`text-entry.html`**: the panel content itself, specified as HTML - -"main.js" is saved in your add-on's `lib` directory, and the other two files -go in your add-on's `data` directory: - -<pre> -my-addon/ - data/ - get-text.js - text-entry.html - lib/ - main.js -</pre> - -The "main.js" looks like this: - - var data = require("self").data; - - // Create a panel whose content is defined in "text-entry.html". - // Attach a content script called "get-text.js". - var text_entry = require("panel").Panel({ - width: 212, - height: 200, - contentURL: data.url("text-entry.html"), - contentScriptFile: data.url("get-text.js") - }); - - // Send the content script a message called "show" when - // the panel is shown. - text_entry.on("show", function() { - text_entry.port.emit("show"); - }); - - // Listen for messages called "text-entered" coming from - // the content script. The message payload is the text the user - // entered. - // In this implementation we'll just log the text to the console. - text_entry.port.on("text-entered", function (text) { - console.log(text); - text_entry.hide(); - }); - - // Create a widget, and attach the panel to it, so the panel is - // shown when the user clicks the widget. - require("widget").Widget({ - label: "Text entry", - id: "text-entry", - contentURL: "http://www.mozilla.org/favicon.ico", - panel: text_entry - }); - -The content script "get-text.js" looks like this: - - self.port.on("show", function (arg) { - var textArea = document.getElementById('edit-box'); - textArea.focus(); - // When the user hits return, send a message to main.js. - // The message payload is the contents of the edit box. - textArea.onkeyup = function(event) { - if (event.keyCode == 13) { - // Remove the newline. - text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); - self.port.emit("text-entered", text); - textArea.value = ''; - } - }; - }); - -Finally, the "text-entry.html" file defines the `<textarea>` element: - -<pre class="brush: html"> - -<html> - -<head> - <style type="text/css" media="all"> - textarea { - margin: 10px; - } - </style> -</head> - -<body> - <textarea rows="10" cols="20" id="edit-box"></textarea> -</body> - -</html> -</pre> - -To learn much more about content scripts, see the -[Working with Content Scripts](dev-guide/guides/content-scripts/index.html) -guide. - -<div class="experimental"> -<h3>Scripting Trusted Panel Content</h3> - -**Note that the feature described in this section is experimental: we'll -very probably continue to support it, but the name of the `addon` -property might change in a future release.** - -We've already seen that you can package HTML files in your add-on's `data` -directory and use them to define the panel's content. We can call this -"trusted" content, because unlike content loaded from a source outside the -add-on, the add-on author knows exactly what it's doing. To -interact with trusted content you don't need to use content scripts: -you can just include a script from the HTML file in the normal way, using -`script` tags. - -Like a content script, these scripts can communicate with the add-on code -using the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. -The crucial difference is that these scripts access the `postMessage` -and `port` objects through the `addon` object, whereas content scripts -access them through the `self` object. - -To show the difference, we can easily convert the `text-entry` add-on above -to use normal page scripts instead of content scripts. - -The main add-on code is exactly the same as the main add-on code in the -previous example, except that we don't attach a content script: - - var data = require("self").data; - - // Create a panel whose content is defined in "text-entry.html". - var text_entry = require("panel").Panel({ - width: 212, - height: 200, - contentURL: data.url("text-entry.html"), - }); - - // Send the page script a message called "show" when - // the panel is shown. - text_entry.on("show", function() { - text_entry.port.emit("show"); - }); - - // Listen for messages called "text-entered" coming from - // the page script. The message payload is the text the user - // entered. - // In this implementation we'll just log the text to the console. - text_entry.port.on("text-entered", function (text) { - console.log(text); - text_entry.hide(); - }); - - // Create a widget, and attach the panel to it, so the panel is - // shown when the user clicks the widget. - require("widget").Widget({ - label: "Text entry", - id: "text-entry", - contentURL: "http://www.mozilla.org/favicon.ico", - panel: text_entry - }); - -The page script is exactly the same as the content script above, except -that instead of `self`, we use `addon` to access the messaging APIs: - - addon.port.on("show", function (arg) { - var textArea = document.getElementById('edit-box'); - textArea.focus(); - // When the user hits return, send a message to main.js. - // The message payload is the contents of the edit box. - textArea.onkeyup = function(event) { - if (event.keyCode == 13) { - // Remove the newline. - text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); - addon.port.emit("text-entered", text); - textArea.value = ''; - } - }; - }); - -Finally, the HTML file now references "get-text.js" inside a `script` tag: - -<pre class="brush: html"> - -<html> - -<head> - <style type="text/css" media="all"> - textarea { - margin: 10px; - } - </style> - <script src="get-text.js"></script> -</head> - -<body> - <textarea rows="10" cols="20" id="edit-box"></textarea> -</body> - -</html> -</pre> -</div> - -## Styling Trusted Panel Content ## - -When the panel's content is specified using an HTML file in your `data` -directory, you can style it using CSS, either embedding the CSS directly -in the file or referencing a CSS file stored under `data`. - -The panel's default style is different for each operating system: - -<img class="image-center" src="static-files/media/screenshots/panel-default-style.png" -alt="OS X panel default style"> - -This helps to ensure that the panel's style is consistent with the dialogs -displayed by Firefox and other applications, but means you need to take care -when applying your own styles. For example, if you set the panel's -`background-color` property to `white` and do not set the `color` property, -then the panel's text will be invisible on OS X although it looks fine on Ubuntu. - -<api name="Panel"> -@class -The Panel object represents a floating modal dialog that can by an add-on to -present user interface content. - -Once a panel object has been created it can be shown and hidden using its -`show()` and `hide()` methods. Once a panel is no longer needed it can be -deactivated using `destroy()`. - -The content of a panel is specified using the `contentURL` option. An add-on -can interact with the content of a panel using content scripts which it -supplies in the `contentScript` and/or `contentScriptFile` options. For example, -a content script could create a menu and send the user's selection to the -add-on. - -<api name="Panel"> -@constructor -Creates a panel. -@param options {object} - Options for the panel, with the following keys: - @prop [width] {number} - The width of the panel in pixels. Optional. - @prop [height] {number} - The height of the panel in pixels. Optional. - @prop [contentURL] {string} - The URL of the content to load in the panel. - @prop [allow] {object} - An optional object describing permissions for the content. It should - contain a single key named `script` whose value is a boolean that indicates - whether or not to execute script in the content. `script` defaults to true. - @prop [contentScriptFile] {string,array} - A local file URL or an array of local file URLs of content scripts to load. - Content scripts specified by this property are loaded *before* those - specified by the `contentScript` property. - @prop [contentScript] {string,array} - A string or an array of strings containing the texts of content scripts to - load. Content scripts specified by this property are loaded *after* those - specified by the `contentScriptFile` property. - @prop [contentScriptWhen="end"] {string} - When to load the content scripts. This may take one of the following - values: - - * "start": load content scripts immediately after the document - element for the panel is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the panel has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - - This property is optional and defaults to "end". - - @prop [onMessage] {function} - Include this to listen to the panel's `message` event. - @prop [onShow] {function} - Include this to listen to the panel's `show` event. - @prop [onHide] {function} - Include this to listen to the panel's `hide` event. -</api> - -<api name="port"> -@property {EventEmitter} -[EventEmitter](packages/api-utils/events.html) object that allows you to: - -* send events to the content script using the `port.emit` function -* receive events from the content script using the `port.on` function - -See the guide to -<a href="dev-guide/guides/content-scripts/using-port.html"> -communicating using <code>port</code></a> for details. -</api> - -<api name="isShowing"> -@property {boolean} -Tells if the panel is currently shown or not. This property is read-only. -</api> - -<api name="height"> -@property {number} -The height of the panel in pixels. -</api> - -<api name="width"> -@property {number} -The width of the panel in pixels. -</api> - -<api name="contentURL"> -@property {string} -The URL of content loaded into the panel. This can point to -local content loaded from your add-on's "data" directory or remote content. -Setting it updates the panel's content immediately. -</api> - -<api name="allow"> -@property {object} -An object describing permissions for the content. It contains a single key -named `script` whose value is a boolean that indicates whether or not to execute -script in the content. -</api> - -<api name="contentScriptFile"> -@property {string,array} -A local file URL or an array of local file URLs of content scripts to load. -Content scripts specified by this property are loaded *before* those -specified by the `contentScript` property. -</api> - -<api name="contentScript"> -@property {string,array} -A string or an array of strings containing the texts of content scripts to -load. Content scripts specified by this property are loaded *after* those -specified by the `contentScriptFile` property. -</api> - -<api name="contentScriptWhen"> -@property {string} -When to load the content scripts. This may have one of the following -values: - -* "start": load content scripts immediately after the document -element for the panel is inserted into the DOM, but before the DOM content -itself has been loaded -* "ready": load content scripts once DOM content has been loaded, -corresponding to the -[DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) -event -* "end": load content scripts once all the content (DOM, JS, CSS, -images) for the panel has been loaded, at the time the -[window.onload event](https://developer.mozilla.org/en/DOM/window.onload) -fires - -</api> - -<api name="destroy"> -@method -Destroys the panel, unloading any content that was loaded in it. Once -destroyed, the panel can no longer be used. If you just want to hide -the panel and might show it later, use `hide` instead. -</api> - -<api name="postMessage"> -@method -Sends a message to the content scripts. -@param message {value} -The message to send. Must be stringifiable to JSON. -</api> - -<api name="show"> -@method -Displays the panel. -</api> - -<api name="hide"> -@method -Stops displaying the panel. -</api> - -<api name="resize"> -@method -Resizes the panel. -@param width {number} -The new width of the panel in pixels. -@param height {number} -The new height of the panel in pixels. -</api> - -<api name="on"> -@method - Registers an event listener with the panel. -@param type {string} - The type of event to listen for. -@param listener {function} - The listener function that handles the event. -</api> - -<api name="removeListener"> -@method - Unregisters an event listener from the panel. -@param type {string} - The type of event for which `listener` was registered. -@param listener {function} - The listener function that was registered. -</api> - -<api name="show"> -@event -This event is emitted when the panel is shown. -</api> - -<api name="hide"> -@event -This event is emitted when the panel is hidden. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this panel. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the panel's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="error"> -@event -This event is emitted when an uncaught runtime error occurs in one of the -panel's content scripts. - -@argument {Error} -Listeners are passed a single argument, the -[Error](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error) -object. -</api> - -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/passwords.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/passwords.md deleted file mode 100644 index 8ee6109..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/passwords.md +++ /dev/null @@ -1,568 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -The `passwords` module allows add-ons to interact with Firefox's -[Password Manager](http://support.mozilla.com/en-US/kb/Remembering%20passwords) -to add, retrieve and remove stored credentials. - -A _credential_ is the set of information a user supplies to authenticate -herself with a service. Typically a credential consists of a username and a -password. - -Using this module you can: - -1. **Search** for credentials which have been stored in the Password Manager. - You can then use the credentials to access their related service (for - example, by logging into a web site). - -2. **Store** credentials in the Password Manager. You can store different sorts - of credentials, as outlined in the "Credentials" section below. - -3. **Remove** stored credentials from the Password Manager. - -## Credentials ## - -In this API, credentials are represented by objects. - -You create credential objects to pass into the API, and the API also returns -credential objects to you. The sections below explain both the properties you -should define on credential objects and the properties you can expect on -credential objects returned by the API. - -All credential objects include `username` and `password` properties. Different -sorts of stored credentials include various additional properties, as -outlined in this section. - -You can use the Passwords API with three sorts of credentials: - -* Add-on credentials -* HTML form credentials -* HTTP Authentication credentials - -### Add-on Credential ### - -These are associated with your add-on rather than a particular web site. -They contain the following properties: - -<table> -<colgroup> -<col width="25%"> -</colgroup> -<tr> - <td> - <code>username</code> - </td> - <td> - The username. - </td> -</tr> - -<tr> - <td> - <code>password</code> - </td> - <td> - The password. - </td> -</tr> - -<tr> - <td> - <code>url</code> - </td> - <td> - <p>For an add-on credential, this property is of the form:<br><code> - addon:<addon-id></code>, where <code><addon-id></code> - is the add-on's - <a href="dev-guide/guides/program-id.html"> - Program ID</a>.</p> - <p>You don't supply this value when storing an add-on credential: it is - automatically generated for you. However, you can use it to work out - which stored credentials belong to your add-on by comparing it with the - <code>uri</code> property of the - <a href="packages/addon-kit/self.html"><code>self</code></a> - module.</p> - </td> -</tr> - -<tr> - <td> - <code>realm</code> - </td> - <td> - <p>You can use this as a name for the credential, to distinguish - it from any other credentials you've stored.</p> - <p>The realm is displayed - in Firefox's Password Manager, under "Site", in brackets after the URL. - For example, if the realm for a credential is "User Registration", then - its "Site" field will look something like:</p> - <code>addon:jid0-01mBBFyu0ZAXCFuB1JYKooSTKIc (User Registration)</code> - </td> -</tr> - -</table> - -### HTML Form Credential ### - -If a web service uses HTML forms to authenticate its users, then the -corresponding credential is an HTML Form credential. - -It contains the following properties: - -<table> -<colgroup> -<col width="25%"> -</colgroup> -<tr> - <td> - <code>username</code> - </td> - <td> - The username. - </td> -</tr> - -<tr> - <td> - <code>password</code> - </td> - <td> - The password. - </td> -</tr> - -<tr> - <td> - <code>url</code> - </td> - <td> - The URL for the web service which requires the credential. - You should omit anything after the hostname and (optional) port. - </td> -</tr> - -<tr> - <td> - <code>formSubmitURL</code> - </td> - <td> - The value of the form's "action" attribute. - You should omit anything after the hostname and (optional) port. - If the form doesn't contain an "action" attribute, this property should - match the <code>url</code> property. - </td> -</tr> - -<tr> - <td> - <code>usernameField</code> - </td> - <td> - The value of the "name" attribute for the form's username field. - </td> -</tr> - -<tr> - <td> - <code>passwordField</code> - </td> - <td> - The value of the "name" attribute for the form's password field. - </td> -</tr> - -</table> - -So: given a form at `http://www.example.com/login` -with the following HTML: - -<script type="syntaxhighlighter" class="brush: html"><![CDATA[ -<form action="http://login.example.com/foo/authenticate.cgi"> - <div>Please log in.</div> - <label>Username:</label> <input type="text" name="uname"> - <label>Password:</label> <input type="password" name="pword"> -</form> -]]> -</script> - -The corresponding values for the credential (excluding username and password) -should be: - -<pre> - url: "http://www.example.com" - formSubmitURL: "http://login.example.com" - usernameField: "uname" - passwordField: "pword" -</pre> - -Note that for both `url` and `formSubmitURL`, the portion of the URL after the -hostname is omitted. - -### HTTP Authentication Credential ### - -These are used to authenticate the user to a web site -which uses HTTP Authentication, as detailed in -[RFC 2617](http://tools.ietf.org/html/rfc2617). -They contain the following properties: - -<table> -<colgroup> -<col width="25%"> -</colgroup> -<tr> - <td> - <code>username</code> - </td> - <td> - The username. - </td> -</tr> - -<tr> - <td> - <code>password</code> - </td> - <td> - The password. - </td> -</tr> - -<tr> - <td> - <code>url</code> - </td> - <td> - The URL for the web service which requires the credential. - You should omit anything after the hostname and (optional) port. - </td> -</tr> - -<tr> - <td> - <code>realm</code> - </td> - <td> - <p>The WWW-Authenticate response header sent by the server may include a - "realm" field as detailed in - <a href="http://tools.ietf.org/html/rfc2617">RFC 2617</a>. If it does, - this property contains the value for the "realm" field. Otherwise, it is - omitted.</p> - <p>The realm is displayed in Firefox's Password Manager, under "Site", - in brackets after the URL.</p> - </td> -</tr> - -</table> - -So: if a web server at `http://www.example.com` requested authentication with -a response code like this: - -<pre> - HTTP/1.0 401 Authorization Required - Server: Apache/1.3.27 - WWW-Authenticate: Basic realm="ExampleCo Login" -</pre> - -The corresponding values for the credential (excluding username and password) -should be: - -<pre> - url: "http://www.example.com" - realm: "ExampleCo Login" -</pre> - -## onComplete and onError ## - -This API is explicitly asynchronous, so all its functions take two callback -functions as additional options: `onComplete` and `onError`. - -`onComplete` is called when the operation has completed successfully and -`onError` is called when the function encounters an error. - -Because the `search` function is expected to return a list of matching -credentials, its `onComplete` option is mandatory. Because the other functions -don't return a value in case of success their `onComplete` options are -optional. - -For all functions, `onError` is optional. - -<api name="search"> -@function - -This function is used to retrieve a credential, or a list of credentials, -stored in the Password Manager. - -You pass it any subset of the possible properties a credential can contain. -Credentials which match all the properties you supplied are returned as an -argument to the `onComplete` callback. - -So if you pass in an empty set of properties, all stored credentials are -returned: - - function show_all_passwords() { - require("passwords").search({ - onComplete: function onComplete(credentials) { - credentials.forEach(function(credential) { - console.log(credential.username); - console.log(credential.password); - }); - } - }); - } - -If you pass it a single property, only credentials matching that property are -returned: - - function show_passwords_for_joe() { - require("passwords").search({ - username: "joe", - onComplete: function onComplete(credentials) { - credentials.forEach(function(credential) { - console.log(credential.username); - console.log(credential.password); - }); - } - }); - } - -If you pass more than one property, returned credentials must match all of -them: - - function show_google_password_for_joe() { - require("passwords").search({ - username: "joe", - url: "https://www.google.com", - onComplete: function onComplete(credentials) { - credentials.forEach(function(credential) { - console.log(credential.username); - console.log(credential.password); - }); - } - }); - } - -To retrieve only credentials associated with your add-on, use the `url` -property, initialized from `self.uri`: - - function show_my_addon_passwords() { - require("passwords").search({ - url: require("self").uri, - onComplete: function onComplete(credentials) { - credentials.forEach(function(credential) { - console.log(credential.username); - console.log(credential.password); - }); - } - }); - } - -@param options {object} -The `options` object may contain any credential properties. It is used to -restrict the set of credentials returned by the `search` function. - -See "Credentials" above for details on what these properties should be. - -Additionally, `options` must contain a function assigned to its `onComplete` -property: this is called when the function completes and is passed the set of -credentials retrieved. - -`options` may contain a function assigned to its `onError` property, which is -called if the function encounters an error. `onError` is passed the error as an -[nsIException](https://developer.mozilla.org/en/nsIException) object. - -@prop [username] {string} -The username for the credential. - -@prop [password] {string} -The password for the credential. - -@prop [url] {string} -The URL associated with the credential. - -@prop [formSubmitURL] {string} -The URL an HTML form credential is submitted to. - -@prop [realm] {string} -For HTTP Authentication credentials, the realm for which the credential was -requested. For add-on credentials, a name for the credential. - -@prop [usernameField] {string} -The value of the `name` attribute for the user name input field in a form. - -@prop [passwordField] {string} -The value of the `name` attribute for the password input field in a form. - -@prop onComplete {function} -The callback function that is called once the function completes successfully. -It is passed all the matching credentials as a list. This is the only -mandatory option. - -@prop [onError] {function} -The callback function that is called if the function failed. The -callback is passed an `error` containing a reason of a failure: this is an -[nsIException](https://developer.mozilla.org/en/nsIException) object. - -</api> - -<api name="store"> -@function - -This function is used to store a credential in the Password Manager. - -It takes an `options` object as an argument: this contains all the properties -for the new credential. - -As different sorts of credentials contain different properties, the -appropriate options differ depending on the sort of credential being stored. - -To store an add-on credential: - - require("passwords").store({ - realm: "User Registration", - username: "joe", - password: "SeCrEt123", - }); - -To store an HTML form credential: - - require("passwords").store({ - url: "http://www.example.com", - formSubmitURL: "http://login.example.com", - username: "joe", - usernameField: "uname", - password: "SeCrEt123", - passwordField: "pword" - }); - -To store an HTTP Authentication credential: - - require("passwords").store({ - url: "http://www.example.com", - realm: "ExampleCo Login", - username: "joe", - password: "SeCrEt123", - }); - -See "Credentials" above for more details on how to set these properties. - -The options parameter may also include `onComplete` and `onError` -callback functions, which are called when the function has completed -successfully and when it encounters an error, respectively. These options -are both optional. - -@param options {object} -An object containing the properties of the credential to be stored, and -optional `onComplete` and `onError` callback functions. - -@prop username {string} -The username for the credential. - -@prop password {string} -The password for the credential. - -@prop [url] {string} -The URL to which the credential applies. Omitted for add-on -credentials. - -@prop [formSubmitURL] {string} -The URL a form-based credential was submitted to. Omitted for add-on -credentials and HTTP Authentication credentials. - -@prop [realm] {string} -For HTTP Authentication credentials, the realm for which the credential was -requested. For add-on credentials, a name for the credential. - -@prop [usernameField] {string} -The value of the `name` attribute for the username input in a form. -Omitted for add-on credentials and HTTP Authentication credentials. - -@prop [passwordField] {string} -The value of the `name` attribute for the password input in a form. -Omitted for add-on credentials and HTTP Authentication credentials. - -@prop [onComplete] {function} -The callback function that is called once the function completes successfully. - -@prop [onError] {function} -The callback function that is called if the function failed. The -callback is passed an `error` argument: this is an -[nsIException](https://developer.mozilla.org/en/nsIException) object. - -</api> - -<api name="remove"> -@function - -Removes a stored credential. You supply it all the properties of the credential -to remove, along with optional `onComplete` and `onError` callbacks. - -Because you must supply all the credential's properties, it may be convenient -to call `search` first, and use its output as the input to `remove`. For -example, to remove all of joe's stored credentials: - - require("passwords").search({ - username: "joe", - onComplete: function onComplete(credentials) { - credentials.forEach(require("passwords").remove); - }) - }); - -To change an existing credential just call `store` after `remove` succeeds: - - require("passwords").remove({ - realm: "User Registration", - username: "joe", - password: "SeCrEt123" - onComplete: function onComplete() { - require("passwords").store({ - realm: "User Registration", - username: "joe", - password: "{{new password}}" - }) - } - }); - -@param options {object} - -An object containing all the properties of the credential to be removed, -and optional `onComplete` and `onError` callback functions. - -@prop username {string} -The username for the credential. - -@prop password {string} -The password for the credential. - -@prop [url] {string} -The URL to which the credential applies. Omitted for add-on -credentials. - -@prop [formSubmitURL] {string} -The URL a form-based credential was submitted to. Omitted for add-on -credentials and HTTP Authentication credentials. - -@prop [realm] {string} -For HTTP Authentication credentials, the realm for which the credential was -requested. For add-on credentials, a name for the credential. - -@prop [usernameField] {string} -The value of the `name` attribute for the username input in a form. -Omitted for add-on credentials and HTTP Authentication credentials. - -@prop [passwordField] {string} -The value of the `name` attribute for the password input in a form. -Omitted for add-on credentials and HTTP Authentication credentials. - -@prop [onComplete] {function} -The callback function that is called once the function has completed -successfully. - -@prop [onError] {function} -The callback function that is called if the function failed. The -callback is passed an `error` argument: this is an -[nsIException](https://developer.mozilla.org/en/nsIException) object. - -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/private-browsing.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/private-browsing.md deleted file mode 100644 index e553357..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/private-browsing.md +++ /dev/null @@ -1,50 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Paul O'Shannessy [paul@oshannessy.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -The `private-browsing` module allows you to access Firefox's private browsing -mode, detecting if it is active and when its state changes. - -This module is available in all applications. However, only Firefox will ever -transition into or out of private browsing mode. For all other applications, -`pb.isActive` will always be `false`, and none of the events will be emitted. - -<api name="isActive"> -@property {boolean} - This read-only boolean is true if private browsing mode is turned on. -</api> - -<api name="activate"> -@function - Turns on private browsing mode. -</api> - -<api name="deactivate"> -@function - Turns off private browsing mode. -</api> - -<api name="start"> -@event -Emitted immediately after the browser enters private browsing mode. - - var pb = require("private-browsing"); - pb.on("start", function() { - // Do something when the browser starts private browsing mode. - }); - -</api> - -<api name="stop"> -@event -Emitted immediately after the browser exits private browsing mode. - - var pb = require("private-browsing"); - pb.on("stop", function() { - // Do something when the browser stops private browsing mode. - }); -</api>
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/request.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/request.md deleted file mode 100644 index af37ecf..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/request.md +++ /dev/null @@ -1,203 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `request` module lets you make simple yet powerful network requests. - -<api name="Request"> -@class -The `Request` object is used to make `GET`, `POST` or `PUT` network requests. -It is constructed with a URL to which the request is sent. Optionally the user -may specify a collection of headers and content to send alongside the request -and a callback which will be executed once the request completes. - -Once a `Request` object has been created a `GET` request can be executed by -calling its `get()` method, a `POST` request by calling its `post()` method, -or a `PUT` request by calling its `put()` method. - -When the server completes the request, the `Request` object emits a "complete" -event. Registered event listeners are passed a `Response` object. - -Each `Request` object is designed to be used once. Once `GET`, `POST` or `PUT` -are called, attempting to call either will throw an error. - -Since the request is not being made by any particular website, requests made -here are not subject to the same-domain restriction that requests made in web -pages are subject to. - -With the exception of `response`, all of a `Request` object's properties -correspond with the options in the constructor. Each can be set by simply -performing an assignment. However, keep in mind that the same validation rules -that apply to `options` in the constructor will apply during assignment. Thus, -each can throw if given an invalid value. - -The example below shows how to use Request to get the most recent public tweet. - - var Request = require("request").Request; - var latestTweetRequest = Request({ - url: "http://api.twitter.com/1/statuses/public_timeline.json", - onComplete: function (response) { - var tweet = response.json[0]; - console.log("User: " + tweet.user.screen_name); - console.log("Tweet: " + tweet.text); - } - }); - - // Be a good consumer and check for rate limiting before doing more. - Request({ - url: "http://api.twitter.com/1/account/rate_limit_status.json", - onComplete: function (response) { - if (response.json.remaining_hits) { - latestTweetRequest.get(); - } else { - console.log("You have been rate limited!"); - } - } - }).get(); - -<api name="Request"> -@constructor -This constructor creates a request object that can be used to make network -requests. The constructor takes a single parameter `options` which is used to -set several properties on the resulting `Request`. -@param options {object} - @prop url {string} - This is the url to which the request will be made. - - @prop [onComplete] {function} - This function will be called when the request has received a response (or in - terms of XHR, when `readyState == 4`). The function is passed a `Response` - object. - - @prop [headers] {object} - An unordered collection of name/value pairs representing headers to send - with the request. - - @prop [content] {string,object} - The content to send to the server. If `content` is a string, it should be - URL-encoded (use `encodeURIComponent`). If `content` is an object, it - should be a collection of name/value pairs. Nested objects & arrays should - encode safely. - - For `GET` requests, the query string (`content`) will be appended to the - URL. For `POST` and `PUT` requests, the query string will be sent as the body - of the request. - - @prop [contentType] {string} - The type of content to send to the server. This explicitly sets the - `Content-Type` header. The default value is `application/x-www-form-urlencoded`. - - @prop [overrideMimeType] {string} - Use this string to override the MIME type returned by the server in the - response's Content-Type header. You can use this to treat the content as a - different MIME type, or to force text to be interpreted using a specific - character. - - For example, if you're retrieving text content which was encoded as - ISO-8859-1 (Latin 1), it will be given a content type of "utf-8" and - certain characters will not display correctly. To force the response to - be interpreted as Latin-1, use `overrideMimeType`: - - var Request = require("request").Request; - var quijote = Request({ - url: "http://www.latin1files.org/quijote.txt", - overrideMimeType: "text/plain; charset=latin1", - onComplete: function (response) { - console.log(response.text); - } - }); - - quijote.get(); - -</api> - -<api name="url"> -@property {string} -</api> - -<api name="headers"> -@property {object} -</api> - -<api name="content"> -@property {string,object} -</api> - -<api name="contentType"> -@property {string} -</api> - -<api name="response"> -@property {Response} -</api> - -<api name="get"> -@method -Make a `GET` request. -@returns {Request} -</api> - -<api name="post"> -@method -Make a `POST` request. -@returns {Request} -</api> - -<api name="put"> -@method -Make a `PUT` request. -@returns {Request} -</api> - -<api name="complete"> -@event -The `Request` object emits this event when the request has completed and a -response has been received. - -@argument {Response} -Listener functions are passed the response to the request as a `Response` object. -</api> - -</api> - - -<api name="Response"> -@class -The Response object contains the response to a network request issued using a -`Request` object. It is returned by the `get()`, `post()` or `put()` method of a -`Request` object. - -All members of a `Response` object are read-only. -<api name="text"> -@property {string} -The content of the response as plain text. -</api> - -<api name="json"> -@property {object} -The content of the response as a JavaScript object. The value will be `null` -if the document cannot be processed by `JSON.parse`. -</api> - -<api name="status"> -@property {string} -The HTTP response status code (e.g. *200*). -</api> - -<api name="statusText"> -@property {string} -The HTTP response status line (e.g. *OK*). -</api> - -<api name="headers"> -@property {object} -The HTTP response headers represented as key/value pairs. - -To print all the headers you can do something like this: - - for (var headerName in response.headers) { - console.log(headerName + " : " + response.headers[headerName]); - } - -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/selection.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/selection.md deleted file mode 100644 index f2d4ca5..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/selection.md +++ /dev/null @@ -1,90 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Eric H. Jung [eric.jung@yahoo.com] --> -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -The `selection` module provides a means to get and set text and HTML selections -in the current Firefox page. It can also observe new selections. - -Registering for Selection Notifications ---------------------------------------- - -To be notified when the user makes a selection, register a listener for the -"select" event. Each listener will be called after a selection is made. - - function myListener() { - console.log("A selection has been made."); - } - var selection = require("selection"); - selection.on('select', myListener); - - // You can remove listeners too. - selection.removeListener('select', myListener); - -Iterating Over Discontiguous Selections ---------------------------------------- - -Discontiguous selections can be accessed by iterating over the `selection` -module itself. Each iteration yields a `Selection` object from which `text`, -`html`, and `isContiguous` properties can be accessed. - - -Examples --------- - -Log the current contiguous selection as text: - - var selection = require("selection"); - if (selection.text) - console.log(selection.text); - -Log the current discontiguous selections as HTML: - - var selection = require("selection"); - if (!selection.isContiguous) { - for (var subselection in selection) { - console.log(subselection.html); - } - } - -Surround HTML selections with delimiters: - - var selection = require("selection"); - selection.on('select', function () { - selection.html = "\\\" + selection.html + "///"; - }); - -<api name="text"> -@property {string} - Gets or sets the current selection as plain text. Setting the selection - removes all current selections, inserts the specified text at the location of - the first selection, and selects the new text. Getting the selection when - there is no current selection returns `null`. Setting the selection when there - is no current selection throws an exception. Getting the selection when - `isContiguous` is `true` returns the text of the first selection. -</api> - -<api name="html"> -@property {string} - Gets or sets the current selection as HTML. Setting the selection removes all - current selections, inserts the specified text at the location of the first - selection, and selects the new text. Getting the selection when there is no - current selection returns `null`. Setting the selection when there is no - current selection throws an exception. Getting the selection when - `isContiguous` is `true` returns the text of the first selection. -</api> - -<api name="isContiguous"> -@property {boolean} - `true` if the current selection is a single, contiguous selection, and `false` - if there are two or more discrete selections, each of which may or may not be - spatially adjacent. (Discontiguous selections can be created by the user with - Ctrl+click-and-drag.) -</api> - -<api name="select"> -@event - This event is emitted whenever the user makes a new selection in a page. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/self.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/self.md deleted file mode 100644 index 8ccdb01..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/self.md +++ /dev/null @@ -1,79 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- edited by Erik Vold [erikvvold@gmail.com] --> - -The `self` module provides access to data that is bundled with the add-on -as a whole. It also provides access to the -[Program ID](dev-guide/guides/program-id.html), a value which is -unique for each add-on. - -Note that the `self` module is completely different from the global `self` -object accessible to content scripts, which is used by a content script to -[communicate with the add-on code](dev-guide/guides/content-scripts/using-port.html). - -<api name="id"> -@property {string} -This property is a printable string that is unique for each add-on. It comes -from the `id` property set in the `package.json` file in the main package -(i.e. the package in which you run `cfx xpi`). While not generally of use to -add-on code directly, it can be used by internal API code to index local -storage and other resources that are associated with a particular add-on. -Eventually, this ID will be unspoofable (see -[JEP 118](https://wiki.mozilla.org/Labs/Jetpack/Reboot/JEP/118) for details). -</api> - -<api name="name"> -@property {string} -This property contains the add-on's short name. It comes from the `name` -property in the main package's `package.json` file. -</api> - -<api name="version"> -@property {string} -This property contains the add-on's version string. It comes from the -`version` property set in the `package.json` file in the main package. -</api> - -<api name="data"> -@property {object} -The `data` object is used to access data that was bundled with the add-on. -This data lives in the main package's `data/` directory, immediately below -the `package.json` file. All files in this directory will be copied into the -XPI and made available through the `data` object. - -The [Package Specification](dev-guide/package-spec.html) -section explains the `package.json` file. - -<api name="data.load"> -@method -The `data.load(NAME)` method returns the contents of an embedded data file, -as a string. It is most useful for data that will be modified or parsed in -some way, such as JSON, XML, plain text, or perhaps an HTML template. For -data that can be displayed directly in a content frame, use `data.url(NAME)`. -@param name {string} The filename to be read, relative to the - package's `data` directory. Each package that uses the `self` module - will see its own `data` directory. -@returns {string} -</api> - -<api name="data.url"> -@method -The `data.url(NAME)` method returns a url that points at an embedded -data file. It is most useful for data that can be displayed directly in a -content frame. The url can be passed to a content frame constructor, such -as the Panel: - - var self = require("self"); - var myPanel = require("panel").Panel({ - contentURL: self.data.url("my-panel-content.html") - }); - myPanel.show(); - -@param name {string} The filename to be read, relative to the - package's `data` directory. Each package that uses the `self` module - will see its own `data` directory. -@returns {String} -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-prefs.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-prefs.md deleted file mode 100644 index b3cd076..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-prefs.md +++ /dev/null @@ -1,75 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Erik Vold [erikvvold@gmail.com] --> - -#### *Experimental* - -The `simple-prefs` module lets you easily and persistently store preferences -across application restarts, which can be configured by users in the -Add-ons Manager. - -Introduction ------------- - -With the simple preferences module you can store booleans, integers, and string -values. - - -Inline Options & Default Values -------------------------------- - -In order to have a `options.xul` (for inline options) generated, or a -`defaults/preferences/prefs.js` for default preferences, you will need to -define the preferences in your `package.json`, like so: - - { - "fullName": "Example Add-on", - ... - "preferences": [{ - "name": "somePreference", - "title": "Some preference title", - "description": "Some short description for the preference", - "type": "string", - "value": "this is the default string value" - }] - } - - -<api name="prefs"> -@property {object} - *experimental* A persistent object private to your add-on. Properties with boolean, - number, and string values will be persisted in the Mozilla preferences system. -</api> - - -<api name="on"> -@function - *experimental* Registers an event `listener` that will be called when a preference is changed. - -**Example:** - - function onPrefChange(prefName) { - console.log("The " + prefName + " preference changed."); - } - require("simple-prefs").on("somePreference", onPrefChange); - require("simple-prefs").on("someOtherPreference", onPrefChange); - - -@param prefName {String} - The name of the preference to watch for changes. -@param listener {Function} - The listener function that processes the event. -</api> - -<api name="removeListener"> -@function - *experimental* Unregisters an event `listener` for the specified preference. - -@param prefName {String} - The name of the preference to watch for changes. -@param listener {Function} - The listener function that processes the event. -</api> - diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-storage.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-storage.md deleted file mode 100644 index bbe9cbe..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/simple-storage.md +++ /dev/null @@ -1,220 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `simple-storage` module lets you easily and persistently store data across -Firefox restarts. If you're familiar with [DOM storage][] on the Web, it's -kind of like that, but for add-ons. - -[DOM storage]: https://developer.mozilla.org/en/DOM/Storage - -The simple storage module exports an object called `storage` that is persistent -and private to your add-on. It's a normal JavaScript object, and you can treat -it as you would any other. - -To store a value, just assign it to a property on `storage`: - - var ss = require("simple-storage"); - ss.storage.myArray = [1, 1, 2, 3, 5, 8, 13]; - ss.storage.myBoolean = true; - ss.storage.myNull = null; - ss.storage.myNumber = 3.1337; - ss.storage.myObject = { a: "foo", b: { c: true }, d: null }; - ss.storage.myString = "O frabjous day!"; - -You can store array, boolean, number, object, null, and string values. -If you'd like to store other types of values, you'll first have to convert -them to strings or another one of these types. - -Be careful to set properties on the `storage` object and not the module itself: - - // This is no good! - var ss = require("simple-storage"); - ss.foo = "I will not be saved! :("; - -Simple Storage and "cfx run" ----------------------------- -The simple storage module stores its data in your profile. -Because `cfx run` by default uses a fresh profile each time it runs, -simple storage won't work with add-ons executed using `cfx run` - that -is, stored data will not persist from one run to the next. - -The easiest solution to this problem is to use the -[`--profiledir` option to `cfx run`](dev-guide/cfx-tool.html#profiledir). - -If you use this method, you must end your debugging session by -quitting Firefox normally, not by cancelling the shell command. -If you don't close Firefox normally, then simple storage will -not be notified that the session is finished, and will not write -your data to the backing store. - -Constructing Arrays -------------------- -Be careful to construct array objects conditionally in your code, or you may -zero them each time the construction code runs. For example, this add-on -tries to store the URLs of pages the user visits: - -<pre><code> -var ss = require("simple-storage"); -ss.storage.pages = []; - -require("tabs").on("ready", function(tab) { - ss.storage.pages.push(tab.url); -}); - -var widget = require("widget").Widget({ - id: "log_history", - label: "Log History", - width: 30, - content: "Log", - onClick: function() { - console.log(ss.storage.pages); - } -}); -</code></pre> - -But this isn't going to work, because it empties the array each time the -add-on runs (for example, each time Firefox is started). Line 2 needs -to be made conditional, so the array is only constructed if it does -not already exist: - -<pre><code> -if (!ss.storage.pages) - ss.storage.pages = []; -</code></pre> - -Deleting Data -------------- -You can delete properties using the `delete` operator. Here's an add-on -that adds three widgets to write, read, and delete a value: - -<pre><code> -var widgets = require("widget"); -var ss = require("simple-storage"); - -var widget = widgets.Widget({ - id: "write", - label: "Write", - width: 50, - content: "Write", - onClick: function() { - ss.storage.value = 1; - console.log("Setting value"); - } -}); - -var widget = widgets.Widget({ - id: "read", - label: "Read", - width: 50, - content: "Read", - onClick: function() { - console.log(ss.storage.value); - } -}); - -var widget = widgets.Widget({ - id: "delete", - label: "Delete", - width: 50, - content: "Delete", - onClick: function() { - delete ss.storage.value; - console.log("Deleting value"); - } -}); -</pre></code> - -If you run it, you'll see that after clicking "Read" after clicking -"Delete" gives you the expected output: - -<pre> -info: undefined -</pre> - -Quotas ------- -The simple storage available to your add-on is limited. Currently this limit is -about five megabytes (5,242,880 bytes). You can choose to be notified when you -go over quota, and you should respond by reducing the amount of data in storage. -If the user quits the application while you are over quota, all data stored -since the last time you were under quota will not be persisted. You should not -let that happen. - -To listen for quota notifications, register a listener for the `"OverQuota"` -event. It will be called when your storage goes over quota. - - function myOnOverQuotaListener() { - console.log("Uh oh."); - } - ss.on("OverQuota", myOnOverQuotaListener); - -Listeners can also be removed: - - ss.removeListener("OverQuota", myOnOverQuotaListener); - -To find out how much of your quota you're using, check the module's `quotaUsage` -property. It indicates the percentage of quota your storage occupies. If -you're within your quota, it's a number from 0 to 1, inclusive, and if you're -over, it's a number greater than 1. - -Therefore, when you're notified that you're over quota, respond by removing -storage until your `quotaUsage` is less than or equal to 1. Which particular -data you remove is up to you. For example: - - ss.storage.myList = [ /* some long array */ ]; - ss.on("OverQuota", function () { - while (ss.quotaUsage > 1) - ss.storage.myList.pop(); - }); - - -Private Browsing ----------------- -If your storage is related to your users' Web history, personal information, or -other sensitive data, your add-on should respect [private browsing mode][SUMO]. -While private browsing mode is active, you should not store any sensitive data. - -Because any kind of data can be placed into simple storage, support for private -browsing is not built into the module. Instead, use the -[`private-browsing`](packages/addon-kit/private-browsing.html) module to -check private browsing status and respond accordingly. - -For example, the URLs your users visit should not be stored during private -browsing. If your add-on records the URL of the selected tab, here's how you -might handle that: - - ss.storage.history = []; - var privateBrowsing = require("private-browsing"); - if (!privateBrowsing.isActive) { - var url = getSelectedTabURL(); - ss.storage.history.push(url); - } - -For more information on supporting private browsing, see its [Mozilla Developer -Network documentation][MDN]. While that page does not apply specifically to -SDK-based add-ons (and its code samples don't apply at all), you should follow -its guidance on best practices and policies. - -[SUMO]: http://support.mozilla.com/en-US/kb/Private+Browsing -[MDN]: https://developer.mozilla.org/En/Supporting_private_browsing_mode - - -<api name="storage"> -@property {object} - A persistent object private to your add-on. Properties with array, boolean, - number, object, null, and string values will be persisted. -</api> - -<api name="quotaUsage"> -@property {number} - A number in the range [0, Infinity) that indicates the percentage of quota - occupied by storage. A value in the range [0, 1] indicates that the storage - is within quota. A value greater than 1 indicates that the storage exceeds - quota. -</api> - -<api name="OverQuota"> -@event -The module emits this event when your add-on's storage goes over its quota. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/tabs.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/tabs.md deleted file mode 100644 index f1e44df..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/tabs.md +++ /dev/null @@ -1,385 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Dietrich Ayala [dietrich@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `tabs` module provides easy access to tabs and tab-related events. - -The module itself can be used like a basic list of all opened -tabs across all windows. In particular, you can enumerate it: - - var tabs = require('tabs'); - for each (var tab in tabs) - console.log(tab.title); - -You can also access individual tabs by index: - - var tabs = require('tabs'); - - tabs.on('ready', function () { - console.log('first: ' + tabs[0].title); - console.log('last: ' + tabs[tabs.length-1].title); - }); - -You can open a new tab, specifying various properties including location: - - var tabs = require("tabs"); - tabs.open("http://www.example.com"); - -You can register event listeners to be notified when tabs open, close, finish -loading DOM content, or are made active or inactive: - - var tabs = require("tabs"); - - // Listen for tab openings. - tabs.on('open', function onOpen(tab) { - myOpenTabs.push(tab); - }); - - // Listen for tab content loads. - tabs.on('ready', function(tab) { - console.log('tab is loaded', tab.title, tab.url) - }); - -You can get and set various properties of tabs (but note that properties - relating to the tab's content, such as the URL, will not contain valid -values until after the tab's `ready` event fires). By setting the `url` -property you can load a new page in the tab: - - var tabs = require("tabs"); - tabs.on('activate', function(tab) { - tab.url = "http://www.example.com"; - }); - -You can attach a [content script](dev-guide/guides/content-scripts/index.html) -to the page hosted in a tab, and use that to access and manipulate the page's -content: - - var tabs = require("tabs"); - - tabs.on('activate', function(tab) { - tab.attach({ - contentScript: 'self.postMessage(document.body.innerHTML);', - onMessage: function (message) { - console.log(message); - } - }); - }); - -<api name="activeTab"> -@property {Tab} - -The currently active tab in the active window. This property is read-only. To -activate a `Tab` object, call its `activate` method. - -**Example** - - // Get the active tab's title. - var tabs = require("tabs"); - console.log("title of active tab is " + tabs.activeTab.title); -</api> - -<api name="length"> -@property {number} -The number of open tabs across all windows. -</api> - -<api name="open"> -@function -Opens a new tab. The new tab will open in the active window or in a new window, -depending on the `inNewWindow` option. - -**Example** - - var tabs = require("tabs"); - - // Open a new tab on active window and make tab active. - tabs.open("http://www.mysite.com"); - - // Open a new tab in a new window and make it active. - tabs.open({ - url: "http://www.mysite.com", - inNewWindow: true - }); - - // Open a new tab on active window in the background. - tabs.open({ - url: "http://www.mysite.com", - inBackground: true - }); - - // Open a new tab as an app tab and do something once it's open. - tabs.open({ - url: "http://www.mysite.com", - isPinned: true, - onOpen: function onOpen(tab) { - // do stuff like listen for content - // loading. - } - }); - -@param options {object} -An object containing configurable options for how and where the tab will be -opened, as well as a listeners for the tab events. - -If the only option being used is `url`, then a bare string URL can be passed to -`open` instead of adding at a property of the `options` object. - -@prop [url] {string} -String URL to be opened in the new tab. -This is a required property. - -@prop [inNewWindow] {boolean} -If present and true, a new browser window will be opened and the URL will be -opened in the first tab in that window. This is an optional property. - -@prop [inBackground] {boolean} -If present and true, the new tab will be opened to the right of the active tab -and will not be active. This is an optional property. - -@prop [isPinned] {boolean} -If present and true, then the new tab will be pinned as an -[app tab](http://support.mozilla.com/en-US/kb/what-are-app-tabs). - -@prop [onOpen] {function} -A callback function that will be registered for 'open' event. -This is an optional property. -@prop [onClose] {function} -A callback function that will be registered for 'close' event. -This is an optional property. -@prop [onReady] {function} -A callback function that will be registered for 'ready' event. -This is an optional property. -@prop [onActivate] {function} -A callback function that will be registered for 'activate' event. -This is an optional property. -@prop [onDeactivate] {function} -A callback function that will be registered for 'deactivate' event. -This is an optional property. -</api> - -<api name="Tab"> -@class -A `Tab` instance represents a single open tab. It contains various tab -properties, several methods for manipulation, as well as per-tab event -registration. - -Tabs emit all the events described in the Events section. Listeners are -passed the `Tab` object that triggered the event. - -<api name="title"> -@property {string} -The title of the page currently loaded in the tab. -This property can be set to change the tab title. -</api> - -<api name="url"> -@property {String} -The URL of the page currently loaded in the tab. -This property can be set to load a different URL in the tab. -</api> - -<api name="favicon"> -@property {string} -The URL of the favicon for the page currently loaded in the tab. -This property is read-only. -</api> - -<api name="index"> -@property {integer} -The index of the tab relative to other tabs in the application window. -This property can be set to change its relative position. -</api> - -<api name="isPinned"> -@property {boolean} -Whether or not tab is pinned as an [app tab][]. -This property is read-only. -[app tab]:http://support.mozilla.com/en-US/kb/what-are-app-tabs -</api> - -<api name="getThumbnail"> -@property {method} -Returns thumbnail data URI of the page currently loaded in this tab. -</api> - -<api name="pin"> -@method -Pins this tab as an [app tab][]. -[app tab]:http://support.mozilla.com/en-US/kb/what-are-app-tabs -</api> - -<api name="unpin"> -@method -Unpins this tab. -</api> - -<api name="close"> -@method -Closes this tab. - -@param [callback] {function} -A function to be called when the tab finishes its closing process. -This is an optional argument. -</api> - -<api name="reload"> -@method -Reloads this tab. -</api> - -<api name="activate"> -@method -Makes this tab active, which will bring this tab to the foreground. -</api> - -<api name="attach"> -@method - Create a page mod and attach it to the document in the tab. - -**Example** - - var tabs = require("tabs"); - - tabs.on('ready', function(tab) { - tab.attach({ - contentScript: - 'document.body.style.border = "5px solid red";' - }); - }); - -@param options {object} - Options for the page mod, with the following keys: - -@prop [contentScriptFile] {string,array} - The local file URLs of content scripts to load. Content scripts specified - by this option are loaded *before* those specified by the `contentScript` - option. Optional. -@prop [contentScript] {string,array} - The texts of content scripts to load. Content scripts specified by this - option are loaded *after* those specified by the `contentScriptFile` option. - Optional. -@prop [onMessage] {function} - A function called when the page mod receives a message from content scripts. - Listeners are passed a single argument, the message posted from the - content script. Optional. - -@returns {Worker} - See [Content Scripts guide](dev-guide/guides/content-scripts/index.html) - to learn how to use the `Worker` object to communicate with the content script. - -</api> - -<api name="close"> -@event - -This event is emitted when the tab is closed. It's also emitted when the -tab's window is closed. - -@argument {Tab} -Listeners are passed the tab object. -</api> - -<api name="ready"> -@event - -This event is emitted when the DOM for the tab's content is ready. It is -equivalent to the `DOMContentLoaded` event for the given content page. - -A single tab will emit this event every time the DOM is loaded: so it will be -emitted again if the tab's location changes or the content is reloaded. - -After this event has been emitted, all properties relating to the tab's -content can be used. - -@argument {Tab} -Listeners are passed the tab object. -</api> - -<api name="activate"> -@event - -This event is emitted when the tab is made active. - -@argument {Tab} -Listeners are passed the tab object. -</api> - -<api name="deactivate"> -@event - -This event is emitted when the tab is made inactive. - -@argument {Tab} -Listeners are passed the tab object. -</api> - -</api> - -<api name="open"> -@event - -This event is emitted when a new tab is opened. This does not mean that -the content has loaded, only that the browser tab itself is fully visible -to the user. - -Properties relating to the tab's content (for example: `title`, `favicon`, -and `url`) will not be correct at this point. If you need to access these -properties, listen for the `ready` event: - - var tabs = require("tabs"); - tabs.on('open', function(tab){ - tab.on('ready', function(tab){ - console.log(tab.url); - }); - }); - -@argument {Tab} -Listeners are passed the tab object that just opened. -</api> - -<api name="close"> -@event - -This event is emitted when a tab is closed. When a window is closed -this event will be emitted for each of the open tabs in that window. - -@argument {Tab} -Listeners are passed the tab object that has closed. -</api> - -<api name="ready"> -@event - -This event is emitted when the DOM for a tab's content is ready. -It is equivalent to the `DOMContentLoaded` event for the given content page. - -A single tab will emit this event every time the DOM is loaded: so it will be -emitted again if the tab's location changes or the content is reloaded. - -After this event has been emitted, all properties relating to the tab's -content can be used. - -@argument {Tab} -Listeners are passed the tab object that has loaded. -</api> - -<api name="activate"> -@event - -This event is emitted when an inactive tab is made active. - -@argument {Tab} -Listeners are passed the tab object that has become active. -</api> - -<api name="deactivate"> -@event - -This event is emitted when the active tab is made inactive. - -@argument {Tab} -Listeners are passed the tab object that has become inactive. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/timers.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/timers.md deleted file mode 100644 index 192663a..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/timers.md +++ /dev/null @@ -1,52 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> -<!-- contributed by Irakli Gozalishvil [gozala@mozilla.com] --> - -The `timers` module provides access to web-like timing functionality. - -<api name="setTimeout"> -@function - Schedules `callback` to be called in `ms` milliseconds. Any additional - arguments are passed straight through to the callback. -@returns {integer} - An ID that can later be used to undo this scheduling, if `callback` hasn't yet - been called. -@param callback {function} - Function to be called. -@param ms {integer} - Interval in milliseconds after which the function will be called. -</api> - -<api name="clearTimeout"> -@function - Given an ID returned from `setTimeout()`, prevents the callback with the ID - from being called (if it hasn't yet been called). -@param ID {integer} - An ID returned from `setTimeout()`. -</api> - -<api name="setInterval"> -@function - Schedules `callback` to be called repeatedly every `ms` milliseconds. Any - additional arguments are passed straight through to the callback. -@returns {integer} - An ID that can later be used to unschedule the callback. -@param callback {function} - Function to be called. -@param ms {integer} - Interval in milliseconds at which the function will be called. -</api> - -<api name="clearInterval"> -@function - Given an ID returned from `setInterval()`, prevents the callback with the ID - from being called again. -@param ID {integer} - An ID returned from `setInterval()`. -</api> - diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/widget.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/widget.md deleted file mode 100644 index 815a085..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/widget.md +++ /dev/null @@ -1,909 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Dietrich Ayala [dietrich@mozilla.com] --> -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `widget` module provides your add-on with a simple user interface that is -consistent with other add-ons and blends in well with Firefox. - -"Widgets" are small pieces of content that live in the Firefox 4 -[add-on bar](https://developer.mozilla.org/en/The_add-on_bar). -They can be simple icons or complex web pages. You can attach -[panels](packages/addon-kit/panel.html) to them that open when they're -clicked, or you can define a custom click handler to perform some other action, -like opening a web page in a tab. - -There are a few advantages to using widgets over an ad hoc user interface. -First, your users will be accustomed to interacting with add-ons via widgets and -the add-on bar. Second, it allows Firefox to treat your interface as a -first-class citizen. For example, in the future Firefox may allow the user to -drag widgets from the add-on bar to other toolbars. By exposing your interface -as a widget, your add-on would automatically inherit such functionality. - -## Creation and Content ## - -Widgets can contain images or arbitrary web content. You can include this -content inline as a string by using the `content` property, or point to content -using a URL with the `contentURL` property. - -Upon creation, the widget is automatically added to the add-on bar. -You can set the width of a widget, but the height is fixed so as to fit in the -add-on bar. If the content is an image, it is automatically scaled to be 16x16 -pixels. - -For example, this widget contains an image, so it looks like a simple icon: - - require("widget").Widget({ - id: "mozilla-icon", - label: "My Mozilla Widget", - contentURL: "http://www.mozilla.org/favicon.ico" - }); - -<img class="image-center" src="static-files/media/screenshots/widget-mozilla-icon.png" -alt="Widget displaying an icon"> - -You can make `contentURL` point to an HTML or icon file which you have -packaged inside your add-on. Just save the file in your add-on's `data` -directory, and reference it using the `data.url()` method of the -[`self`](packages/addon-kit/self.html) module: - - var data = require("self").data; - - require("widget").Widget({ - id: "my-widget", - label: "My Widget", - contentURL: data.url("my-content.html") - }); - -This widget contains an entire web page: - - require("widget").Widget({ - id: "hello-display", - label: "My Hello Widget", - content: "Hello!", - width: 50 - }); - -<img class="image-center" src="static-files/media/screenshots/widget-hello-text.png" -alt="Widget displaying 'hello'"> - -Widgets are quite small by default, so this example used the `width` property to -grow it in order to show all the text. - -## Scripting Widget Content ## - -To interact with the widget's content you need to load a separate script into -the panel. In the SDK these scripts are called "content scripts" because -they're explicitly used for interacting with web content. - -While content scripts can access the content they're attached to, they can't -use the SDK's APIs. So implementing a complete solution usually means you -have to send messages between the content script and the main add-on code. - -* You can specify one or more content scripts to load into the widget using the -`contentScript` or `contentScriptFile` options to the -[`Widget()` constructor](packages/addon-kit/widget.html#Widget(options)). - -* You can communicate with the script using either the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or (preferably, usually) the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. - -<div class="warning"> -<p>Unless your content script is extremely simple and consists only of a -static string, don't use <code>contentScript</code>: if you do, you may -have problems getting your add-on approved on AMO.</p> -<p>Instead, keep the script in a separate file and load it using -<code>contentScriptFile</code>. This makes your code easier to maintain, -secure, debug and review.</p> -</div> - -<!-- The icons this widget displays, shown in the screenshot, is taken from the -Glossy Buttons icon set created by IconEden which is made freely available for -commercial and non-commercial use. -See: http://www.iconeden.com/icon/category/free --> - -<img class="image-right" src="static-files/media/screenshots/widget-player-buttons.png" -alt="Media player UI implemented as a widget"> - -For example, suppose we want to implement a media player as an add-on. -We could implement the main user interface as a widget hosting an array -of buttons to control play/pause/stop functions. - -We can then use a content script to listen for clicks on those buttons. -But because content scripts can't use the SDK's APIs, we'll want the -content script to send messages to the main add-on code, which can then -implement the media player functions using the SDK. - -The widget's content is specified using HTML like this: - -<pre class="brush: html"> -<html> - <body> - <img src="play.png" id="play-button"> - <img src="pause.png" id="pause-button"> - <img src="stop.png" id="stop-button"> - </body> -</html> -</pre> - -We just include three icons, and assign an ID to each one. This HTML file, -and the icon files it references, are saved in the add-on's `data` -directory. - -Next, we write a content script that listens for click events on each icon -and sends the corresponding message to the main add-on code: - - var play_button = document.getElementById("play-button"); - play_button.onclick = function() { - self.port.emit("play"); - } - - var pause_button = document.getElementById("pause-button"); - pause_button.onclick = function() { - self.port.emit("pause"); - } - - var stop_button = document.getElementById("stop-button"); - stop_button.onclick = function() { - self.port.emit("stop"); - } - -We save this file in the add-on's `data` directory as "button-script.js". -Finally. in the add-on's "main.js" file, we create the widget, assign it -the HTML file and the content script, and listen for events from the content -script: - - const widgets = require("widget"); - const data = require("self").data; - - var player = widgets.Widget({ - id: "player", - width: 72, - label: "Player", - contentURL: data.url("buttons.html"), - contentScriptFile: data.url("button-script.js") - }); - - player.port.on("play", function() { - console.log("playing"); - }); - - player.port.on("pause", function() { - console.log("pausing"); - }); - - player.port.on("stop", function() { - console.log("stopping"); - }); - -To learn much more about content scripts, see the -[Working with Content Scripts](dev-guide/guides/content-scripts/index.html) -guide. - -<div class="experimental"> -<h3>Scripting Trusted Widget Content</h3> - -**Note that the feature described in this section is experimental: we'll -very probably continue to support it, but the name of the `addon` -property might change in a future release.** - -We've already seen that you can package HTML files in your add-on's `data` -directory and use them to define the widget's content. We can call this -"trusted" content, because unlike content loaded from a source outside the -add-on, the add-on author knows exactly what it's doing. To -interact with trusted content you don't need to use content scripts: -you can just include a script from the HTML file in the normal way, using -`script` tags. - -Like a content script, these scripts can communicate with the add-on code -using the -[`postMessage()`](dev-guide/guides/content-scripts/using-postmessage.html) -API or the -[`port`](dev-guide/guides/content-scripts/using-port.html) API. -The crucial difference is that these scripts access the `postMessage` -and `port` objects through the `addon` object, whereas content scripts -access them through the `self` object. - -To show the difference, convert the `player` add-on above -to use normal page scripts instead of content scripts. - -First, in the content script, change `self` to `addon`, and wrap it in a -function: - - function init() { - var play_button = document.getElementById("play-button"); - play_button.onclick = function() { - addon.port.emit("play"); - } - - var pause_button = document.getElementById("pause-button"); - pause_button.onclick = function() { - addon.port.emit("pause"); - } - - var stop_button = document.getElementById("stop-button"); - stop_button.onclick = function() { - addon.port.emit("stop"); - } - } - -Next, add a `script` tag to reference "button-script.js", and -call its `init()` function on load: - -<pre class="brush: html"> -<html> - <head> - <script src="button-script.js"></script> - </head> - <body onLoad="init()"> - <img src="play.png" id="play-button"> - <img src="pause.png" id="pause-button"> - <img src="stop.png" id="stop-button"> - </body> -</html> -</pre> - -Finally, remove the line attaching the content script from "main.js": - - const widgets = require("widget"); - const data = require("self").data; - - var player = widgets.Widget({ - id: "player", - width: 72, - label: "Player", - contentURL: data.url("buttons.html") - }); - - player.port.emit("init"); - - player.port.on("play", function() { - console.log("playing"); - }); - - player.port.on("pause", function() { - console.log("pausing"); - }); - - player.port.on("stop", function() { - console.log("stopping"); - }); -</div> - -## Attaching Panels to Widgets ## - -You can supply a [panel](packages/addon-kit/panel.html) to the widget's -constructor: if you do this, the panel is automatically displayed when the -user clicks the widget. - -<!-- The icon the widget displays, shown in the screenshot, is taken from the -Circular icon set, http://prothemedesign.com/circular-icons/ which is made -available under the Creative Commons Attribution 2.5 Generic License: -http://creativecommons.org/licenses/by/2.5/ --> - -<img class="image-right" src="static-files/media/screenshots/widget-panel-clock.png" -alt="Panel attached to a widget"> - - data = require("self").data - - var clockPanel = require("panel").Panel({ - width:215, - height:160, - contentURL: data.url("clock.html") - }); - - require("widget").Widget({ - id: "open-clock-btn", - label: "Clock", - contentURL: data.url("History.png"), - panel: clockPanel - }); - -Note that this is, at the moment, the only way you can attach a panel to a widget. - -You must supply the panel in the widget's constructor for it to work. If you -assign the panel to the widget after construction, the panel can still be shown -but will not be anchored to the widget: - - data = require("self").data - - var clockPanel = require("panel").Panel({ - width:215, - height:160, - contentURL: data.url("clock.html") - }); - - widget = require("widget").Widget({ - id: "open-clock-btn", - label: "Clock", - contentURL: data.url("History.png") - }); - - widget.panel = clockPanel; - - // Will not be anchored - widget.panel.show(); - -Also, if you try to call `panel.show()` inside your widget's `click` event -listener, the panel will not be anchored: - - data = require("self").data - - var clockPanel = require("panel").Panel({ - width:215, - height:160, - contentURL: data.url("clock.html") - }); - - require("widget").Widget({ - id: "open-clock-btn", - label: "Clock", - contentURL: data.url("History.png"), - panel: clockPanel, - onClick: function() { - // Will not be anchored - this.panel.show(); - } - }); - -See [bug 638142](https://bugzilla.mozilla.org/show_bug.cgi?id=638142). - -## Examples ## - -For conciseness, these examples create their content scripts as strings and use -the `contentScript` property. In your own add-ons, you will probably want to -create your content scripts in separate files and pass their URLs using the -`contentScriptFile` property. See -[Working with Content Scripts](dev-guide/guides/content-scripts/index.html) for more -information. - - var widgets = require("widget"); - - // A basic click-able image widget. - widgets.Widget({ - id: "google-link", - label: "Widget with an image and a click handler", - contentURL: "http://www.google.com/favicon.ico", - onClick: function() { - require("tabs").activeTab.url = "http://www.google.com/"; - } - }); -<br> - - // A widget that changes display on mouseover. - widgets.Widget({ - id: "mouseover-effect", - label: "Widget with changing image on mouseover", - contentURL: "http://www.yahoo.com/favicon.ico", - onMouseover: function() { - this.contentURL = "http://www.bing.com/favicon.ico"; - }, - onMouseout: function() { - this.contentURL = "http://www.yahoo.com/favicon.ico"; - } - }); -<br> - - // A widget that updates content on a timer. - widgets.Widget({ - id: "auto-update-widget", - label: "Widget that updates content on a timer", - content: "0", - contentScript: 'setTimeout(function() {' + - ' document.body.innerHTML++;' + - '}, 2000)', - contentScriptWhen: "ready" - }); -<br> - - // A widget that loads a random Flickr photo every 5 minutes. - widgets.Widget({ - id: "random-flickr", - label: "Random Flickr Photo Widget", - contentURL: "http://www.flickr.com/explore/", - contentScriptWhen: "ready", - contentScript: 'postMessage(document.querySelector(".pc_img").src);' + - 'setTimeout(function() {' + - ' document.location = "http://www.flickr.com/explore/";' + - '}, 5 * 60 * 1000);', - onMessage: function(imgSrc) { - this.contentURL = imgSrc; - }, - onClick: function() { - require("tabs").activeTab.url = this.contentURL; - } - }); -<br> - - // A widget created with a specified width, that grows. - let myWidget = widgets.Widget({ - id: "widget-effect", - label: "Wide widget that grows wider on a timer", - content: "I'm getting longer.", - width: 50, - }); - require("timers").setInterval(function() { - myWidget.width += 10; - }, 1000); -<br> - - // A widget communicating bi-directionally with a content script. - let widget = widgets.Widget({ - id: "message-test", - label: "Bi-directional communication!", - content: "<foo>bar</foo>", - contentScriptWhen: "ready", - contentScript: 'on("message", function(message) {' + - ' alert("Got message: " + message);' + - '});' + - 'postMessage("ready");', - onMessage: function(message) { - if (message == "ready") - widget.postMessage("me too"); - } - }); - -<api-name="Widget"> -@class -Represents a widget object. - -<api name="Widget"> -@constructor {options} - Creates a new widget. The widget is immediately added to the add-on bar. - -@param options {object} - An object with the following keys: - - @prop label {string} - A required string description of the widget used for accessibility, - title bars, and error reporting. - - @prop id {string} - Mandatory string used to identify your widget in order to save its - location when the user moves it in the browser. - This string has to be unique and must not be changed over time. - - @prop [content] {string} - An optional string value containing the displayed content of the widget. - It may contain HTML. Widgets must have either the `content` property or the - `contentURL` property set. - - If the content is an image, it is automatically scaled to be 16x16 pixels. - - @prop [contentURL] {string} - An optional string URL to content to load into the widget. This can be - [local content](dev-guide/guides/content-scripts/index.html) or remote - content, an image or web content. Widgets must have either the `content` - property or the `contentURL` property set. - - If the content is an image, it is automatically scaled to be 16x16 pixels. - - @prop [panel] {Panel} - An optional [panel](packages/addon-kit/panel.html) to open when the - user clicks on the widget. Note: If you also register a "click" listener, - it will be called instead of the panel being opened. However, you can show - the panel from the listener by calling `this.panel.show()`. - - @prop [width] {integer} - Optional width in pixels of the widget. If not given, a default width is - used. - - @prop [onClick] {function} - Include this to listen to the widget's `click` event. - - @prop [onMessage] {function} - Include this to listen to the widget's `message` event. - - @prop [onMouseover] {function} - Include this to listen to the widget's `mouseover` event. - - @prop [onMouseout] {function} - Include this to listen to the widget's `mouseout` event. - - @prop [onAttach] {function} - Include this to listen to the widget's `attach` event. - - @prop [tooltip] {string} - Optional text to show when the user's mouse hovers over the widget. If not - given, the `label` is used. - - @prop [allow] {object} - An optional object describing permissions for the content. It should - contain a single key named `script` whose value is a boolean that indicates - whether or not to execute script in the content. `script` defaults to true. - - @prop [contentScriptFile] {string,array} - A local file URL or an array of local file URLs of content scripts to load. - Content scripts specified by this property are loaded *before* those - specified by the `contentScript` property. - - @prop [contentScript] {string,array} - A string or an array of strings containing the texts of content scripts to - load. Content scripts specified by this property are loaded *after* those - specified by the `contentScriptFile` property. - - @prop [contentScriptWhen="end"] {string} - When to load the content scripts. This may take one of the following - values: - - * "start": load content scripts immediately after the document - element for the widget is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the widget has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - - This property is optional and defaults to "end". - -</api> - -<api name="destroy"> -@method - Removes the widget from the add-on bar. -</api> - -<api name="postMessage"> -@method - Sends a message to the widget's content scripts. -@param data {value} - The message to send. - The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="on"> -@method - Registers an event listener with the widget. -@param type {string} - The type of event to listen for. -@param listener {function} - The listener function that handles the event. -</api> - -<api name="removeListener"> -@method - Unregisters an event listener from the widget. -@param type {string} - The type of event for which `listener` was registered. -@param listener {function} - The listener function that was registered. -</api> - -<api name="getView"> -@method - Retrieve a `WidgetView` instance of this widget relative to a browser window. -@param window {BrowserWindow} - The [BrowserWindow](packages/addon-kit/windows.html) instance to match. -@returns {WidgetView} - A `WidgetView` instance associated with the browser window. Any changes - subsequently applied to this object will only be applied to the widget - attached to that window. -</api> - -<api name="label"> -@property {string} - The widget's label. Read-only. -</api> - -<api name="content"> -@property {string} - A string containing the widget's content. It can contain HTML. Setting it - updates the widget's appearance immediately. However, if the widget was - created using `contentURL`, then this property is meaningless, and setting it - has no effect. -</api> - -<api name="contentURL"> -@property {string} - The URL of content to load into the widget. This can point to - local content loaded from your add-on's "data" directory or remote - content, an image or web content. Setting it updates the widget's appearance - immediately. However, if the widget was created using `content`, then this - property is meaningless, and setting it has no effect. -</api> - -<api name="panel"> -@property {Panel} - A [panel](packages/addon-kit/panel.html) to open when the user clicks on - the widget. -</api> - -<api name="width"> -@property {number} - The widget's width in pixels. Setting it updates the widget's appearance - immediately. -</api> - -<api name="tooltip"> -@property {string} - The text of the tooltip that appears when the user hovers over the widget. -</api> - -<api name="allow"> -@property {object} - A object describing permissions for the content. It contains a single key - named `script` whose value is a boolean that indicates whether or not to - execute script in the content. -</api> - -<api name="contentScriptFile"> -@property {string,array} - A local file URL or an array of local file URLs of content scripts to load. -</api> - -<api name="contentScript"> -@property {string,array} - A string or an array of strings containing the texts of content scripts to - load. -</api> - -<api name="contentScriptWhen"> -@property {string} - When to load the content scripts. This may have one of the following - values: - - * "start": load content scripts immediately after the document - element for the widget is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the widget has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - -</api> - -<api name="port"> -@property {EventEmitter} -[EventEmitter](packages/api-utils/events.html) object that allows you to: - -* send events to the content script using the `port.emit` function -* receive events from the content script using the `port.on` function - -See the guide to -<a href="dev-guide/guides/content-scripts/using-port.html"> -communicating using <code>port</code></a> for details. -</api> - -<api name="attach"> -@event -This event is emitted when a new `WidgetView` object is created using the -`getView()` function. -</api> - -<api name="click"> -@event -This event is emitted when the widget is clicked. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this widget. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the widget's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="mouseover"> -@event -This event is emitted when the user moves the mouse over the widget. -</api> - -<api name="mouseout"> -@event -This event is emitted when the user moves the mouse away from the widget. -</api> - -</api> - - -<api-name="WidgetView"> -@class -Represents a widget instance specific to one browser window. - -Anything you do to an instance of this object will only be applied to the -instance attached to its browser window: widget instances attached to other -browser windows will be unaffected. - -By contrast, any changes you make to an instance of the normal `Widget` class -will be applied across all browser windows. - -This class has all the same methods, attributes and events as the `Widget` -class except for the `getView` method and the `attach` event. - -In this example `WidgetView` is used to display different content for -`http` and `https` schemes: - - // A widget that update its content specifically to each window. - let tabs = require("tabs"); - let windows = require("windows").browserWindows; - let widget = widgets.Widget({ - id: "window-specific-test", - label: "Widget with content specific to each window", - content: " ", - width: 50 - }); - // Observe tab switch or document changes in each existing tab: - function updateWidgetState(tab) { - let view = widget.getView(tab.window); - if (!view) return; - // Update widget displayed text: - view.content = tab.url.match(/^https/) ? "Secured" : "Unsafe"; - } - tabs.on('ready', updateWidgetState); - tabs.on('activate', updateWidgetState); - -<api name="destroy"> -@method - Removes the widget view from the add-on bar. -</api> - -<api name="postMessage"> -@method - Sends a message to the widget view's content scripts. -@param data {value} - The message to send. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="on"> -@method - Registers an event listener with the widget view. -@param type {string} - The type of event to listen for. -@param listener {function} - The listener function that handles the event. -</api> - -<api name="removeListener"> -@method - Unregisters an event listener from the widget view. -@param type {string} - The type of event for which `listener` was registered. -@param listener {function} - The listener function that was registered. -</api> - -<api name="label"> -@property {string} - The widget view's label. Read-only. -</api> - -<api name="content"> -@property {string} - A string containing the widget view's content. It can contain HTML. - Setting it updates the widget view's appearance immediately. However, - if the widget view was created using `contentURL`, then this property - is meaningless, and setting it has no effect. -</api> - -<api name="contentURL"> -@property {string} - The URL of content to load into the widget. This can point to - local content loaded from your add-on's "data" directory or remote - content, an image or web content. Setting it updates the widget's appearance - immediately. However, if the widget was created using `content`, then this - property is meaningless, and setting it has no effect. -</api> - -<api name="panel"> -@property {Panel} - A [panel](packages/addon-kit/panel.html) to open when the user clicks on - the widget view. -</api> - -<api name="width"> -@property {number} - The widget view's width in pixels. Setting it updates the widget view's - appearance immediately. -</api> - -<api name="tooltip"> -@property {string} - The text of the tooltip that appears when the user hovers over the widget - view. -</api> - -<api name="allow"> -@property {object} - A object describing permissions for the content. It contains a single key - named `script` whose value is a boolean that indicates whether or not to - execute script in the content. -</api> - -<api name="contentScriptFile"> -@property {string,array} - A local file URL or an array of local file URLs of content scripts to load. -</api> - -<api name="contentScript"> -@property {string,array} - A string or an array of strings containing the texts of content scripts to - load. -</api> - -<api name="contentScriptWhen"> -@property {string} - When to load the content scripts. This may have one of the following - values: - - * "start": load content scripts immediately after the document - element for the widget view is inserted into the DOM, but before the DOM - content itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the widget view has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - -</api> - -<api name="port"> -@property {EventEmitter} -[EventEmitter](packages/api-utils/events.html) object that allows you to: - -* send events to the content script using the `port.emit` function -* receive events from the content script using the `port.on` - -See the guide to -<a href="dev-guide/guides/content-scripts/using-port.html"> -communicating using <code>port</code></a> for details. -</api> - -<api name="detach"> -@event -The `detach` event is fired when the widget view is removed from its related -window. -This can occur if the window is closed, Firefox exits, or the add-on is -disabled. -</api> - -<api name="click"> -@event -This event is emitted when the widget view is clicked. -</api> - -<api name="message"> -@event -If you listen to this event you can receive message events from content -scripts associated with this widget view. When a content script posts a -message using `self.postMessage()`, the message is delivered to the add-on -code in the widget view's `message` event. - -@argument {value} -Listeners are passed a single argument which is the message posted -from the content script. The message can be any -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="mouseover"> -@event -This event is emitted when the user moves the mouse over the widget view. -</api> - -<api name="mouseout"> -@event -This event is emitted when the user moves the mouse away from the widget view. -</api> - -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/docs/windows.md b/tools/addon-sdk-1.7/packages/addon-kit/docs/windows.md deleted file mode 100644 index f44817e..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/docs/windows.md +++ /dev/null @@ -1,191 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Felipe Gomes [felipc@gmail.com] --> - - -The `windows` module provides easy access to browser windows, their -tabs, and open/close related functions and events. - -This module currently only supports browser windows and does not provide -access to non-browser windows such as the Bookmarks Library, preferences -or other non-browser windows created via add-ons. - -<api name="browserWindows"> -@property {List} -An object that contains various properties and methods to access -functionality from browser windows, such as opening new windows, accessing -their tabs or switching the current active window. - -`browserWindows` provides access to all the currently open browser windows: - - var windows = require("windows"); - for each (var window in windows.browserWindows) { - console.log(window.title); - } - - console.log(windows.browserWindows.length); - -Object emits all the events listed under "Events" section. - -####Examples#### - - var windows = require("windows").browserWindows; - - // add a listener to the 'open' event - windows.on('open', function(window) { - myOpenWindows.push(window); - }); - - // add a listener to the 'close' event - windows.on('close', function(window) { - console.log("A window was closed."); - }); - -<api name="activeWindow"> -@property {BrowserWindow} - -The currently active window. This property is read-only. - -**Example** - - // get - var windows = require("windows"); - console.log("title of active window is " + - windows.browserWindows.activeWindow.title); - - anotherWindow.activate(); - // set - windows.activeWindow == anotherWindow // true -</api> - -</api> - -<api name="open"> -@function -Open a new window. - - var windows = require("windows").browserWindows; - - // Open a new window. - windows.open("http://www.example.com"); - - // Open a new window and set a listener for "open" event. - windows.open({ - url: "http://www.example.com", - onOpen: function(window) { - // do stuff like listen for content - // loading. - } - }); - -Returns the window that was opened: - - var widgets = require("widget"); - var windows = require("windows").browserWindows; - - var example = windows.open("http://www.example.com"); - - var widget = widgets.Widget({ - id: "close-window", - label: "Close window", - contentURL: "http://www.mozilla.org/favicon.ico", - onClick: function() { - example.close(); - } - }); - -@param options {object} -An object containing configurable options for how this window will be opened, -as well as a callback for being notified when the window has fully opened. - -If the only option being used is `url`, then a bare string URL can be passed to -`open` instead of specifying it as a property of the `options` object. - -@prop url {string} -String URL to be opened in the new window. -This is a required property. - -@prop [onOpen] {function} -A callback function that is called when the window has opened. This does not -mean that the URL content has loaded, only that the window itself is fully -functional and its properties can be accessed. This is an optional property. - -@prop [onClose] {function} -A callback function that is called when the window will be called. -This is an optional property. - -@returns {BrowserWindow} -</api> - -<api name="BrowserWindow"> -@class -A `BrowserWindow` instance represents a single open window. They can be -retrieved from the `browserWindows` property exported by this module. - - var windows = require("windows").browserWindows; - - //Print how many tabs the current window has - console.log("The active window has " + - windows.activeWindow.tabs.length + - " tabs."); - - // Print the title of all browser windows - for each (var window in windows) { - console.log(window.title); - } - - // close the active window - windows.activeWindow.close(); - - windows.activeWindow.close(function() { - console.log("The active window was closed"); - }); - -<api name="title"> -@property {string} -The current title of the window. Usually the title of the active tab, -plus an app identifier. -This property is read-only. -</api> - -<api name="tabs"> -@property {TabList} -A live list of tabs in this window. This object has the same interface as the -[`tabs` API](packages/addon-kit/tabs.html), except it contains only the -tabs in this window, not all tabs in all windows. This property is read-only. -</api> - -<api name="activate"> -@method -Makes window active, which will focus that window and bring it to the -foreground. -</api> - -<api name="close"> -@method -Close the window. - -@param [callback] {function} -A function to be called when the window finishes its closing process. -This is an optional argument. -</api> - -</api> - -<api name="open"> -@event -Event emitted when a new window is open. -This does not mean that the content has loaded, only that the browser window -itself is fully visible to the user. -@argument {Window} -Listeners are passed the `window` object that triggered the event. -</api> - -<api name="close"> -@event -Event emitted when a window is closed. -@argument {Window} -Listeners are passed the `window` object that triggered the event. -</api> diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/addon-page.js b/tools/addon-sdk-1.7/packages/addon-kit/lib/addon-page.js deleted file mode 100644 index eeb5461..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/addon-page.js +++ /dev/null @@ -1,33 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -'use strict'; - -const { uriPrefix, name } = require('@packaging'); -const { WindowTracker, isBrowser } = require('api-utils/window-utils'); -const { add, remove } = require('api-utils/array'); -const { getTabs, closeTab } = require('api-utils/tabs/utils'); - -// Note: This is an URL that will be returned by calling -// `require('self').data.url('index.html')` from the add-on modules. -// We could not use this expression as in this module it would have -// returned "addon-kit/data/index.html" instead. -const addonURL = uriPrefix + name + '/data/index.html'; - -WindowTracker({ - onTrack: function onTrack(window) { - if (isBrowser(window)) - add(window.XULBrowserWindow.inContentWhitelist, addonURL); - }, - onUntrack: function onUntrack(window) { - getTabs(window). - filter(function(tab) tab.linkedBrowser.currentURI.spec === addonURL). - forEach(function(tab) { - // Note: `onUntrack` will be called for all windows on add-on unloads, - // so we want to clean them up from these URLs. - remove(window.XULBrowserWindow.inContentWhitelist, addonURL); - closeTab(tab); - }); - } -}); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/private-browsing.js b/tools/addon-sdk-1.7/packages/addon-kit/lib/private-browsing.js deleted file mode 100644 index ff40c98..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/private-browsing.js +++ /dev/null @@ -1,61 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Cc, Ci } = require("chrome"); -const { emit, on, once, off } = require("api-utils/event/core"); -const { defer } = require("api-utils/functional"); -const { when: unload } = require("api-utils/unload"); -const observers = require("api-utils/observer-service"); - -// Model holding a state. -const model = { active: false }; - -let deferredEmit = defer(emit); - -let pbService; -// Currently, only Firefox implements the private browsing service. -if (require("api-utils/xul-app").is("Firefox")) { - pbService = Cc["@mozilla.org/privatebrowsing;1"]. - getService(Ci.nsIPrivateBrowsingService); - - // Update model state. - model.active = pbService.privateBrowsingEnabled; - - // set up an observer for private browsing switches. - observers.add('private-browsing-transition-complete', function onChange() { - // Update model state. - model.active = pbService.privateBrowsingEnabled; - // Emit event with in next turn of event loop. - deferredEmit(exports, model.active ? 'start' : 'stop'); - }); -} - -let setMode = defer(function setMode(value) { - // We toggle private browsing mode asynchronously in order to work around - // bug 659629. Since private browsing transitions are asynchronous - // anyway, this doesn't significantly change the behavior of the API. - pbService.privateBrowsingEnabled = !!value -}); - - -// Make sure listeners are cleaned up. -unload(function() off(exports)); - -Object.defineProperty(exports, "isActive", { get: function() model.active }); -exports.activate = function activate() pbService && setMode(true) -exports.deactivate = function deactivate() pbService && setMode(false) -exports.on = on.bind(null, exports); -exports.once = once.bind(null, exports); -exports.removeListener = function removeListener(type, listener) { - // Note: We can't just bind `off` as we do it for other methods cause skipping - // a listener argument will remove all listeners for the given event type - // causing misbehavior. This way we make sure all arguments are passed. - off(exports, type, listener); -}; - -// This is workaround making sure that exports is wrapped before it's -// frozen, which needs to happen in order to workaround Bug 673468. -off(exports, 'workaround-bug-673468'); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/simple-prefs.js b/tools/addon-sdk-1.7/packages/addon-kit/lib/simple-prefs.js deleted file mode 100644 index 5f73cc5..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/simple-prefs.js +++ /dev/null @@ -1,68 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const { Cc, Ci } = require("chrome"); -const { emit, off } = require("api-utils/event/core"); -const { EventTarget } = require("api-utils/event/target"); -const { when: unload } = require("api-utils/unload"); -const { jetpackID } = require("@packaging"); -const prefService = require("api-utils/preferences-service"); -const observers = require("api-utils/observer-service"); - -const ADDON_BRANCH = "extensions." + jetpackID + "."; -const BUTTON_PRESSED = jetpackID + "-cmdPressed"; - -// XXX Currently, only Firefox implements the inline preferences. -if (!require("xul-app").is("Firefox")) - throw Error("This API is only supported in Firefox"); - -const branch = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefService). - getBranch(ADDON_BRANCH). - QueryInterface(Ci.nsIPrefBranch2); - -// Listen to changes in the preferences -function preferenceChange(subject, topic, name) { - if (topic === 'nsPref:changed') - emit(target, name, name); -} -branch.addObserver('', preferenceChange, false); - -// Listen to clicks on buttons -function buttonClick(subject, data) { - emit(target, data); -} -observers.add(BUTTON_PRESSED, buttonClick); - -// Make sure we cleanup listeners on unload. -unload(function() { - off(exports); - branch.removeObserver('', preferenceChange, false); - observers.remove(BUTTON_PRESSED, buttonClick); -}); - -const prefs = Proxy.create({ - get: function(receiver, pref) { - return prefService.get(ADDON_BRANCH + pref); - }, - set: function(receiver, pref, val) { - prefService.set(ADDON_BRANCH + pref, val); - }, - delete: function(pref) { - prefService.reset(ADDON_BRANCH + pref); - return true; - }, - has: function(pref) { - return prefService.has(ADDON_BRANCH + pref); - } -}); - -// Event target we will expose as module exports in order to be able to -// emit events on it. -const target = EventTarget.extend({ prefs: prefs }).new(); -module.exports = target; - -// This is workaround making sure that exports is wrapped before it's -// frozen, which needs to happen in order to workaround Bug 673468. -off(target, 'workaround-bug-673468'); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/lib/tabs.js b/tools/addon-sdk-1.7/packages/addon-kit/lib/tabs.js deleted file mode 100644 index ab915f5..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/lib/tabs.js +++ /dev/null @@ -1,28 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; - -if (!require("api-utils/xul-app").is("Firefox")) { - throw new Error([ - "The tabs module currently supports only Firefox. In the future ", - "we would like it to support other applications, however. Please see ", - "https://bugzilla.mozilla.org/show_bug.cgi?id=560716 for more information." - ].join("")); -} - -const { browserWindows } = require("./windows"); -const { tabs } = require("api-utils/windows/tabs"); - -Object.defineProperties(tabs, { - open: { value: function open(options) { - if (options.inNewWindow) - // `tabs` option is under review and may be removed. - return browserWindows.open({ tabs: [ options ] }); - // Open in active window if new window was not required. - return browserWindows.activeWindow.tabs.open(options); - }} -}); -// It's a hack but we will be able to remove it once will implement CommonJS -// feature that would allow us to override exports. -exports.__proto__ = tabs; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/package.json b/tools/addon-sdk-1.7/packages/addon-kit/package.json deleted file mode 100644 index 8cd643f..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "addon-kit", - "description": "Add-on development made easy.", - "keywords": ["javascript", "engine", "platform", "xulrunner", "jetpack-high-level"], - "author": "Atul Varma (http://toolness.com/) <atul@mozilla.com>", - "contributors": [ - "Myk Melez (http://melez.com/) <myk@mozilla.org>", - "Daniel Aquino <mr.danielaquino@gmail.com>" - ], - "license": "MPL 2.0", - "dependencies": ["api-utils"] -} diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/helpers.js b/tools/addon-sdk-1.7/packages/addon-kit/tests/helpers.js deleted file mode 100644 index 399046f..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/helpers.js +++ /dev/null @@ -1,23 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Loader } = require("@loader"); - -exports.Loader = function(module, globals) { - var options = JSON.parse(JSON.stringify(require("@packaging"))); - options.globals = globals; - let loader = Loader.new(options); - return Object.create(loader, { - require: { value: Loader.require.bind(loader, module.path) }, - sandbox: { value: function sandbox(id) { - let path = options.manifest[module.path].requirements[id].path; - return loader.sandboxes[path].sandbox; - }}, - unload: { value: function unload(reason, callback) { - loader.unload(reason, callback); - }} - }) -}; diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-addon-page.js b/tools/addon-sdk-1.7/packages/addon-kit/tests/test-addon-page.js deleted file mode 100644 index c0ee35d..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-addon-page.js +++ /dev/null @@ -1,51 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -'use strict'; - -const { isTabOpen, activateTab, openTab, closeTab } = require('api-utils/tabs/utils'); -const windows = require('api-utils/window-utils'); -const { Loader } = require('./helpers'); -const { setTimeout } = require('api-utils/timer'); - -let uri = require('self').data.url('index.html'); - -function isChromeVisible(window) - window.document.documentElement.getAttribute('disablechrome') !== 'true' - -exports['test that add-on page has no chrome'] = function(assert, done) { - let loader = Loader(module); - loader.require('addon-kit/addon-page'); - - let window = windows.activeBrowserWindow; - let tab = openTab(window, uri); - - assert.ok(isChromeVisible(window), 'chrome is visible for non addon page'); - - // need to do this in another turn to make sure event listener - // that sets property has time to do that. - setTimeout(function() { - activateTab(tab); - - assert.ok(!isChromeVisible(window), 'chrome is not visible for addon page'); - - closeTab(tab); - assert.ok(isChromeVisible(window), 'chrome is visible again'); - loader.unload(); - done(); - }); -}; - -exports['test that add-on pages is closed on unload'] = function(assert) { - let loader = Loader(module); - loader.require('addon-kit/addon-page'); - - let tab = openTab(windows.activeBrowserWindow, uri); - loader.unload(); - - assert.ok(isTabOpen(tab), 'add-on page tabs are closed on unload'); -}; - - -require('test').run(exports); diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-clipboard.js b/tools/addon-sdk-1.7/packages/addon-kit/tests/test-clipboard.js deleted file mode 100644 index 1819d68..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-clipboard.js +++ /dev/null @@ -1,64 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -// Test the typical use case, setting & getting with no flavors specified -exports.testWithNoFlavor = function(test) { - var contents = "hello there"; - var flavor = "text"; - var fullFlavor = "text/unicode"; - var clip = require("clipboard"); - // Confirm we set the clipboard - test.assert(clip.set(contents)); - // Confirm flavor is set - test.assertEqual(clip.currentFlavors[0], flavor); - // Confirm we set the clipboard - test.assertEqual(clip.get(), contents); - // Confirm we can get the clipboard using the flavor - test.assertEqual(clip.get(flavor), contents); - // Confirm we can still get the clipboard using the full flavor - test.assertEqual(clip.get(fullFlavor), contents); -}; - -// Test the slightly less common case where we specify the flavor -exports.testWithFlavor = function(test) { - var contents = "<b>hello there</b>"; - var contentsText = "hello there"; - var flavor = "html"; - var fullFlavor = "text/html"; - var unicodeFlavor = "text"; - var unicodeFullFlavor = "text/unicode"; - var clip = require("clipboard"); - test.assert(clip.set(contents, flavor)); - test.assertEqual(clip.currentFlavors[0], unicodeFlavor); - test.assertEqual(clip.currentFlavors[1], flavor); - test.assertEqual(clip.get(), contentsText); - test.assertEqual(clip.get(flavor), contents); - test.assertEqual(clip.get(fullFlavor), contents); - test.assertEqual(clip.get(unicodeFlavor), contentsText); - test.assertEqual(clip.get(unicodeFullFlavor), contentsText); -}; - -// Test that the typical case still works when we specify the flavor to set -exports.testWithRedundantFlavor = function(test) { - var contents = "<b>hello there</b>"; - var flavor = "text"; - var fullFlavor = "text/unicode"; - var clip = require("clipboard"); - test.assert(clip.set(contents, flavor)); - test.assertEqual(clip.currentFlavors[0], flavor); - test.assertEqual(clip.get(), contents); - test.assertEqual(clip.get(flavor), contents); - test.assertEqual(clip.get(fullFlavor), contents); -}; - -exports.testNotInFlavor = function(test) { - var contents = "hello there"; - var flavor = "html"; - var clip = require("clipboard"); - test.assert(clip.set(contents)); - // If there's nothing on the clipboard with this flavor, should return null - test.assertEqual(clip.get(flavor), null); -}; -// TODO: Test error cases. diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-l10n.js b/tools/addon-sdk-1.7/packages/addon-kit/tests/test-l10n.js deleted file mode 100644 index 259b160..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-l10n.js +++ /dev/null @@ -1,97 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const prefs = require("preferences-service"); -const { Loader } = require('./helpers'); - -const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS"; -const PREF_SELECTED_LOCALE = "general.useragent.locale"; - -function setLocale(locale) { - prefs.set(PREF_MATCH_OS_LOCALE, false); - prefs.set(PREF_SELECTED_LOCALE, locale); -} - -function resetLocale() { - prefs.reset(PREF_MATCH_OS_LOCALE); - prefs.reset(PREF_SELECTED_LOCALE); -} - -exports.testExactMatching = function(test) { - let loader = Loader(module); - setLocale("fr-FR"); - - let _ = loader.require("l10n").get; - test.assertEqual(_("Not translated"), "Not translated", - "Key not translated"); - test.assertEqual(_("Translated"), "Oui", - "Simple key translated"); - - // Placeholders - test.assertEqual(_("placeholderString", "works"), "Placeholder works", - "Value with placeholder"); - test.assertEqual(_("Placeholder %s", "works"), "Placeholder works", - "Key without value but with placeholder"); - test.assertEqual(_("Placeholders %2s %1s %s.", "working", "are", "correctly"), - "Placeholders are working correctly.", - "Multiple placeholders"); - - // Plurals - test.assertEqual(_("downloadsCount", 0), - "0 téléchargement", - "PluralForm form 'one' for 0 in french"); - test.assertEqual(_("downloadsCount", 1), - "1 téléchargement", - "PluralForm form 'one' for 1 in french"); - test.assertEqual(_("downloadsCount", 2), - "2 téléchargements", - "PluralForm form 'other' for n > 1 in french"); - - loader.unload(); - resetLocale(); -} - -exports.testEnUsLocaleName = function(test) { - let loader = Loader(module); - setLocale("en-US"); - - let _ = loader.require("l10n").get; - test.assertEqual(_("Not translated"), "Not translated"); - test.assertEqual(_("Translated"), "Yes"); - - // Check plural forms regular matching - test.assertEqual(_("downloadsCount", 0), - "0 downloads", - "PluralForm form 'other' for 0 in english"); - test.assertEqual(_("downloadsCount", 1), - "one download", - "PluralForm form 'one' for 1 in english"); - test.assertEqual(_("downloadsCount", 2), - "2 downloads", - "PluralForm form 'other' for n != 1 in english"); - - // Check optional plural forms - test.assertEqual(_("pluralTest", 0), - "optional zero form", - "PluralForm form 'zero' can be optionaly specified. (Isn't mandatory in english)"); - test.assertEqual(_("pluralTest", 1), - "fallback to other", - "If the specific plural form is missing, we fallback to 'other'"); - - loader.unload(); - resetLocale(); -} - -exports.testShortLocaleName = function(test) { - let loader = Loader(module); - setLocale("eo"); - - let _ = loader.require("l10n").get; - test.assertEqual(_("Not translated"), "Not translated"); - test.assertEqual(_("Translated"), "jes"); - - loader.unload(); - resetLocale(); -} - diff --git a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-prefs.js b/tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-prefs.js deleted file mode 100644 index 7452a8a..0000000 --- a/tools/addon-sdk-1.7/packages/addon-kit/tests/test-simple-prefs.js +++ /dev/null @@ -1,175 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - - -const { Loader } = require("./helpers"); -const { setTimeout } = require("timers"); -const { notify } = require("observer-service"); -const { jetpackID } = require("@packaging"); - -exports.testSetGetBool = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs").prefs; - - test.assertEqual(sp.test, undefined, "Value should not exist"); - sp.test = true; - test.assert(sp.test, "Value read should be the value previously set"); - - loader.unload(); - test.done(); -}; - -exports.testSetGetInt = function(test) { - test.waitUntilDone(); - - // Load the module once, set a value. - let loader = Loader(module); - let sp = loader.require("simple-prefs").prefs; - - test.assertEqual(sp["test-int"], undefined, "Value should not exist"); - sp["test-int"] = 1; - test.assertEqual(sp["test-int"], 1, "Value read should be the value previously set"); - - loader.unload(); - test.done(); -}; - -exports.testSetComplex = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs").prefs; - - try { - sp["test-complex"] = {test: true}; - test.fail("Complex values are not allowed"); - } - catch (e) { - test.pass("Complex values are not allowed"); - } - - loader.unload(); - test.done(); -}; - -exports.testSetGetString = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs").prefs; - - test.assertEqual(sp["test-string"], undefined, "Value should not exist"); - sp["test-string"] = "test"; - test.assertEqual(sp["test-string"], "test", "Value read should be the value previously set"); - - loader.unload(); - test.done(); -}; - -exports.testHasAndRemove = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs").prefs; - - sp.test = true; - test.assert(("test" in sp), "Value exists"); - delete sp.test; - test.assertEqual(sp.test, undefined, "Value should be undefined"); - - loader.unload(); - test.done(); - -}; - -exports.testPrefListener = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs"); - - let listener = function(prefName) { - test.assertEqual(prefName, "test-listen", "The prefs listener heard the right event"); - test.done(); - }; - - sp.on("test-listen", listener); - - sp.prefs["test-listen"] = true; - loader.unload(); -}; - -exports.testBtnListener = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs"); - - sp.on("test-btn-listen", function() { - test.pass("Button press event was heard"); - test.done(); - }); - notify((jetpackID + "-cmdPressed"), "", "test-btn-listen"); - - loader.unload(); -}; - -exports.testPrefRemoveListener = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs"); - let counter = 0; - - let listener = function() { - test.pass("The prefs listener was not removed yet"); - - if (++counter > 1) - test.fail("The prefs listener was not removed"); - - sp.removeListener("test-listen2", listener); - - sp.prefs["test-listen2"] = false; - - setTimeout(function() { - test.pass("The prefs listener was removed"); - loader.unload(); - test.done(); - }, 250); - }; - - sp.on("test-listen2", listener); - - // emit change - sp.prefs["test-listen2"] = true; -}; - -// Bug 710117: Test that simple-pref listeners are removed on unload -exports.testPrefUnloadListener = function(test) { - test.waitUntilDone(); - - let loader = Loader(module); - let sp = loader.require("simple-prefs"); - let counter = 0; - - let listener = function() { - test.assertEqual(++counter, 1, "This listener should only be called once"); - - loader.unload(); - - // this may not execute after unload, but definitely shouldn't fire listener - sp.prefs["test-listen3"] = false; - // this should execute, but also definitely shouldn't fire listener - require("simple-prefs").prefs["test-listen3"] = false; // - - test.done(); - }; - - sp.on("test-listen3", listener); - - // emit change - sp.prefs["test-listen3"] = true; -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/README.md b/tools/addon-sdk-1.7/packages/api-utils/README.md deleted file mode 100644 index 55adb57..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/README.md +++ /dev/null @@ -1,35 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -API Utils provides a basic CommonJS infrastructure for -developing traditional XULRunner add-ons and applications. It is -the basis for the Add-on SDK. - -To address issues present in traditional add-on development, -API Utils provides mechanisms for: - -* writing and executing test cases, inspired by Python's [nose][] - package, -* tracking JS objects of interest to aid in memory profiling and leak - detection, -* registering callbacks that perform cleanup tasks when modules are - unloaded, -* easily reporting errors with full stack tracebacks. - -API Utils also has the following characteristics: - -* Beautiful, concise documentation. -* A rigorous test suite ensuring that the library doesn't break as the - Mozilla platform evolves. -* Solid developer ergonomics ensuring that developers can easily find - out why something they're doing isn't working. - -API Utils is intended to be very small and only contain the bare -minimum of functionality that all add-ons need. - -Note that the API Utils package has not fully stabilized yet, meaning that -we do still expect to make incompatible changes to its APIs in future releases -of the SDK. - - [nose]: http://code.google.com/p/python-nose/ diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md deleted file mode 100644 index aee88da..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md +++ /dev/null @@ -1,157 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `api-utils` module provides some helpers useful to the SDK's high-level API -implementations. - -Introduction ------------- - -The SDK high-level API design guidelines make a number of recommendations. -This module implements some of those patterns so that your own implementations -don't need to reinvent them. - -For example, public constructors should be callable both with and without the -`new` keyword. Your module can implement this recommendation using the -`publicConstructor` function. - -Options objects or "dictionaries" are also common throughout the high-level -APIs. The guidelines recommend that public constructors should generally define -a single `options` parameter rather than defining many parameters. Since one of -the SDK's principles is to be friendly to developers, ideally all properties on -options dictionaries should be checked for correct type, and informative error -messages should be generated when clients make mistakes. With the -`validateOptions` function, your module can easily do so. - -And objects are sometimes iterable over a custom set of key/value pairs. -Such objects should have custom iterators that let consumers iterate keys, -values, or [key, value] pairs. The `addIterator` function makes it easy to do -so in a way that is consistent with the behavior of default iterators during -`for...in`, `for each...in`, and `for...in Iterator()` loops. - -<api name="publicConstructor"> -@function -Returns a function *C* that creates an instance of `privateConstructor`. *C* -may be called with or without the `new` keyword. - -The prototype of each instance returned from *C* is *C*.`prototype`, and -*C*.`prototype` is an object whose prototype is -`privateConstructor.prototype`. Instances returned from *C* are therefore -instances of both *C* and `privateConstructor`. - -Additionally, the constructor of each instance returned from *C* is *C*. - -Instances returned from *C* are automatically memory tracked using -`memory.track` under the bin name `privateConstructor.name`. - -**Example** - - function MyObject() {} - exports.MyObject = apiUtils.publicConstructor(MyObject); - -@returns {function} -A function that makes new instances of `privateConstructor`. - -@param privateConstructor {constructor} -</api> - -<api name="validateOptions"> -@function -A function to validate an options dictionary according to the specified -constraints. - -`map`, `is`, and `ok` are used in that order. - -The return value is an object whose keys are those keys in `requirements` that -are also in `options` and whose values are the corresponding return values of -`map` or the corresponding values in `options`. Note that any keys not shared -by both `requirements` and `options` are not in the returned object. - -**Examples** - -A typical use: - - var opts = { foo: 1337 }; - var requirements = { - foo: { - map: function (val) val.toString(), - is: ["string"], - ok: function (val) val.length > 0, - msg: "foo must be a non-empty string." - } - }; - var validatedOpts = apiUtils.validateOptions(opts, requirements); - // validatedOpts == { foo: "1337" } - -If the key `foo` is optional and doesn't need to be mapped: - - var opts = { foo: 1337 }; - var validatedOpts = apiUtils.validateOptions(opts, { foo: {} }); - // validatedOpts == { foo: 1337 } - - opts = {}; - validatedOpts = apiUtils.validateOptions(opts, { foo: {} }); - // validatedOpts == {} - -@returns {object} -A validated options dictionary given some requirements. If any of the -requirements are not met, an exception is thrown. - -@param options {object} -The options dictionary to validate. It's not modified. If it's null or -otherwise falsey, an empty object is assumed. - -@param requirements {object} -An object whose keys are the expected keys in `options`. Any key in -`options` that is not present in `requirements` is ignored. Each -value in `requirements` is itself an object describing the requirements -of its key. The keys of that object are the following, and each is optional: - -@prop [map] {function} -A function that's passed the value of the key in the `options`. `map`'s -return value is taken as the key's value in the final validated options, -`is`, and `ok`. If `map` throws an exception it is caught and discarded, -and the key's value is its value in `options`. - -@prop [is] {array} -An array containing the number of `typeof` type names. If the key's value is -none of these types it fails validation. Arrays and nulls are identified by -the special type names "array" and "null"; "object" will not match either. -No type coercion is done. - -@prop [ok] {function} -A function that is passed the key's value. If it returns false, the value -fails validation. - -@prop [msg] {string} -If the key's value fails validation, an exception is thrown. This string -will be used as its message. If undefined, a generic message is used, unless -`is` is defined, in which case the message will state that the value needs to -be one of the given types. -</api> - -<api name="addIterator"> -@function -Adds an iterator to the specified object that iterates keys, values, -or [key, value] pairs depending on how it is invoked, i.e.: - - for (var key in obj) { ... } // iterate keys - for each (var val in obj) { ... } // iterate values - for (var [key, val] in Iterator(obj)) { ... } // iterate pairs - -If your object only iterates either keys or values, you don't need this -function. Simply assign a generator function that iterates the keys/values -to your object's `__iterator__` property instead, f.e.: - - obj.__iterator__ = function () { for each (var i in items) yield i; } - -@param obj {object} -the object to which to add the iterator - -@param keysValsGen {function} -a generator function that yields [key, value] pairs -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md b/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md deleted file mode 100644 index c40ddaf..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md +++ /dev/null @@ -1,65 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `app-strings` module gives you access to the host application's localized -string bundles (`.properties` files). - -The module exports the `StringBundle` constructor function. To access a string -bundle, construct an instance of `StringBundle`, passing it the bundle's URL: - - var StringBundle = require("app-strings").StringBundle; - var bundle = StringBundle("chrome://browser/locale/browser.properties"); - -To get the value of a string, call the object's `get` method, passing it -the name of the string: - - var accessKey = bundle.get("contextMenuSearchText.accesskey"); - // "S" in the en-US locale - -To get the formatted value of a string that accepts arguments, call the object's -`get` method, passing it the name of the string and an array of arguments -with which to format the string: - - var searchText = bundle.get("contextMenuSearchText", - ["universe", "signs of intelligent life"]); - // 'Search universe for "signs of intelligent life"' in the en-US locale - -To get all strings in the bundle, iterate the object, which returns arrays -of the form [name, value]: - - for (var [name, value] in Iterator(bundle)) - console.log(name + " = " + value); - -Iteration ---------- - -<code>for (var name in bundle) { ... }</code> - -Iterate the names of strings in the bundle. - -<code>for each (var val in bundle) { ... }</code> - -Iterate the values of strings in the bundle. - -<code>for (var [name, value] in Iterator(bundle)) { ... }</code> - -Iterate the names and values of strings in the bundle. - - -<api name="StringBundle"> -@class -The `StringBundle` object represents a string bundle. -<api name="StringBundle"> -@constructor -Creates a StringBundle object that gives you access to a string bundle. -@param url {string} the URL of the string bundle -@returns {StringBundle} the string bundle -</api> -<api name="get"> -@method Get the value of the string with the given name. -@param [name] {string} the name of the string to get -@param [args] {array} (optional) strings that replace placeholders in the string -@returns {string} the value of the string -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/base.md b/tools/addon-sdk-1.7/packages/api-utils/docs/base.md deleted file mode 100644 index 7a694f2..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/base.md +++ /dev/null @@ -1,207 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -### Inheritance ### - -Doing [inheritance in JavaScript](https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript) -is both verbose and painful. Reading or writing such code requires requires -sharp eye and lot's of discipline, mainly due to code fragmentation and lots of -machinery exposed: - - // Defining a simple Class - function Dog(name) { - // Classes are for creating instances, calling them without `new` changes - // behavior, which in majority cases you need to handle, so you end up - // with additional boilerplate. - if (!(this instanceof Dog)) return new Dog(name); - - this.name = name; - }; - // To define methods you need to make a dance with a special 'prototype' - // property of the constructor function. This is too much machinery exposed. - Dog.prototype.type = 'dog'; - Dog.prototype.bark = function bark() { - return 'Ruff! Ruff!' - }; - - // Subclassing a `Dog` - function Pet(name, breed) { - // Once again we do our little dance - if (!(this instanceof Pet)) return new Pet(name, breed); - - Dog.call(this, name); - this.breed = breed; - } - // To subclass, you need to make another special dance with special - // 'prototype' properties. - Pet.prototype = Object.create(Dog.prototype); - // If you want correct instanceof behavior you need to make a dance with - // another special `constructor` property of the `prototype` object. - Object.defineProperty(Pet.prototype, 'contsructor', { value: Pet }); - // Finally you can define some properties. - Pet.prototype.call = function(name) { - return this.name === name ? this.bark() : ''; - }; - -An "exemplar" is a factory for instances. Usually exemplars are defined as -(constructor) functions as in examples above. But that does not necessary has -to be the case. Prototype (object) can form far more simpler exemplars. After -all what could be more object oriented than objects that inherit from objects. - - var Dog = { - new: function(name) { - var instance = Object.create(this); - this.initialize.apply(instance, arguments); - return instance; - }, - initialize: function initialize(name) { - this.name = name; - }, - type: 'dog', - bark: function bark() { - return 'Ruff! Ruff!' - } - }; - var fluffy = Dog.new('fluffy'); - - - var Pet = Object.create(Dog); - Pet.initialize = function initialize(name, breed) { - Dog.initialize.call(this, name); - this.breed = breed; - }; - Pet.call = function call(name) { - return this.name === name ? this.bark() : ''; - }; - -While this small trick solves some readability issues, there are still more. To -address them this module exports `Base` exemplar with few methods predefined: - - var Dog = Base.extend({ - initialize: function initialize(name) { - this.name = name; - }, - type: 'dog', - bark: function bark() { - return 'Ruff! Ruff!' - } - }); - - var Pet = Dog.extend({ - initialize: function initialize(name, breed) { - Dog.initialize.call(this, name); - this.breed = breed; - }, - function call(name) { - return this.name === name ? this.bark() : ''; - } - }); - - var fluffy = Dog.new('fluffy'); - dog.bark(); // 'Ruff! Ruff!' - Dog.isPrototypeOf(fluffy); // true - Pet.isPrototypeOf(fluffy); // true - -### Composition ### - -Even though (single) inheritance is very powerful it's not always enough. -Sometimes it's more useful suitable to define reusable pieces of functionality -and then compose bigger pieces out of them: - - var HEX = Base.extend({ - hex: function hex() { - return '#' + this.color - } - }) - - var RGB = Base.extend({ - red: function red() { - return parseInt(this.color.substr(0, 2), 16) - }, - green: function green() { - return parseInt(this.color.substr(2, 2), 16) - }, - blue: function blue() { - return parseInt(this.color.substr(4, 2), 16) - } - }) - - var CMYK = Base.extend(RGB, { - black: function black() { - var color = Math.max(Math.max(this.red(), this.green()), this.blue()) - return (1 - color / 255).toFixed(4) - }, - magenta: function magenta() { - var K = this.black(); - return (((1 - this.green() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) - }, - yellow: function yellow() { - var K = this.black(); - return (((1 - this.blue() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) - }, - cyan: function cyan() { - var K = this.black(); - return (((1 - this.red() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) - } - }) - - // Composing `Color` prototype out of reusable components: - var Color = Base.extend(HEX, RGB, CMYK, { - initialize: function initialize(color) { - this.color = color - } - }) - - var pink = Color.new('FFC0CB') - // RGB - pink.red() // 255 - pink.green() // 192 - pink.blue() // 203 - - // CMYK - pink.magenta() // 0.2471 - pink.yellow() // 0.2039 - pink.cyan() // 0.0000 - -### Combining composition & inheritance ### - -Also it's easy to mix composition with inheritance: - - var Pixel = Color.extend({ - initialize: function initialize(x, y, color) { - Color.initialize.call(this, color) - this.x = x - this.y = y - }, - toString: function toString() { - return this.x + ':' + this.y + '@' + this.hex() - } - }); - - var pixel = Pixel.new(11, 23, 'CC3399'); - pixel.toString() // 11:23@#CC3399 - Pixel.isPrototypeOf(pixel) // true - - // Pixel instances inhertis from `Color` - Color.isPrototypeOf(pixel); // true - - // In fact `Pixel` itself inherits from `Color`, remember just simple and - // pure prototypal inheritance where object inherit from objects. - Color.isPrototypeOf(Pixel); // true - -### Classes ### - -Module exports `Class` function. `Class` takes argument of exemplar object -extending `Base` and returns `constructor` function that can be used for -simulating classes defined by given exemplar. - - var CPixel = Class(Pixel); - var pixel = CPixel(11, 12, '000000'); - pixel instanceof CPixel // true - Pixel.prototypeOf(pixel); // true - - // Use of `new` is optional, but possible. - var p2 = CPixel(17, 2, 'cccccc'); - p2 instanceof CPixel // true - p2.prototypeOf(pixel); // true diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md b/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md deleted file mode 100644 index 1238cd8..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md +++ /dev/null @@ -1,68 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `byte-streams` module provides streams for reading and writing bytes. - -<api name="ByteReader"> -@class -<api name="ByteReader"> -@constructor - Creates a binary input stream that reads bytes from a backing stream. -@param inputStream {stream} - The backing stream, an <a href="http://mxr.mozilla.org/mozilla-central/ -source/xpcom/io/nsIInputStream.idl"><code>nsIInputStream</code></a>. -</api> -<api name="closed"> -@property {boolean} - True if the stream is closed. -</api> - -<api name="close"> -@method - Closes both the stream and its backing stream. If the stream is already - closed, an exception is thrown. -</api> - -<api name="read"> -@method - Reads a string from the stream. If the stream is closed, an exception is - thrown. -@param [numBytes] {number} - The number of bytes to read. If not given, the remainder of the entire stream - is read. -@returns {string} - A string containing the bytes read. If the stream is at the end, returns the - empty string. -</api> -</api> - -<api name="ByteWriter"> -@class -<api name="ByteWriter"> -@constructor - Creates a binary output stream that writes bytes to a backing stream. -@param outputStream {stream} - The backing stream, an <a href="http://mxr.mozilla.org/mozilla-central/ -source/xpcom/io/nsIOutputStream.idl"><code>nsIOutputStream</code></a>. -</api> -<api name="closed"> -@property {boolean} - True if the stream is closed. -</api> -<api name="close"> -@method - Closes both the stream and its backing stream. If the stream is already - closed, an exception is thrown. -</api> -<api name="write"> -@method - Writes a string to the stream. If the stream is closed, an exception is - thrown. -@param str {string} - The string to write. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md b/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md deleted file mode 100644 index 1e557c6..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md +++ /dev/null @@ -1,77 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `collection` module provides a simple list-like class and utilities for -using it. A collection is ordered, like an array, but its items are unique, -like a set. - -<api name="Collection"> -@class -A collection object provides for...in-loop iteration. Items are yielded in the -order they were added. For example, the following code... - - var collection = require("collection"); - var c = new collection.Collection(); - c.add(1); - c.add(2); - c.add(3); - for (item in c) - console.log(item); - -... would print this to the console: - -<pre> - 1 - 2 - 3 -</pre> - -Iteration proceeds over a copy of the collection made before iteration begins, -so it is safe to mutate the collection during iteration; doing so does not -affect the results of the iteration. - -<api name="Collection"> -@constructor -Creates a new collection. The collection is backed by an array. -@param [array] {array} -If *array* is given, it will be used as the backing array. This way the caller -can fully control the collection. Otherwise a new empty array will be used, and -no one but the collection will have access to it. -</api> -<api name="length"> -@property {number} -The number of items in the collection array. -</api> -<api name="add"> -@method -Adds a single item or an array of items to the collection. Any items already -contained in the collection are ignored. -@param itemOrItems {object} An item or array of items. -@returns {Collection} The Collection. -</api> -<api name="remove"> -@method -Removes a single item or an array of items from the collection. Any items not -contained in the collection are ignored. -@param itemOrItems {object} An item or array of items. -@returns {Collection} The Collection. -</api> -</api> - -<api name="addCollectionProperty"> -@function -Adds a collection property to the given object. Setting the property to a -scalar value empties the collection and adds the value. Setting it to an array -empties the collection and adds all the items in the array. -@param object {object} -The property will be defined on this object. -@param propName {string} -The name of the property. -@param [backingArray] {array} -If given, this will be used as the collection's backing array. -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content.md deleted file mode 100644 index 1c25eb4..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/content.md +++ /dev/null @@ -1,15 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -The `content` module exports three different traits [Loader][], [Worker][] and -[Symbiont][]. None of this traits is intended to be used directly by programs. -Rather, they are intended to be used by other modules that provide high -level APIs to programs or libraries. - -[Loader]:packages/api-utils/content/loader.html -[Worker]:packages/api-utils/content/worker.html -[Symbiont]:packages/api-utils/content/symbiont.html - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md deleted file mode 100644 index a460476..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md +++ /dev/null @@ -1,92 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -Loader is base trait and it provides set of core properties and associated -validations. Trait is useful for all the compositions providing high level -APIs for creating JavaScript contexts that can access web content. - -Loader is composed from the -[EventEmitter](packages/api-utils/events.html) trait, therefore -instances of Loader and their descendants expose all the public properties -exposed by EventEmitter along with additional public properties: - -Value changes on all of the above mentioned properties emit `propertyChange` -events on an instances. - -**Example:** - -The following code creates a wrapper on hidden frame that reloads a web page -in frame every time `contentURL` property is changed: - - var hiddenFrames = require("hidden-frame"); - var { Loader } = require("content"); - var PageLoader = Loader.compose({ - constructor: function PageLoader(options) { - options = options || {}; - if (options.contentURL) - this.contentURL = options.contentURL; - this.on('propertyChange', this._onChange = this._onChange.bind(this)); - let self = this; - hiddenFrames.add(hiddenFrames.HiddenFrame({ - onReady: function onReady() { - let frame = self._frame = this.element; - self._emit('propertyChange', { contentURL: self.contentURL }); - } - })); - }, - _onChange: function _onChange(e) { - if ('contentURL' in e) - this._frame.setAttribute('src', this._contentURL); - } - }); - -<api name="Loader"> -@class -<api name="contentScriptFile"> -@property {array} -The local file URLs of content scripts to load. Content scripts specified by -this property are loaded *before* those specified by the `contentScript` -property. -</api> - -<api name="contentScript"> -@property {array} -The texts of content scripts to load. Content scripts specified by this -property are loaded *after* those specified by the `contentScriptFile` property. -</api> - -<api name="contentScriptWhen"> -@property {string} -When to load the content scripts. This may take one of the following -values: - -* "start": load content scripts immediately after the document -element for the page is inserted into the DOM, but before the DOM content -itself has been loaded -* "ready": load content scripts once DOM content has been loaded, -corresponding to the -[DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) -event -* "end": load content scripts once all the content (DOM, JS, CSS, -images) for the page has been loaded, at the time the -[window.onload event](https://developer.mozilla.org/en/DOM/window.onload) -fires - -</api> - -<api name="contentURL"> -@property {string} -The URL of the content loaded. -</api> - -<api name="allow"> -@property {object} -Permissions for the content, with the following keys: -@prop script {boolean} - Whether or not to execute script in the content. Defaults to true. -</api> -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md deleted file mode 100644 index 095e8ff..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md +++ /dev/null @@ -1,241 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Alexandre Poirot [apoirot@mozilla.com] --> - -Content scripts need access to the DOM of the pages they are attached to. -However, those pages should be considered to be hostile environments: we -have no control over any other scripts loaded by the web page that may be -executing in the same context. If the content scripts and scripts loaded -by the web page were to access the same DOM objects, there are two possible -security problems: - -First, a malicious page might redefine functions and properties of DOM -objects so they don't do what the add-on expects. For example, if a -content script calls `document.getElementById()` to retrieve a DOM -element, then a malicious page could redefine its behavior to return -something unexpected: - -<pre><code> -// If the web document contains the following script: -document.getElementById = function (str) { - // Overload indexOf method of all string instances - str.__proto__.indexOf = function () {return -1;}; - // Overload toString method of all object instances - str.__proto__.__proto__.toString = function () {return "evil";}; -}; -// After the following line, the content script will be compromised: -var node = document.getElementById("element"); -// Then your content script is totally out of control. -</code></pre> - -Second, changes the content script made to the DOM objects would be visible -to the page, leaking information to it. - -The general approach to fixing these problems is to wrap DOM objects in -[`XrayWrappers`](https://developer.mozilla.org/en/XPCNativeWrapper) -(also know as `XPCNativeWrapper`). This guarantees that: - -* when the content script accesses DOM properties and functions it gets the -original native version of them, ignoring any modifications made by the web -page -* changes to the DOM made by the content script are not visible to scripts -running in the page. - -However, `XrayWrapper` has some limitations and bugs, which break many -popular web frameworks. In particular, you can't: - -* define attributes like `onclick`: you have to use `addEventListener` syntax -* overload native methods on DOM objects, like this: -<pre><code> -proxy.addEventListener = function () {}; -</code></pre> -* access named elements using properties like `window[framename]` or -`document[formname]` -* use some other features that have bugs in the `XrayWrapper` -implementation, like `mozMatchesSelector` - -The `proxy` module uses `XrayWrapper` in combination with the -experimental -[Proxy API](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy) -to address both the security vulnerabilities of content scripts and the -limitations of `XrayWrapper`. - -<pre> - /--------------------\ /------------------------\ - | Web document | | Content script sandbox | - | http://mozilla.org | | data/worker.js | - | | require('content-proxy'). | | - | window >-----------|- create(window) -|-> window | - \--------------------/ \------------------------/ -</pre> - - -## The Big Picture ## - -The implementation defines two different kinds of proxy: - - 1. Content script proxies that wrap DOM objects that are exposed to - content scripts as described above. - 2. XrayWrapper proxies that wrap objects from content scripts before handing - them over to XrayWrapper functions. These proxies are internal - and are not exposed to content scripts or document content. - -<pre> - /--------------------\ /------------------------\ - | Web document | | Content script sandbox | - | http://mozilla.org | | data/worker.js | - | | /-------|-> myObject = {} | - | | /----------------v--\ | | - | | | XrayWrapper Proxy | | - document | - | | \---------v---------/ \----^-------------------/ - | | v | - | | /-------------\ /----------\ | - | - document >-------|->| XrayWrapper |<-| CS proxy |-/ - \--------------------/ \-------------/ \----------/ -</pre> - -Everything begins with a single call to the `create` function exported by the -content-proxy module: - - // Retrieve the unwrapped reference to the current web page window object - var win = gBrowser.contentDocument.defaultView.wrappedJSObject; - // Or in addon sdk style - var win = require("tab-browser").activeTab.linkedBrowser.contentWindow.wrappedJSObject; - // Now create a content script proxy for the window object - var windowProxy = require("api-utils/content/content-proxy").create(win); - - // We finally use this window object as sandbox prototype, - // so that all web page globals are accessible in CS too: - var contentScriptSandbox = new Cu.Sandbox(win, { - sandboxPrototype: windowProxy - }); - -Then all other proxies are created from this one. Attempts to access DOM -attributes of this proxy are trapped, and the proxy constructs and returns -content script proxies for those attributes: - - // For example, if you simply do this: - var document = window.document; - // accessing the `document` attribute will be trapped by the `window` content script - // proxy, and that proxy will that create another content script proxy for `document` - -So the main responsibility of the content script proxy implementation is to -ensure that we always return content script proxies to the content script. - -## Internal Implementation ## - -Each content script proxy keeps a reference to the `XrayWrapper` that enables -it to be sure of calling native DOM methods. - -There are two internal functions to convert between content script proxy -values and `XrayWrapper` values. - -1. __`wrap`__ takes an XrayWrapper value and wraps it in a content script -proxy if needed. - This method is called when: - * a content script accesses an attribute of a content script proxy. - * XrayWrapper code calls a callback function defined in the content -script, so that arguments passed into the function by the XrayWrapper are -converted into content script proxies. For example, if a content script -calls `addEventListener`, then the listener function will expect any arguments -to be content script proxies. -<br/><br/> -2. __`unwrap`__ takes an object coming from the content script context and: - * if the object is a content script proxy, unwraps it back to an -XrayWrapper reference - * if the object is not a content script proxy, wraps it in an XrayWrapper -proxy. -<br/><br/> -This means we can call a XrayWrapper method either with: - - * a raw XrayWrapper object. - - // The following line doesn't work if child is a content script proxy, - // it has to be a raw XrayWrapper reference - xrayWrapper.appendChild(child) - - * an XrayWrapper proxy when you pass a custom object from the content -script context. - - var myListener = { - handleEvent: function(event) { - // `event` should be a content script proxy - } - }; - // `myListener` has to be another kind of Proxy: XrayWrapper proxy, - // that aims to catch the call to `handleEvent` in order to wrap its - // arguments in a content script proxy. - xrayWrapper.addEventListener("click", myListener, false); - - -## Stack Traces ## - -The following code: - - function listener(event) { - - } - csProxy.addEventListener("message", listener, false); - -generates the following internal calls: - - -> CS Proxy:: get("addEventListener") - -> wrap(xrayWrapper.addEventListener) - -> NativeFunctionWrapper(xrayWrapper.addEventListener) - // NativeFunctionWrapper generates: - function ("message", listener, false) { - return xraywrapper.addEventListener("message", unwrap(listener), false); - } - -> unwrap(listener) - -> ContentScriptFunctionWrapper(listener) - // ContentScriptFunctionWrapper generates: - function (event) { - return listener(wrap(event)); - } - -<br> - - // First, create an object from content script context - var myListener = { - handleEvent: function (event) { - - } - }; - // Then, pass this object as an argument to a CS proxy method - window.addEventListener("message", myListener, false); - - // Generates the following internal calls: - -> CS Proxy:: get("addEventListener") - -> wrap(xrayWrapper.addEventListener) - -> NativeFunctionWrapper(xrayWrapper.addEventListener) - // Generate the following function: - function ("message", myListener, false) { - return xraywrapper.addEventListener("message", unwrap(myListener), false); - } - -> unwrap(myListener) - -> ContentScriptObjectWrapper(myListener) - // Generate an XrayWrapper proxy and give it to xrayWrapper method. - // Then when native code fires an event, the proxy will catch it: - -> XrayWrapper Proxy:: get("handleEvent") - -> unwrap(myListener.handleEvent) - -> ContentScriptFunctionWrapper(myListener.handleEvent) - // Generate following function: - function (event) { - return myListener.handleEvent(wrap(event)); - } - - -<api name="create"> -@function - Create a content script proxy. <br/> - Doesn't create a proxy if we are not able to create a XrayWrapper for - this object: for example, if the object comes from system principal. - -@param object {Object} - The object to proxify. - -@returns {Object} - A content script proxy that wraps `object`. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md deleted file mode 100644 index 1ff7dd1..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md +++ /dev/null @@ -1,140 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Myk Melez [myk@mozilla.org] --> -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - - -This module is not intended to be used directly by programs. Rather, it is -intended to be used by other modules that provide APIs to programs. - - -This module exports `Symbiont` trait that can be used for creating JavaScript -contexts that can access web content in host application frames (i.e. XUL -`<iframe>` and `<browser>` elements) and communicate with programs via -asynchronous JSON pipes. It is useful in the construction of APIs that -are compatible with the execution model codenamed "electrolysis" in which -programs run in separate processes from web content. - -Introduction ------------- - -`Symbiont` constructs a content symbiont for a given frame, it loads the -specified contentURL and scripts into it, and plumbs an asynchronous -JSON pipe between the content symbiont object and the content symbiont -context. If frame is not provided hidden frame will be created. - -Examples --------- - - var { Symbiont } = require('content'); - var Thing = Symbiont.resolve({ constructor: '_init' }).compose({ - constructor: function Thing(options) { - // `getMyFrame` returns the host application frame in which - // the page is loaded. - this._frame = getMyFrame(); - this._init(options) - } - }); - -See the [panel][] module for a real-world example of usage of this module. - -[panel]:packages/addon-kit/panel.html - -Reference ---------- - -<api name="Symbiont"> -@class -Symbiont is composed from the [Worker][] trait, therefore instances -of Symbiont and their descendants expose all the public properties -exposed by [Worker][] along with additional public properties that -are listed below: - -[Worker]:packages/api-utils/content/worker.html - -<api name="Symbiont"> -@constructor -Creates a content symbiont. -@param options {object} - Options for the constructor. Includes all the keys that -the [Worker](packages/api-utils/content/worker.html) -constructor accepts and a few more: - - @prop [frame] {object} - The host application frame in which the page is loaded. - If frame is not provided hidden one will be created. - @prop [contentScriptWhen="end"] {string} - When to load the content scripts. This may take one of the following - values: - - * "start": load content scripts immediately after the document - element for the page is inserted into the DOM, but before the DOM content - itself has been loaded - * "ready": load content scripts once DOM content has been loaded, - corresponding to the - [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) - event - * "end": load content scripts once all the content (DOM, JS, CSS, - images) for the page has been loaded, at the time the - [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) - fires - - This property is optional and defaults to "end". - - @prop [allow] {object} - Permissions for the content, with the following keys: - @prop [script] {boolean} - Whether or not to execute script in the content. Defaults to true. - Optional. - Optional. -</api> - -<api name="contentScriptFile"> -@property {array} -The local file URLs of content scripts to load. Content scripts specified by -this property are loaded *before* those specified by the `contentScript` -property. -</api> - -<api name="contentScript"> -@property {array} -The texts of content scripts to load. Content scripts specified by this -property are loaded *after* those specified by the `contentScriptFile` property. -</api> - -<api name="contentScriptWhen"> -@property {string} -When to load the content scripts. This may have one of the following -values: - -* "start": load content scripts immediately after the document -element for the page is inserted into the DOM, but before the DOM content -itself has been loaded -* "ready": load content scripts once DOM content has been loaded, -corresponding to the -[DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) -event -* "end": load content scripts once all the content (DOM, JS, CSS, -images) for the page has been loaded, at the time the -[window.onload event](https://developer.mozilla.org/en/DOM/window.onload) -fires - -</api> - -<api name="contentURL"> -@property {string} -The URL of the content loaded. -</api> - -<api name="allow"> -@property {object} -Permissions for the content, with a single boolean key called `script` which -defaults to true and indicates whether or not to execute scripts in the -content. -</api> - -</api> - - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md deleted file mode 100644 index b3e17ea..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md +++ /dev/null @@ -1,130 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -This module exports the `Worker` trait, which may be used to construct objects -implementing the [Worker][] interface defined by the W3C, with minor -differences. - -Content workers are message-passing facilities for communication between -[content scripts](dev-guide/guides/content-scripts/index.html) and the main -add-on code. - -It is important to note that unlike "web workers," these workers run in the -same process as web content and browser chrome, so code within workers can -block the UI. - -[Worker]:http://www.w3.org/TR/workers/#worker - -<api name="Worker"> -@class -Worker is composed from the [EventEmitter][] trait, therefore instances -of Worker and their descendants expose all the public properties -exposed by [EventEmitter][] along with additional public properties that -are listed below. - -**Example** - - var workers = require("content/worker"); - let worker = workers.Worker({ - window: require("window-utils").activeWindow, - contentScript: - "self.port.on('hello', function(name) { " + - " self.port.emit('response', window.location); " + - "});" - }); - worker.port.emit("hello", { name: "worker"}); - worker.port.on("response", function (location) { - console.log(location); - }); - -[EventEmitter]:packages/api-utils/events.html - -<api name="Worker"> -@constructor -Creates a content worker. -@param options {object} -Options for the constructor, with the following keys: - @prop window {object} - The content window to create JavaScript sandbox for communication with. - @prop [contentScriptFile] {string,array} - The local file URLs of content scripts to load. Content scripts specified - by this option are loaded *before* those specified by the `contentScript` - option. Optional. - @prop [contentScript] {string,array} - The texts of content scripts to load. Content scripts specified by this - option are loaded *after* those specified by the `contentScriptFile` option. - Optional. - @prop [onMessage] {function} - Functions that will registered as a listener to a 'message' events. - @prop [onError] {function} - Functions that will registered as a listener to an 'error' events. -</api> - -<api name="port"> -@property {EventEmitter} -[EventEmitter](packages/api-utils/events.html) object that allows you to: - -* send customized messages to the worker using the `port.emit` function -* receive events from the worker using the `port.on` function - -</api> - -<api name="postMessage"> -@method -Asynchronously emits `"message"` events in the enclosed worker, where content -script was loaded. -@param data {number,string,JSON} -The data to send. Must be stringifiable to JSON. -</api> - -<api name="destroy"> -@method -Destroy the worker by removing the content script from the page and removing -all registered listeners. A `detach` event is fired just before removal. -</api> - -<api name="url"> -@property {string} -The URL of the content. -</api> - -<api name="tab"> -@property {object} -If this worker is attached to a content document, returns the related -[tab](packages/addon-kit/tabs.html). -</api> - -<api name="message"> -@event -This event allows the content worker to receive messages from its associated -content scripts. Calling the `self.postMessage()` function from a content -script will asynchronously emit the `message` event on the corresponding -worker. - -@argument {value} -The event listener is passed the message, which must be a -<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. -</api> - -<api name="error"> -@event -This event allows the content worker to react to an uncaught runtime script -error that occurs in one of the content scripts. - -@argument {Error} -The event listener is passed a single argument which is an -[Error](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error) -object. -</api> - -<api name="detach"> -@event -This event is emitted when the document associated with this worker is unloaded -or the worker's `destroy()` method is called. -</api> - -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md b/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md deleted file mode 100644 index afae8cb..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md +++ /dev/null @@ -1,160 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - - -## Property Encapsulation ## - -In JavaScript it is not possible to create properties that have limited or -controlled accessibility. It is possible to create non-enumerable and -non-writable properties, but still they can be discovered and accessed. -Usually so called "closure capturing" is used to encapsulate such properties -in lexical scope: - - function Foo() { - var _secret = 'secret'; - this.hello = function hello() { - return 'Hello ' + _secret; - } - } - -This provides desired result, but has side effect of degrading code readability, -especially with object-oriented programs. Another disadvantage with this pattern -is that there is no immediate solution for inheriting access to the privates -(illustrated by the following example): - - function Derived() { - this.hello = function hello() { - return _secret; - } - this.bye = function bye() { - return _secret; - } - } - Derived.prototype = Object.create(Foo.prototype); - -## Facade Objects ## - -Alternatively constructor can returned facade objects - proxies to the -instance's public properties: - - function Foo() { - var foo = Object.create(Foo.prototype); - return { - bar: foo.hello.bind(foo); - } - } - Foo.prototype._secret = 'secret'; - Foo.prototype.hello = function hello() { - return 'Hello ' + this._secret; - } - - function Derived() { - var derived = Object.create(Derived.prototype); - return { - bar: derived.hello.bind(derived); - bye: derived.bye.bind(derived); - } - } - Derived.prototype = Object.create(Foo.prototype); - Derived.prototype.bye = function bye() { - return 'Bye ' + this._secret; - }; - -While this solution solves given issue and provides proper encapsulation for -both own and inherited private properties, it does not addresses following: - - - Privates defined on the `prototype` can be compromised, since they are - accessible through the constructor (`Foo.prototype._secret`). - - Behavior of `instanceof` is broken, since `new Derived() instanceof Derived` - is going to evaluate to `false`. - -## Tamper Proofing with Property Descriptor Maps ## - -In ES5 new property descriptor maps were introduced, which can be used as a -building blocks for defining reusable peace of functionality. To some degree -they are similar to a `prototype` objects, and can be used so to define pieces -of functionality that is considered to be private (In contrast to `prototype` -they are not exposed by default). - - function Foo() { - var foo = Object.create(Foo.prototype, FooDescriptor); - var facade = Object.create(Foo.prototype); - facade.hello = foo.hello.bind(foo); - return facade; - } - Foo.prototype.hello = function hello() { - return 'Hello ' + this._secret; - } - var FooDescriptor = { - _secret: { value: 'secret' }; - } - - function Derived() { - var derived = Object.create(Derived.prototype, DerivedDescriptor); - var facade = Object.create(Derived.prototype); - facade.hello = derived.hello.bind(derived); - facade.bye = derived.bye.bind(derived); - return facade; - } - Derived.prototype = Object.create(Foo.prototype); - Derived.prototype.bye = function bye() { - return 'Bye ' + this._secret; - }; - DerivedDescriptor = {}; - - Object.keys(FooDescriptor).forEach(function(key) { - DerivedDescriptor[key] = FooDescriptor[key]; - }); - -## Cortex Objects ## - -Last approach solves all of the concerns, but adds complexity, verbosity -and decreases code readability. Combination of `Cortex`'s and `Trait`'s -will gracefully solve all these issues and keep code clean: - - var Cortex = require('cortex').Cortex; - var Trait = require('light-traits').Trait; - - var FooTrait = Trait({ - _secret: 'secret', - hello: function hello() { - return 'Hello ' + this._secret; - } - }); - function Foo() { - return Cortex(FooTrait.create(Foo.prototype)); - } - - var DerivedTrait = Trait.compose(FooTrait, Trait({ - bye: function bye() { - return 'Bye ' + this._secret; - } - })); - function Derived() { - var derived = DerivedTrait.create(Derived.prototype); - return Cortex(derived); - } - -Function `Cortex` takes any object and returns a proxy for its public -properties. By default properties are considered to be public if they don't -start with `"_"`, but default behavior can be overridden if needed, by passing -array of public property names as a second argument. - -## Gotchas ## - -`Cortex` is just a utility function to create a proxy object, and it does not -solve the `prototype`-related issues highlighted earlier, but since traits make -use of property descriptor maps instead of `prototype`s, there aren't any -issues with using `Cortex` to wrap objects created from traits. - -If you want to use `Cortex` with an object that uses a `prototype` chain, -however, you should either make sure you don't have any private properties -in the prototype chain or pass the optional third `prototype` argument. - -In the latter case, the returned proxy will inherit from the given prototype, -and the `prototype` chain of the wrapped object will be inaccessible. -However, note that the behavior of the `instanceof` operator will vary, -as `proxy instanceof Constructor` will return false even if the Constructor -function's prototype is in the wrapped object's prototype chain. - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md b/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md deleted file mode 100644 index b5057a2..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md +++ /dev/null @@ -1,43 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Module provides API to access, set and unset environment variables via exported -`env` object. - - var { env } = require('api-utils/environment'); - -You can get the value of an environment variable, by accessing property that -has name of desired variable: - - var PATH = env.PATH; - -You can check existence of an environment variable by checking if property with -such variable name exists: - - console.log('PATH' in env); // true - console.log('FOO' in env); // false - -You can set value of an environment variable by setting a property: - - env.FOO = 'foo'; - env.PATH += ':/my/path/' - -You can unset environment variable by deleting a property: - - delete env.FOO; - -## Limitations ## - -There is no way to enumerate existing environment variables, also `env` -won't have any enumerable properties: - - console.log(Object.keys(env)); // [] - -Environment variable will be unset, show up as non-existing if it's set -to `null`, `undefined` or `''`. - - env.FOO = null; - console.log('FOO' in env); // false - env.BAR = ''; - console.log(env.BAR); // undefined diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md b/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md deleted file mode 100644 index 98e94ac..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md +++ /dev/null @@ -1,42 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> - -The `errors` module provides helpers for safely invoking user callbacks. - -<api name="catchAndLog"> -@function - Wraps a callback in a function that when invoked will catch and log any - exception thrown by the callback. -@param callback {function} - The callback to wrap. -@param [defaultResponse] {value} - This value will be returned by the wrapper if `callback` throws an exception. - If not given, `undefined` is used. -@param [logException] {function} - When `callback` throws an exception, it will be passed to this function. If - not given, the exception is logged using `console.exception()`. -@returns {function} - A function that will invoke `callback` when called. The return value of this - function is the return value of `callback` unless `callback` throws an - exception. In that case, `defaultResponse` is returned or `undefined` if - `defaultResponse` is not given. -</api> - -<api name="catchAndLogProps"> -@function - Replaces methods of an object with wrapped versions of those methods returned - by `catchAndLog()`. -@param object {object} - The object whose methods to replace. -@param props {string,array} - The names of the methods of `object` to replace, either a string for a single - method or an array of strings for multiple methods. -@param [defaultResponse] {value} - This value will be returned by any wrapper whose wrapped method throws an - exception. If not given, `undefined` is used. -@param [logException] {function} - See `catchAndLog()`. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md b/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md deleted file mode 100644 index 6ab3317..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md +++ /dev/null @@ -1,51 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Module provides core (low level) API for working with events in the SDK. This -API is mainly for implementing higher level event APIs. - -Event `listener` may be registered on any (event `target`) object using -provided `on` function: - - var { on, once, off, emit } = require('api-utils/event/core'); - var target = { name: 'target' }; - on(target, 'message', function listener(event) { - console.log('hello ' + event); - }); - on(target, 'data', console.log); - -Event of specific `type` may be emitted on any event `target` object using -`emit` function. This will call all registered `listener`s for the given `type` -on the given event `target` in the same order they were registered. - - emit(target, 'message', 'event'); - // info: 'hello event' - emit(target, 'data', { type: 'data' }, 'second arg'); - // info: [Object object] 'second arg' - -Registered event listeners may be removed using `off` function: - - off(target, 'message'); - emit(target, 'message', 'bye'); - // info: 'hello bye' - -Sometimes listener only cares about first event of specific `type`. To avoid -hassles of removing such listeners there is convenient `once` function: - - once(target, 'load', function() { - console.log('ready'); - }); - emit(target, 'load') - // info: 'ready' - emit(target, 'load') - -There are also convenient ways to remove registered listeners. All listeners of -the specific type can be easily removed (only two argument must be passed): - - off(target, 'message'); - -Also, removing all registered listeners is possible (only one argument must be -passed): - - off(target); diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md b/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md deleted file mode 100644 index 96feb79..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md +++ /dev/null @@ -1,95 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Provides an exemplar `EventTarget` object, that implements interface for -adding removing event listeners of a specific type. `EventTarget` is a -base of all objects in SDK on which events are emitted. - -### Instantiation - -It's easy to create event target objects, no special arguments are required. - - const { EventTarget } = require('api-utils/event/target'); - let target = EventTarget.new(); - -For a convenience though optional `options` arguments may be used, in which -case all the function properties with keys like: `onMessage`, `onMyEvent`... -will be auto registered for associated `'message'`, `'myEvent'` events on -the created instance. _All other properties of `options` will be ignored_. - -### Adding listeners - -`EventTarget` interface defines `on` method, that can be used to register -event listeners on them for the given event type: - - target.on('message', function onMessage(message) { - // Note: `this` pseudo variable is an event `target` unless - // intentionally overridden via `.bind()`. - console.log(message); - }); - -Sometimes event listener may care only about very first event of specific -`type`. `EventTarget` interface defines convenience method for adding one -shot event listeners via method `once`. Such listeners are called only once -next time event of the specified type is emitted: - - target.once('ready', function onReady() { - // Do the thing once ready! - }); - -### Removing listeners - -`EventTarget` interface defines API for unregistering event listeners, via -`removeListener` method: - - target.removeListener('message', onMessage); - -### Emitting events - -`EventTarget` interface intentionally does not defines an API for emitting -events. In majority of cases party emitting events is different from party -registering listeners. In order to emit events one needs to use `event/core` -module instead: - - let { emit } = require('api-utils/event/core'); - - target.on('hi', function(person) { console.log(person + 'tells hi'); }); - emit(target, 'hi', 'Mark'); - // info: 'Mark tells hi' - -For more details see **event/core** documentation. - -### More details - -Listeners registered during the event propagation (by one of the listeners) -won't be triggered until next emit of the matching type: - - let { emit } = require('api-utils/event/core'); - - target.on('message', function onMessage(message) { - console.log('listener trigerred'); - target.on('message', function() { - console.log('nested listener triggered'); - }); - }); - - emit(target, 'message'); - // info: 'listener trigerred' - emit(target, 'message'); - // info: 'listener trigerred' - // info: 'nested listener trigerred' - -Exceptions in the listeners can be handled via `'error'` event listeners: - - target.on('boom', function() { - throw Error('Boom!'); - }); - target.once('error', function(error) { - console.log('caught an error: ' + error.message); - }); - emit(target, 'boom'); - // info: caught an error: Boom! - -If there is no listener registered for `error` event or if it also throws -exception then such exceptions are logged into a console. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/events.md b/tools/addon-sdk-1.7/packages/api-utils/docs/events.md deleted file mode 100644 index 76f9efd..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/events.md +++ /dev/null @@ -1,78 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `events` module provides base API for emitting events. - -This module is not intended to be used directly by programs. Rather, it is -intended to be used by other modules that provide APIs to programs. - -<api name="EventEmitter"> -@class -The EventEmitter is the base building block for all compositions that -would need to broadcast data to multiple consumers. - -Please note that `EventEmitter` does not expose either a method for emitting -events or a list of available event listeners as its public API. Obviously -both are accessible but from the instance itself through the private API. -<api name="EventEmitter"> -@constructor -Creates an EventEmitter object. -</api> - -<api name="on"> -@method -Registers an event `listener` that will be called when events of -specified `type` are emitted. - -If the `listener` is already registered for this `type`, a call to this -method has no effect. - -If the event listener is being registered while an event is being processed, -the event listener is not called during the current emit. - -**Example:** - - // worker is instance of EventEmitter - worker.on('message', function (data) { - console.log('data received: ' + data) - }); - -@param type {String} - The type of the event. -@param listener {Function} - The listener function that processes the event. -</api> - -<api name="once"> -@method -Registers an event `listener` that will only be called once, the next time -an event of the specified `type` is emitted. - -If the event listener is registered while an event of the specified `type` -is being emitted, the event listener will not be called during the current -emit. - -@param type {String} - The type of the event. -@param listener {Function} - The listener function that processes the event. -</api> - -<api name="removeListener"> -@method -Unregisters an event `listener` for the specified event `type`. - -If the `listener` is not registered for this `type`, a call to this -method has no effect. - -If an event listener is removed while an event is being processed, it is -still triggered by the current emit. After it is removed, the event listener -is never invoked again (unless registered again for future processing). - -@param type {String} - The type of the event. -@param listener {Function} - The listener function that processes the event. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/file.md b/tools/addon-sdk-1.7/packages/api-utils/docs/file.md deleted file mode 100644 index 9587353..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/file.md +++ /dev/null @@ -1,151 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `file` module provides access to the local filesystem. - - -Paths ------ - -Path specifications in this API are platform-specific. This means that on -Windows paths are specified using the backslash path separator (`\`), and on -Unix-like systems like Linux and OS X paths are specified using the forward -slash path separator (`/`). - -If your add-on uses literal Windows-style path specifications with this API, -your add-on likely won't work when users run it on Unix-like systems. Likewise, -if your add-on uses literal Unix-style path specifications, it won't work for -users on Windows. - -To ensure your add-on works for everyone, generate paths using the -[`join`](packages/api-utils/file.html#join(...)) function. Unfortunately -this API does not currently provide a way to obtain an absolute base path which -you could then use with `join`. For now, you need to -[`require("chrome")`](dev-guide/tutorials/chrome.html) and use the -XPCOM directory service as described at -[MDN](https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Getting_special_files). - -Note that if you do decide to hardcode Windows-style paths, be sure to escape -backslashes in strings. For example, to specify the file at `C:\Users\Myk`, you -need to use the string `"C:\\Users\\Myk"`, not `"C:\Users\Myk"`. You can read -more about escaping characters in strings at -[MDN](https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Escaping_Characters). - - -<api name="basename"> -@function - Returns the last component of the given path. For example, - `basename("/foo/bar/baz")` returns `"baz"`. If the path has no components, - the empty string is returned. -@param path {string} - The path of a file. -@returns {string} - The last component of the given path. -</api> - -<api name="dirname"> -@function - Returns the path of the directory containing the given file. If the file is - at the top of the volume, the empty string is returned. -@param path {string} - The path of a file. -@returns {string} - The path of the directory containing the file. -</api> - -<api name="exists"> -@function - Returns true if a file exists at the given path and false otherwise. -@param path {string} - The path of a file. -@returns {boolean} - True if the file exists and false otherwise. -</api> - -<api name="join"> -@function - Takes a variable number of strings, joins them on the file system's path - separator, and returns the result. -@param ... {strings} - A variable number of strings to join. The first string must be an absolute - path. -@returns {string} - A single string formed by joining the strings on the file system's path - separator. -</api> - -<api name="list"> -@function - Returns an array of file names in the given directory. -@param path {string} - The path of the directory. -@returns {array} - An array of file names. Each is a basename, not a full path. -</api> - -<api name="mkpath"> -@function - Makes a new directory named by the given path. Any subdirectories that do not - exist are also created. `mkpath` can be called multiple times on the same - path. -@param path {string} - The path to create. -</api> - -<api name="open"> -@function - Returns a stream providing access to the contents of a file. -@param path {string} - The path of the file to open. -@param [mode] {string} - An optional string, each character of which describes a characteristic of the - returned stream. If the string contains `"r"`, the file is opened in - read-only mode. `"w"` opens the file in write-only mode. `"b"` opens the - file in binary mode. If `"b"` is not present, the file is opened in text - mode, and its contents are assumed to be UTF-8. If *`mode`* is not given, - `"r"` is assumed, and the file is opened in read-only text mode. -@returns {stream} - If the file is opened in text read-only `mode`, a `TextReader` is returned, - and if text write-only mode, a `TextWriter` is returned. See - [`text-streams`](packages/api-utils/text-streams.html) for information on - these text stream objects. If the file is opened in binary read-only `mode`, - a `ByteReader` is returned, and if binary write-only mode, a `ByteWriter` is - returned. See - [`byte-streams`](packages/api-utils/byte-streams.html) for more - information on these byte stream objects. Opened files should always be - closed after use by calling `close` on the returned stream. -</api> - -<api name="read"> -@function - Opens a file and returns a string containing its entire contents. -@param path {string} - The path of the file to read. -@param [mode] {string} - An optional string, each character of which describes a characteristic of the - returned stream. If the string contains `"b"`, the contents will be returned - in binary mode. If `"b"` is not present or `mode` is not given, the file - contents will be returned in text mode. -@returns {string} - A string containing the file's entire contents. -</api> - -<api name="remove"> -@function - Removes a file from the file system. To remove directories, use `rmdir`. -@param path {string} - The path of the file to remove. -</api> - -<api name="rmdir"> -@function - Removes a directory from the file system. If the directory is not empty, an - exception is thrown. -@param path {string} - The path of the directory to remove. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md deleted file mode 100644 index c88d198..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md +++ /dev/null @@ -1,53 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `frame/utils` module provides helper functions for working with platform -internals like [frames](https://developer.mozilla.org/en/XUL/iframe) and -[browsers](https://developer.mozilla.org/en/XUL/browser). - -### create - -Module exports `create` function that takes `nsIDOMDocument` of the -[privileged document](https://developer.mozilla.org/en/Working_with_windows_in_chrome_code) -and creates a `browser` element in it's `documentElement`: - - let { open } = require('api-utils/window/utils'); - let { create } = require('api-utils/frame/utils'); - let window = open('data:text/html,Foo'); - let frame = create(window.document); - -Optionally `create` can be passed set of `options` to configure created frame -even further. Following options are supported: - -- `type` -String that defines access type of the document loaded into it. Defaults to -`'content'`. For more details and other possible values see -[documentation on MDN](https://developer.mozilla.org/en/XUL/Attribute/browser.type) - -- `uri` -URI of the document to be loaded into created frame. Defaults to `about:blank`. - -- `remote` -If `true` separate process will be used for this frame, also in such case all -the following options are ignored. - -- `allowAuth` -Whether to allow auth dialogs. Defaults to `false`. - -- `allowJavascript` -Whether to allow Javascript execution. Defaults to `false`. - -- `allowPlugins` -Whether to allow plugin execution. Defaults to `false`. - -Execution of scripts may easily be enabled: - - let { open } = require('api-utils/window/utils'); - let { create } = require('api-utils/frame/utils'); - let window = open('data:text/html,top'); - let frame = create(window.document, { - uri: 'data:text/html,<script>alert("Hello")</script>', - allowJavascript: true - }); - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md b/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md deleted file mode 100644 index e6df8a8..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md +++ /dev/null @@ -1,100 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Globals in this section are subject to change in the future and/or are likely -to be of interest to SDK module developers, rather than add-on developers. - -## Components ## - -To access the infamous and powerful `Components` object, see the -[Chrome Authority](dev-guide/tutorials/chrome.html) documentation. - -## \_\_url\_\_ ## - -The `__url__` global is a string identifying the URL from which the code has -been retrieved. If the code has no identifiable URL, this value may be `null`. - -## packaging ## - -<span class="aside"> -For more information on packaging, see the [Package Specification][] appendix. -</span> - -The `packaging` global contains methods and metadata related to -the packages available in the current environment. - -<code>packaging.**getURLForData**(*path*)</code> - -Given a unix-style path relative to the calling package's `data` -directory, returns an absolute URL to the file or directory. - -By "calling package", we mean the package in which the caller's source -code resides. - -Thus, for example, if a package contains a resource at -`data/mydata.dat` and a module at `lib/foo.js`, the module at -`lib/foo.js` may make the following call to retrieve an absolute URL -to `data/mydata.dat`: - - var myDataURL = packaging.getURLForData("/mydata.dat"); - -If the calling package has no `data` directory, an exception is -thrown. - -## memory ## - -`memory` is an object that exposes functionality to track -objects of interest and help diagnose and prevent memory leaks. - -<code>memory.**track**(*object*, [*bin*])</code> - -Marks *object* for being tracked, and categorizes it with the given -bin name. If *bin* isn't specified, the memory tracker attempts to -infer a bin name by first checking the object's -`constructor.name`; if that fails or results in the generic -`Object`, the stack is inspected and the name of the current -function being executed—which is assumed to be a constructor -function—is used. If that fails, then the object is placed in a -bin named `generic`. - -<code>memory.**getObjects**([*bin*])</code> - -Returns an `Array` containing information about tracked objects -that have been categorized with the given bin name. If *bin* isn't -provided, information about all live tracked objects are returned. - -Each element of the array is an object with the following keys: - -<table> - <tr> - <td><code>weakref</code></td> - <td>A weak reference to the object being tracked. Call - <code>get()</code> on this object to retrieve its strong reference; if - a strong reference to the object no longer exists, <code>get()</code> - will return <code>null</code>.</td> - </tr> - <tr> - <td><code>created</code></td> - <td>A <code>Date</code> representing the date and time that - <code>memory.track()</code> was called on the object being - tracked.</td> - </tr> - <tr> - <td><code>filename</code></td> - <td>The name of the file that called <code>memory.track()</code> on - the object being tracked.</td> - </tr> - <tr> - <td><code>lineNo</code></td> - <td>The line number of the file that called - <code>memory.track()</code> on the object being tracked.</td> - </tr> -</table> - -<code>memory.**getBins**()</code> - -Returns an `Array` containing the names of all bins that aren't -currently empty. - - [Package Specification]: dev-guide/package-spec.html
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md b/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md deleted file mode 100644 index 9d16dfa..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md +++ /dev/null @@ -1,83 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Myk Melez [myk@mozilla.org] --> - -The `hidden-frame` module creates host application frames (i.e. XUL `<iframe>` -elements) that are not displayed to the user. It is useful in the construction -of APIs that load web content not intended to be directly seen or accessed -by users, like `page-worker`. It is also useful in the construction of APIs -that load web content for intermittent display, such as `panel`. - -This module is not intended to be used directly by programs. Rather, it is -intended to be used by other modules that provide APIs to programs. - -Introduction ------------- - -The module exports a constructor function, `HiddenFrame`, and two other -functions, `add` and `remove`. - -`HiddenFrame` constructs a new hidden frame. `add` registers a hidden frame, -preparing it to load content. `remove` unregisters a frame, unloading any -content that was loaded in it. - -Examples --------- - -The following code creates a hidden frame, loads a web page into it, and then -logs its title: - - var hiddenFrames = require("hidden-frame"); - let hiddenFrame = hiddenFrames.add(hiddenFrames.HiddenFrame({ - onReady: function() { - this.element.contentWindow.location = "http://www.mozilla.org/"; - let self = this; - this.element.addEventListener("DOMContentLoaded", function() { - console.log(self.element.contentDocument.title); - }, true, true); - } - })); - -See the `panel` module for a real-world example of usage of this module. - -Reference ---------- -<api name="HiddenFrame"> -@class -`HiddenFrame` objects represent hidden frames. -<api name="HiddenFrame"> -@constructor -Creates a hidden frame. -@param options {object} - Options for the frame, with the following keys: - @prop onReady {function,array} - Functions to call when the frame is ready to load content. You must specify - an `onReady` callback and refrain from using the hidden frame until - the callback gets called, because hidden frames are not always ready to load - content the moment they are added. -</api> - -<api name="add"> -@function -Register a hidden frame, preparing it to load content. -@param hiddenFrame {HiddenFrame} the frame to add -</api> - -<api name="remove"> -@function -Unregister a hidden frame, unloading any content that was loaded in it. -@param hiddenFrame {HiddenFrame} the frame to remove -</api> - -<api name="element"> -@property {DOMElement} -The host application frame in which the page is loaded. -</api> - -<api name="onReady"> -@property {array} -Functions to call when the frame is ready to load content. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md b/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md deleted file mode 100644 index 3f131f9..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md +++ /dev/null @@ -1,31 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Provides an HTTP server written in JavaScript for the Mozilla platform, which -can be used in unit tests. - -The most basic usage is: - - var {startServerAsync} = require("httpd"); - var srv = startServerAsync(port, basePath); - require("unload").when(function cleanup() { - srv.stop(function() { // you should continue execution from this point. - }) - }); - -This starts a server in background (assuming you're running this code in an -application that has an event loop, such as Firefox). The server listens at -http://localhost:port/ and serves files from the specified directory. You -can serve static content or use SJS scripts, as described in documentation -on developer.mozilla.org. - -You can also use `nsHttpServer` to start the server manually: - - var {nsHttpServer} = require("httpd"); - var srv = new nsHttpServer(); - // further documentation on developer.mozilla.org - -See -[HTTP server for unit tests](https://developer.mozilla.org/En/HTTP_server_for_unit_tests) -for general information. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md b/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md deleted file mode 100644 index 367a6a9..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md +++ /dev/null @@ -1,295 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - - -[Traits](http://en.wikipedia.org/wiki/Trait_%28computer_science%29) are a simple -mechanism for structuring object-oriented programs. They represent reusable and -composable building blocks of functionality that factor out the common -attributes and behavior of objects. - -They are a more robust alternative to -[mixins](http://en.wikipedia.org/wiki/Mixins) and -[multiple inheritance](http://en.wikipedia.org/wiki/Multiple_inheritance), -because name clashes must be explicitly resolved and composition is commutative -and associative (i.e. the order of traits in a composition is irrelevant). - -Use traits to share functionality between similar objects without duplicating -code or creating complex inheritance chains. - -## Trait Creation ## - -To create a trait, call the `Trait` constructor function exported by this -module, passing it a JavaScript object that specifies the properties of the -trait. - - let Trait = require('light-traits').Trait; - let t = Trait({ - foo: "foo", - bar: function bar() { - return "Hi!" - }, - baz: Trait.required - }); - -Traits can both provide and require properties. A *provided* property is a -property for which the trait itself provides a value. A *required* property is a -property that the trait needs in order to function correctly but for which -it doesn't provide a value. - -Required properties must be provided by another trait or by an object with a -trait. Creation of an object with a trait will fail if required properties are -not provided. Specify a required property by setting the value of the property -to `Trait.required`. - -## Object Creation ## - -Create objects with a single trait by calling the trait's `create` method. The -method takes a single argument, the object to serve as the new object's -prototype. If no prototype is specified, the new object's prototype will be -`Object.prototype`. - - let t = Trait({ - foo: 'foo', - bar: 2 - }); - let foo1 = t.create(); - let foo2 = t.create({ name: 'Super' }); - -## Trait Composition ## - -Traits are designed to be composed with other traits to create objects with the -properties of multiple traits. To compose an object with multiple traits, you -first create a composite trait and then use it to create the object. A composite -trait is a trait that contains all of the properties of the traits from which it -is composed. In the following example, MagnitudeTrait is a composite trait. - - let EqualityTrait = Trait({ - equal: Trait.required, - notEqual: function notEqual(x) { - return !this.equal(x) - } - }); - - let ComparisonTrait = Trait({ - less: Trait.required, - notEqual: Trait.required, - greater: function greater(x) { - return !this.less(x) && this.notEqual(x) - } - }); - - let MagnitudeTrait = Trait.compose(EqualityTrait, ComparisonTrait); - -<?xml version="1.0"?> -<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="-11 121 490 190" width="490px" height="190px"> - <defs> - <marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="SharpArrow_Marker" viewBox="-4 -4 10 8" markerWidth="10" markerHeight="8" color="black"> - <g> - <path d="M 5 0 L -3 -3 L 0 0 L 0 0 L -3 3 Z" fill="currentColor" stroke="currentColor" stroke-width="1px"/> - </g> - </marker> - </defs> - <g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1"> - <g> - <rect x="9" y="165.33334" width="141" height="14"/> - <rect x="9" y="165.33334" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 165.33334)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="47.373047">notEqual</tspan> - </text> - <rect x="9" y="151.33334" width="141" height="14"/> - <rect x="9" y="151.33334" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 151.33334)" fill="red"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="29.361328">equal</tspan> - </text> - <rect x="9" y="137.33334" width="141" height="14"/> - <rect x="9" y="137.33334" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 137.33334)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="bold" x="38.49707" y="11" textLength="54.00586">EqualityTrait</tspan> - </text> - <rect x="9" y="273" width="141" height="14"/> - <rect x="9" y="273" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 273)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="38.021484">greater</tspan> - </text> - <rect x="9" y="259" width="141" height="14"/> - <rect x="9" y="259" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 259)" fill="red"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="47.373047">notEqual</tspan> - </text> - <rect x="9" y="245" width="141" height="14"/> - <rect x="9" y="245" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 245)" fill="red"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="21.339844">less</tspan> - </text> - <rect x="9" y="231" width="141" height="14"/> - <rect x="9" y="231" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(14 231)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="bold" x=".15332031" y="11" textLength="112.67578">ComparisonTrait</tspan> - </text> - <rect x="317.75" y="235.5" width="141" height="14"/> - <rect x="317.75" y="235.5" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(322.75 235.5)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="38.021484">greater</tspan> - </text> - <rect x="317.75" y="221.5" width="141" height="14"/> - <rect x="317.75" y="221.5" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(322.75 221.5)" fill="red"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="21.339844">less</tspan> - </text> - <rect x="317.75" y="207.5" width="141" height="14"/> - <rect x="317.75" y="207.5" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(322.75 207.5)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="47.373047">notEqual</tspan> - </text> - <rect x="317.75" y="193.5" width="141" height="14"/> - <rect x="317.75" y="193.5" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(322.75 193.5)" fill="red"> - <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="29.361328">equal</tspan> - </text> - <rect x="317.75" y="179.5" width="141" height="14"/> - <rect x="317.75" y="179.5" width="141" height="14" stroke="black" stroke-width="1px"/> - <text transform="translate(322.75 179.5)" fill="black"> - <tspan font-family="Helvetica" font-size="12" font-weight="bold" x="31.83789" y="11" textLength="67.32422">MagnitudeTrait</tspan> - </text> - <path d="M 150 248.83887 L 158.89999 248.83887 L 235.9 248.83887 L 235.9 224.66113 L 308.85 224.66113 L 310.85 224.66113" marker-end="url(#SharpArrow_Marker)" stroke="black" stroke-linecap="butt" stroke-linejoin="miter" stroke-width="1px"/> - <path d="M 150 171.15845 L 158.89999 171.15845 L 233.9 171.15845 L 233.9 201.6749 L 308.85 201.6749 L 310.85 201.6749" marker-end="url(#SharpArrow_Marker)" stroke="black" stroke-linecap="butt" stroke-linejoin="miter" stroke-width="1px"/> - </g> - </g> -</svg> - -## Trait Resolution ## - -Composite traits have conflicts when two of the traits in the composition -provide properties with the same name but different values (when compared using -the `===` strict equality operator). In the following example, `TC` has a -conflict because `T1` and `T2` both define a `foo` property: - - let T1 = Trait({ - foo: function () { - // do something - }, - bar: 'bar', - t1: 1 - }); - - let T2 = Trait({ - foo: function() { - // do something else - }, - bar: 'bar', - t2: 2 - }); - - let TC = Trait.compose(T1, T2); - -Attempting to create an object from a composite trait with conflicts throws a -`remaining conflicting property` exception. To create objects from such traits, -you must resolve the conflict. - -You do so by excluding or renaming the conflicting property of one of the -traits. Excluding a property removes it from the composition, so the composition -only acquires the property from the other trait. Renaming a property gives it a -new, non-conflicting name at which it can be accessed. - -In both cases, you call the `resolve` method on the trait whose property you -want to exclude or rename, passing it an object. Each key in the object is the -name of a conflicting property; each value is either `null` to exclude the -property or a string representing the new name of the property. - -For example, the conflict in the previous example could be resolved by excluding -the `foo` property of the second trait. - - let TC = Trait(T1, T2.resolve({ foo: null })); - -It could also be resolved by renaming the `foo` property of the first trait to -`foo2`: - - let TC = Trait(T1.resolve({ foo: "foo2" }), T2); - -When you resolve a conflict, the same-named property of the other trait (the one -that wasn't excluded or renamed) remains available in the composition under its -original name. - -## Constructor Functions ## - -When your code is going to create more than one object with traits, you may want -to define a constructor function to create them. To do so, create a composite -trait representing the traits the created objects should have, then define a -constructor function that creates objects with that trait and whose prototype is -the prototype of the constructor: - - let PointTrait = Trait.compose(T1, T2, T3); - function Point(options) { - let point = PointTrait.create(Point.prototype); - return point; - } - -## Property Descriptor Maps ## - -Traits are designed to work with the new object manipulation APIs defined in -[ECMAScript-262, Edition -5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) (ES5). -Traits are also property descriptor maps that inherit from `Trait.prototype` to -expose methods for creating objects and resolving conflicts. - -The following trait definition: - - let FooTrait = Trait({ - foo: "foo", - bar: function bar() { - return "Hi!" - }, - baz: Trait.required - }); - -Creates the following property descriptor map: - - { - foo: { - value: 'foo', - enumerable: true, - configurable: true, - writable: true - }, - - bar: { - value: function b() { - return 'bar' - }, - enumerable: true, - configurable: true, - writable: true - }, - - baz: { - get baz() { throw new Error('Missing required property: `baz`') } - set baz() { throw new Error('Missing required property: `baz`') } - }, - - __proto__: Trait.prototype - } - -Since Traits are also property descriptor maps, they can be used with built-in -`Object.*` methods that accept such maps: - - Object.create(proto, FooTrait); - Object.defineProperties(myObject, FooTrait); - -Note that conflicting and required properties won't cause exceptions to be -thrown when traits are used with the `Object.*` methods, since those methods are -not aware of those constraints. However, such exceptions will be thrown when the -property with the conflict or the required but missing property is accessed. - -Property descriptor maps can also be used in compositions. This may be useful -for defining non-enumerable properties, for example: - - let TC = Trait.compose( - Trait({ foo: 'foo' }), - { bar: { value: 'bar', enumerable: false } } - ); - -_When using property descriptor maps in this way, make sure the map is not the -only argument to `Trait.compose`, since in that case it will be interpreted as -an object literal with properties to be defined._ - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/list.md b/tools/addon-sdk-1.7/packages/api-utils/docs/list.md deleted file mode 100644 index fd70698..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/list.md +++ /dev/null @@ -1,98 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> - -The `"list"` module provides base building blocks for composing lists. - -<api name="Iterable"> -@class -Base trait that can be used to compose traits with non-standard -enumeration behaviors. - -This trait is supposed to be used as part of a composition, since it only -provides custom enumeration behavior to a composed object. -It defines one required `_keyValueMap` property, that is used as a hash of -"key-values" to iterate on during enumeration. - -<api name="Iterable"> -@constructor -Constructs an `Iterable` object. -</api> - -<api name="_keyValueMap"> -@property {Object} -Hash map of key-values to iterate over. _Required_ property: that is, the -property must be supplied by objects that compose this trait. -_Note: That this property can be a getter if you need dynamic behavior._ -</api> - -</api> - -<api name="List"> -@class -An ordered collection (also known as a sequence) disallowing duplicate -elements. List is composed out of `Iterable`, therefore it provides custom -enumeration behavior that is similar to array (enumerates only on the -elements of the list). - -List is a base trait and is meant to be part of a -composition, since all of its API is private except for the `length` property. - -**Examples:** - - var MyList = List.compose({ - add: function add(item1, item2, /*item3...*/) { - Array.slice(arguments).forEach(this._add.bind(this)); - }, - remove: function remove(item1, item2, /*item3...*/) { - Array.slice(arguments).forEach(this._remove.bind(this)); - } - }); - MyList('foo', 'bar', 'baz').length == 3; // true - new MyList('new', 'keyword').length == 2; // true - MyList.apply(null, [1, 2, 3]).length == 3; // true - let list = MyList(); - list.length == 0; // true - list.add(1, 2, 3) == 3; // true - -<api name="List"> -@constructor -Constructor can takes any number of elements and creates an instance of -`List` populated with the specified elements. -@param [element1] {Object|String|Number} -@param [element2] {Object|String|Number} -@param [...] {Object|String|Number} -</api> - -<api name="length"> -@property {Number} -Number of elements in this list. -</api> - -<api name="_has"> -@method -@param element {Object|Number|String} -Returns `true` if this list contains the specified `element`. -</api> -<api name="_add"> -@method -@param element {Object|Number|String} -Appends the specified `element` to the end of this list, if it doesn't -contain it. - -_Ignores the call if `element` is already contained._ -</api> -<api name="_remove"> -@method -@param element {Object|Number|String} -Removes specified `element` from this list, if it contains it. - -_Ignores the call if `element` is not contained._ -</api> -<api name="_clear"> -@method -Removes all of the elements from this list. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md b/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md deleted file mode 100644 index 0222e65..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md +++ /dev/null @@ -1,246 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `match-pattern` module can be used to test strings containing URLs -against simple patterns. - -## Specifying Patterns ## - -There are three ways you can specify patterns: - -* as an exact match string -* using a wildcard in a string -* using a regular expression - -### Exact Matches ### - -**A URL** matches only that URL. The URL must start with a scheme, end with a -slash, and contain no wildcards. - -<table> - - <colgroup> - <col width="30%"> - <col width="35%"> - <col width="35%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - <th>Example non-matching URLs</th> - </tr> - - <tr> - <td><code>"http://example.com/"</code></td> - <td><code>http://example.com/</code></td> - <td><code>http://example.com</code><br> - <code>http://example.com/foo</code><br> - <code>https://example.com/</code><br> - <code>http://foo.example.com/</code></td> - </tr> - -</table> - -### Wildcards ### - -**A single asterisk** matches any URL with an `http`, `https`, or `ftp` -scheme. For other schemes like `file`, use a scheme followed by an -asterisk, as below. - -<table> - - <colgroup> - <col width="30%"> - <col width="35%"> - <col width="35%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - <th>Example non-matching URLs</th> - </tr> - - <tr> - <td><code>"*"</code></td> - <td><code>http://example.com/</code><br> - <code>https://example.com/</code><br> - <code>ftp://example.com/</code><br> - <code>http://bar.com/foo.js</code><br> - <code>http://foo.com/</code></td> - <td><code>file://example.js</code></td> - </tr> - -</table> - -**A domain name prefixed with an asterisk and dot** matches any URL of that -domain or a subdomain, using any of `http`, `https`, `ftp`. - -<table> - - <colgroup> - <col width="30%"> - <col width="35%"> - <col width="35%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - <th>Example non-matching URLs</th> - </tr> - - <tr> - <td><code>"*.example.com"</code></td> - <td><code>http://example.com/</code><br> - <code>http://foo.example.com/</code><br> - <code>https://example.com/</code><br> - <code>http://example.com/foo</code><br> - <code>ftp://foo.example.com/</code></td> - <td><code>ldap://example.com</code><br> - <code>http://example.foo.com/</code></td> - </tr> - -</table> - -**A URL followed by an asterisk** matches that URL and any URL prefixed with -the pattern. - -<table> - - <colgroup> - <col width="30%"> - <col width="35%"> - <col width="35%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - <th>Example non-matching URLs</th> - </tr> - - <tr> - <td><code>"https://foo.com/*"</code></td> - <td><code>https://foo.com/</code><br> - <code>https://foo.com/bar</code></td> - <td><code>http://foo.com/</code><br> - <code>https://foo.com</code><br> - <code>https://bar.foo.com/</code></td> - </tr> - -</table> - -**A scheme followed by an asterisk** matches all URLs with that scheme. To -match local files, use `file://*`. - -<table> - - <colgroup> - <col width="30%"> - <col width="70%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - </tr> - - <tr> - <td><code>"file://*"</code></td> - <td><code>file://C:/file.html</code><br> - <code>file:///home/file.png</code></td> - </tr> - -</table> - -### Regular Expressions ### - -You can specify patterns using a -[regular expression](https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions): - - var { MatchPattern } = require("match-pattern"); - var pattern = new MatchPattern(/.*example.*/); - -The regular expression is subject to restrictions based on those applied to the -[HTML5 pattern attribute](http://dev.w3.org/html5/spec/common-input-element-attributes.html#attr-input-pattern). In particular: - -* The pattern must match the entire value, not just any subset. For example, the -pattern `/moz.*/` will not match the URL `http://mozilla.org`. - -* The expression is compiled with the `global`, `ignoreCase`, and `multiline` flags - disabled. The `MatchPattern` constructor will throw an exception - if you try to set any of these flags. - -<table> - - <colgroup> - <col width="30%"> - <col width="35%"> - <col width="35%"> - </colgroup> - - <tr> - <th>Example pattern</th> - <th>Example matching URLs</th> - <th>Example non-matching URLs</th> - </tr> - - <tr> - <td><code>/.*moz.*/</code></td> - <td><code>http://foo.mozilla.org/</code><br> - <code>http://mozilla.org</code><br> - <code>https://mozilla.org</code><br> - <code>http://foo.com/mozilla</code><br> - <code>http://hemozoon.org</code><br> - <code>mozscheme://foo.org</code><br></td> - <td><code>http://foo.org</code><br> - </tr> - - <tr> - <td><code>/http:\/\/moz.*/</code></td> - <td><code>http://mozilla.org</code><br> - <code>http://mozzarella.com</code></td> - <td><code>https://mozilla.org</code><br> - <code>http://foo.mozilla.org/</code><br> - <code>http://foo.com/moz</code></td> - </tr> - - <tr> - <td><code>/http.*moz.*/</code><br></td> - <td><code>http://foo.mozilla.org/</code><br> - <code>http://mozilla.org</code><br> - <code>http://hemozoon.org/</code></td> - <td><code>ftp://http/mozilla.org</code></td> - </tr> - -</table> - -## Examples ## - - var { MatchPattern } = require("match-pattern"); - var pattern = new MatchPattern("http://example.com/*"); - console.log(pattern.test("http://example.com/")); // true - console.log(pattern.test("http://example.com/foo")); // true - console.log(pattern.test("http://foo.com/")); // false! - -<api name="MatchPattern"> -@class -<api name="MatchPattern"> -@constructor - This constructor creates match pattern objects that can be used to test URLs. -@param pattern {string} - The pattern to use. See Patterns above. -</api> - -<api name="test"> -@method - Tests a URL against the match pattern. -@param url {string} - The URL to test. -@returns {boolean} - True if the URL matches the pattern and false otherwise. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md b/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md deleted file mode 100644 index 04de606..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md +++ /dev/null @@ -1,7 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `memory` module provides a concrete default implementation for the SDK's -`memory` global. For documentation on the `memory` global, see the -[Globals](packages/api-utils/globals.html) reference. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md b/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md deleted file mode 100644 index 522c613..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md +++ /dev/null @@ -1,13 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Matteo Ferretti [zer0@mozilla.com] --> - -Overview --------- -The `message-manager` module provides a minimalist implementation -of the [Message Manager](https://developer.mozilla.org/en/The_message_manager) -APIs, in a single process environment. - -It's mainly used internally for Fennec Birch support.
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md b/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md deleted file mode 100644 index 07ec96e..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md +++ /dev/null @@ -1,71 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Provides an API for creating namespaces for any given objects, which -effectively may be used for creating fields that are not part of objects -public API. - - let { ns } = require('api-utils/namespace'); - let aNamespace = ns(); - - aNamespace(publicAPI).secret = secret; - -One namespace may be used with multiple objects: - - let { ns } = require('api-utils/namespace'); - let dom = ns(); - - function View(element) { - let view = Object.create(View.prototype); - dom(view).element = element; - // .... - } - View.prototype.destroy = function destroy() { - let { element } = dom(this); - element.parentNode.removeChild(element); - // ... - }; - // ... - exports.View = View; - // ... - -Also, multiple namespaces can be used with one object: - - // ./widget.js - - let { Cu } = require('chrome'); - let { ns } = require('api-utils/namespace'); - let { View } = require('./view'); - - // Note this is completely independent from View's internal Namespace object. - let sandboxes = ns(); - - function Widget(options) { - let { element, contentScript } = options; - let widget = Object.create(Widget.prototype); - View.call(widget, options.element); - sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); - // ... - } - Widget.prototype = Object.create(View.prototype); - Widget.prototype.postMessage = function postMessage(message) { - let { sandbox } = sandboxes(this); - sandbox.postMessage(JSON.stringify(JSON.parse(message))); - ... - }; - Widget.prototype.destroy = function destroy() { - View.prototype.destroy.call(this); - // ... - delete sandboxes(this).sandbox; - }; - exports.Widget = Widget; - -In addition access to the namespace can be shared with other code by just -handing them a namespace accessor function. - - let { dom } = require('./view'); - Widget.prototype.setInnerHTML = function setInnerHTML(html) { - dom(this).element.innerHTML = String(html); - }; - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md b/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md deleted file mode 100644 index 4d7cb58..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md +++ /dev/null @@ -1,73 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `observer-service` module provides access to the -application-wide observer service singleton. - -For a list of common observer topics across a variety of Mozilla-based -applications, see the MDC page on -[Observer Notifications](https://developer.mozilla.org/en/Observer_Notifications). - -## Observer Callbacks ## - -Observer callbacks are functions of the following form: - - function callback(subject, data) { - /* Respond to the event notification here... */ - } - -In the above example, `subject` is any JavaScript object, as is -`data`. The particulars of what the two contain are specific -to the notification topic. - -<api name="add"> -@function - Adds an observer callback to be triggered whenever a notification matching the - topic is broadcast throughout the application. - -@param topic {string} - The topic to observe. - -@param callback {function,object} - Either a function or an object that implements [`nsIObserver`](http://mxr.mozilla.org/mozilla-central/source/xpcom/ds/nsIObserver.idl). - If a function, then it is called when the notification occurs. If an object, - then its `observe()` method is called when the notification occurs. - -@param [thisObject] {object} - An optional object to use as `this` when a function callback is called. -</api> - -<api name="remove"> -@function - Unsubscribes a callback from being triggered whenever a notification - matching the topic is broadcast throughout the application. - -@param topic {string} - The topic being observed by the previous call to `add()`. - -@param callback {function,object} - The callback subscribed in the previous call to `add()`, either a function or - object. - -@param [thisObject] {object} - If `thisObject` was passed to the previous call to `add()`, it should be - passed to `remove()` as well. -</api> - -<api name="notify"> -@function - Broadcasts a notification event for a topic, passing a subject and data to all - applicable observers in the application. - -@param topic {string} - The topic about which to broadcast a notification. - -@param [subject] {value} - Optional information about the topic. This can be any JS object or primitive. - If you have multiple values to pass to observers, wrap them in an object, - e.g., `{ foo: 1, bar: "some string", baz: myObject }`. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md b/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md deleted file mode 100644 index d139587..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md +++ /dev/null @@ -1,7 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `plain-text-console` module provides a minimalist implementation -of the [console](dev-guide/console.html) global, -which simply logs all messages to standard output. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md b/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md deleted file mode 100644 index 03b4725..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md +++ /dev/null @@ -1,116 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Myk Melez [myk@mozilla.org] --> -<!-- contributed by Daniel Aquino [mr.danielaquino@gmail.com] --> -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `preferences-service` module provides access to the -application-wide preferences service singleton. - - -<api name="set"> -@function -Sets the application preference `name` to `value`. -@param name {string} Preference name. -@param value {string,number,bool} Preference value. - -**Example:** - - var name = "extensions.checkCompatibility.nightly"; - require("preferences-service").set(name, false); -</api> - - -<api name="get"> -@function -Gets the application preference `name`. -@param name {string} -@param defaultValue {string,number,bool} Preference value. -@returns {string,number,bool} Preference value, returns a default value if no -preference is set. - -**Example:** - - var name = "extensions.checkCompatibility.nightly"; - var nightlyCompatChk = require("preferences-service").get(name); -</api> - - -<api name="has"> -@function -@param name {string} Preference name. -@returns {bool} Returns whether or not the application preference `name` exists. - -**Example:** - - var name = "extensions.checkCompatibility.nightly"; - if (require("preferences-service").has(name)) { - // ... - } -</api> - - -<api name="isSet"> -@function -@param name {string} Preference name. -@returns {bool} -Returns whether or not the application preference `name` both exists -and has been set to a non-default value by the user (or a program -acting on the user's behalf). - -**Example:** - - var name = "extensions.checkCompatibility.nightly"; - if (require("preferences-service").isSet(name)) { - // ... - } -</api> - - -<api name="reset"> -@function -Clears a non-default, user-set value from the application preference -`name`. If no user-set value is defined on `name`, the function -does nothing. If no default value exists the preference will cease to exist. -@param name {string} Preference name. - -**Example:** - - var name = "extensions.checkCompatibility.nightly"; - require("preferences-service").reset(name); -</api> - -<api name="getLocalized"> -@function -Gets the localized value for an application preference `name`. -@param name {string} -@param defaultValue {string} Preference value. -@returns {string} Localized preference value, returns a default value if no -preference is set. Some preferences refer to a properties file. -So that `prefs.get` returns the properties file URL whereas -`prefs.getLocalized` returns the value defined in the properties file. - -**Example:** - - var prefs = require("preferences-service"); - var name = "general.useragent.locale"; - prefs.get(name); // is equal to "chrome://global/locale/intl.properties" - prefs.getLocalized(name) // is equal to "en-US" - -</api> - -<api name="setLocalized"> -@function -Sets the localized application preference `name` to `value`. -@param name {string} Preference name. -@param value {string} Preference value, a URL to a properties file - -**Example:** - - require("preferences-service").set("general.useragent.locale", - "chrome://global/locale/intl.properties"); - -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md b/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md deleted file mode 100644 index d67b820..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md +++ /dev/null @@ -1,394 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -## Rationale - -Most of the JS APIs are asynchronous complementing it's non-blocking nature. -While this has a good reason and many advantages, it comes with a price. -Instead of structuring our programs into logical black boxes: - - function blackbox(a, b) { - var c = assemble(a); - return combine(b, c); - } - - -We're forced into continuation passing style, involving lot's of machinery: - - function sphagetti(a, b, callback) { - assemble(a, function continueWith(error, c) { - if (error) callback(error); - else combine(b, c, callback); - }); - } - -This style also makes doing things in sequence hard: - - widget.on('click', function onClick() { - promptUserForTwitterHandle(function continueWith(error, handle) { - if (error) return ui.displayError(error); - twitter.getTweetsFor(handle, funtion continueWith(error, tweets) { - if (error) return ui.displayError(error); - ui.showTweets(tweets); - }); - }); - }); - -Doing things in parallel is even harder: - - var tweets, answers, checkins; - twitter.getTweetsFor(user, function continueWith(result) { - tweets = result; - somethingFinished(); - }); - - stackOverflow.getAnswersFor(question, function continueWith(result) { - answers = result; - somethingFinished(); - }); - - fourSquare.getCheckinsBy(user, function continueWith(result) { - checkins=result; - somethingFinished(); - }); - - var finished = 0; - functions somethingFinished() { - if (++finished === 3) - ui.show(tweets, answers, checkins); - } - -This also makes error handling quite of an adventure. - -## Promises - -Consider another approach, where instead of continuation passing via `callback`, -function returns an object, that represents eventual result, either successful -or failed. This object is a promise, both figuratively and by name, to -eventually resolve. We can call a function on the promise to observe -either its fulfillment or rejection. If the promise is rejected and the -rejection is not explicitly observed, any derived promises will be implicitly -rejected for the same reason. - -In the Add-on SDK we follow -[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) specification -and model a promise as an object with a `then` method, which can be used to get -the eventual return (fulfillment) value or thrown exception (rejection): - - foo().then(function success(value) { - // ... - }, function failure(reason) { - // ... - }); - -If `foo` returns a promise that gets fulfilled with the `value`, `success` -callback (the value handler) will be called with that `value`. However, -if the returned promise gets rejected, the `failure` callback (the error -handler) will be called with the `reason` of an error. - -## Propagation - -The `then` method of a promise returns a new promise that is resolved with the -return value of either handler. Since function can either return value or throw -an exception, only one handler will be ever called. - - - var bar = foo().then(function success(value) { - // compute something from a value... - }, function failure(reason) { - // handle an error... - }); - -In this example `bar` is a promise and it's fulfilled by one of two handlers -that are responsible for: - - - If handler returns a value, `bar` will be resolved with it. - - If handler throws an exception, `bar` will be rejected with it. - - If handler returns a **promise**, `bar` will "become" that promise. To be - more precise it will be resolved with a resolution value of the returned - promise, which will appear and feel as if it was that returned promise. - -If the `foo()` promise gets rejected and you omit the error handler, the -**error** will propagate to `bar` (`bar` will be rejected with that error): - - var bar = foo().then(function success(value) { - // compute something out of the value... - }); - -If the `foo()` promise gets fulfilled and you omit the value handler, the -**value** will propagate to `bar` (`bar` will be fulfilled with that value): - - var bar = foo().then(null, function failure(error) { - // handle error... - }); - - -## Chaining - -There are two ways to chain promise operations. You can chain them using either -inside or outside handlers. - -### Flat chaining - -You can use `then` for chaining intermediate operations on promises -(`var data = readAsync().then(parse).then(extract)`). You can chain multiple -`then` functions, because `then` returns a promise resolved to a return value -of an operation and errors propagate through the promise chains. In general -good rule of thumb is to prefer `then` based flat chaining. It makes code -easier to read and make changes later: - - var data = readAsync(url). // read content of url asynchronously - then(parse). // parse content from the url - then(extractQuery). // extract SQL query - then(readDBAsync); // exectue extracted query against DB - -### Nested chaining - -Flat chaining is not always an option though, as in some cases you may want to -capture an intermediate values of the chain: - - var result = readAsync(url).then(function(source) { - var json = parse(source) - return readDBAsync(extractQuery(json)).then(function(data) { - return writeAsync(json.url, data); - }); - }); - -In general, nesting is useful for computing values from more then one promise: - - function eventualAdd(a, b) { - return a.then(function (a) { - return b.then(function (b) { - return a + b; - }); - }); - } - - var c = eventualAdd(aAsync(), bAsync()); - -## Error handling - -One sometimes-unintuitive aspect of promises is that if you throw an exception -in the value handler, it will not be be caught by the error handler. - - readAsync(url).then(function (value) { - throw new Error("Can't bar."); - }, function (error) { - // We only get here if `readAsync` fails. - }); - -To see why this is, consider the parallel between promises and `try`/`catch`. -We are `try`-ing to execute `readAsync()`: the error handler represents a -`catch` for `readAsync()`, while the value handler represents code that happens -*after* the `try`/`catch` block. That code then needs its own `try`/`catch` -block to handle errors there. - -In terms of promises, this means chaining your error handler: - - readAsync(url). - then(parse). - then(null, function handleParseError(error) { - // handle here both `readAsync` and `parse` errors. - }); - - -# Consuming promises - -In general, whole purpose of promises is to avoid a callback spaghetti in the -code. As a matter of fact it would be great if we could convert any synchronous -functions to asynchronous by making it aware of promises. Module exports -`promised` function to do exactly that: - - const { promised } = require('api-utils/promise'); - function sum(x, y) { return x + y } - var sumAsync = promised(sum); - - var c = sum(a, b); - var cAsync = asyncSum(aAsync(), bAsinc()); - -`promised` takes normal function and composes new promise aware version of it -that may take both normal values and promises as arguments and returns promise -that will resolve to value that would have being returned by an original -function if it was called with fulfillment values of given arguments. - -This technique is so powerful that it can replace most of the promise utility -functions provided by other promise libraries. For example grouping promises -to observe single resolution of all of them is as simple as this: - - var group = promised(Array); - var abc = group(aAsync, bAsync, cAsync).then(function(items) { - return items[0] + items[1] + items[2]; - }); - -# Making promises - -Everything above assumes you get a promise from somewhere else. This -is the common case, but every once in a while, you will need to create a -promise from scratch. Add-on SDK's `promise` module provides API for doing -that. - -## defer - -Module exports `defer` function, which is where all promises ultimately -come from. Lets see implementation of `readAsync` that we used in lot's -of examples above: - - const { defer } = require('api-utils/promise'); - function readAsync(url) { - var deferred = defer(); - - let xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.onload = function() { - deferred.resolve(xhr.responseText); - } - xhr.onerror = function(event) { - deferred.reject(event); - } - xhr.send(); - - return deferred.promise; - } - -So `defer` returns an object that contains `promise` and two `resolve`, `reject` -functions that can be used to resolve / reject that `promise`. **Note:** that -promise can be rejected or resolved and only once. All subsequent attempts will be -ignored. - -Another simple example may be `delay` function that returns promise which -is fulfilled with a given `value` in a given `ms`, kind of promise based -alternative to `setTimeout`: - - function delay(ms, value) { - let { promise, resolve } = defer(); - setTimeout(resolve, ms, value); - return promise; - } - - delay(10, 'Hello world').then(console.log); - // After 10ms => 'Helo world' - -# Advanced usage - -If general `defer` and `promised` should be enough to doing almost anything -you may think of with promises, but once you start using promises extensively -you may discover some missing pieces and this section of documentation may -help you to discover them. - -## Doing things concurrently - -So far we have being playing with promises that do things sequentially, but -there are bunch of cases where one would need to do things concurrently. In the -following example we implement functions that takes multiple promises and -returns one that resolves to first on being fulfilled: - - function race() { - let { promise, resolve } = defer(); - Array.slice(arguments).forEach(function(promise) { - promise.then(resolve); - }); - return promise; - } - - var asyncAorB = race(readAsync(urlA), readAsync(urlB)); - -*Note: that this implementation forgives failures and would fail if all -promises fail to resolve.* - -There are cases when promise may or may not be fulfilled in a reasonable time. -In such cases it's useful to put a timer on such tasks: - - function timeout(promise, ms) { - let deferred = defer(); - promise.then(deferred.resolve, deferred.reject); - delay(ms, 'timeout').then(deferred.reject); - return deferred.promise; - } - - var tweets = readAsync(url); - timeout(tweets, 20).then(function(data) { - ui.display(data); - }, function() { - alert('Network is being too slow, try again later'); - }); - -## Alternative promise APIs - -There may be a cases where you will want to provide more than just `then` -method on your promises. In fact some other promise frameworks do that. -Such use cases are also supported. Earlier described `defer` may be passed -optional `prototype` argument, in order to make returned promise and all -the subsequent promises decedents of that `prototype`: - - let { promise, resolve } = defer({ - get: function get(name) { - return this.then(function(value) { - return value[name]; - }) - } - }); - - promise.get('foo').get('bar').then(console.log); - resolve({ foo: { bar: 'taram !!' } }); - - // => 'taram !!' - -Also `promised` function maybe passed second optional `prototype` argument to -achieve same effect. - -## Treat all values as promises - -Module provides a simple function for wrapping values into promises: - - const { resolve } = require('api-utils/promise'); - - var a = resolve(5).then(function(value) { - return value + 2 - }); - a.then(console.log); // => 7 - -Also `resolve` not only takes values, but also promises. If you pass it -a promise it will return new identical one: - - const { resolve } = require('api-utils/promise'); - - resolve(resolve(resolve(3))).then(console.log); // => 3 - -If this construct may look strange at first, but it becomes quite handy -when writing functions that deal with both promises and values. In such -cases it's usually easier to wrap value into promise than branch on value -type: - - function or(a, b) { - var second = resolve(b).then(function(bValue) { return !!bValue }); - return resolve(a).then(function(aValue) { - return !!aValue || second; - }, function() { - return second; - }) - } - -*Note: We could not use `promised` function here, as they reject returned -promise if any of the given arguments is rejected.* - -If you need to customize your promises even further you may pass `resolve` a -second optional `prototype` argument that will have same effect as with `defer`. - -## Treat errors as promises - -Now that we can create all kinds of eventual values, it's useful to have a -way to create eventual errors. Module exports `reject` exactly for that. -It takes anything as an argument and returns a promise that is rejected with -it. - - const { reject } = require('api-utils/promise'); - - var boom = reject(Error('boom!')); - - future(function() { - return Math.random() < 0.5 ? boom : value - }) - -As with rest of the APIs error may be given second optional `prototype` -argument to customize resulting promise to your needs. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md b/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md deleted file mode 100644 index 30f4117..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md +++ /dev/null @@ -1,37 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Module exports utility functions for working with query strings. - -### stringify - -Object may be serialize to a query string via exported `stringify` function: - - querystring.stringify({ foo: 'bar', baz: 4 }); // => 'foo=bar&baz=4' - -Optionally `separator` and `assignment` arguments may be passed to -override default `'&'` and`'='` characters: - - querystring.stringify({ foo: 'bar', baz: 4 }, ';', ':'); // => 'foo:bar;baz:4' - -### parse - -Query string may be deserialized to an object via exported `parse` -function: - - querystring.parse('foo=bar&baz=bla') // => { foo: 'bar', baz: 'bla' } - -Optionally `separator` and `assignment` arguments may be passed to -override default `'&'` and `'='` characters: - - querystring.parse('foo:bar|baz:bla', '|', ':') // => { foo: 'bar', baz: 'bla' } - -### escape - -The escape function used by `stringify` to encodes a string safely -matching RFC 3986 for `application/x-www-form-urlencoded`. - -### unescape - -The unescape function used by `parse` to decode a string safely. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md b/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md deleted file mode 100644 index c8d8ed3..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md +++ /dev/null @@ -1,75 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Wes Kocher [kwierso@gmail.com] --> - -The `runtime` module provides access to information about Firefox's -runtime environment. All properties exposed are read-only. - -For more information, see [nsIXULRuntime][nsIXULRuntime]. -[nsIXULRuntime]: https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIXULRuntime - -<api name="inSafeMode"> -@property {boolean} - This value is `true` if Firefox was started in safe mode, - otherwise `false`. -</api> - -<api name="OS"> -@property {string} - A string identifying the current operating system. For example, . - `"WINNT"`, `"Darwin"`, or `"Linux"`. See [OS_TARGET][OS_TARGET] - for a more complete list of possible values. - -[OS_TARGET]: https://developer.mozilla.org/en/OS_TARGET -</api> - -<api name="processType"> -@property {long} - The type of the caller's process, which will be one of these constants\: -<table> - <tr> - <th>Constant</th> - <th>Value</th> - <th>Description</th> - </tr> - - <tr> - <td>PROCESS_TYPE_DEFAULT</td> - <td>0</td> - <td>The default (chrome) process.</td> - </tr> - - <tr> - <td>PROCESS_TYPE_PLUGIN</td> - <td>1</td> - <td>A plugin subprocess.</td> - </tr> - - <tr> - <td>PROCESS_TYPE_CONTENT</td> - <td>2</td> - <td>A content subprocess.</td> - </tr> - - <tr> - <td>PROCESS_TYPE_IPDLUNITTEST</td> - <td>3</td> - <td>An IPDL unit testing subprocess.</td> - </tr> -</table> -</api> - -<api name="widgetToolkit"> -@property {string} - A string identifying the target widget toolkit in use. -</api> - -<api name="XPCOMABI"> -@property {string} - A string identifying the [ABI][ABI] of the current processor and compiler vtable. - This string takes the form \<`processor`\>-\<`compilerABI`\>, - for example\: "`x86-msvc`" or "`ppc-gcc3`". -[ABI]: https://developer.mozilla.org/en/XPCOM_ABI -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md b/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md deleted file mode 100644 index 026b569..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md +++ /dev/null @@ -1,51 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Provides an API for creating javascript sandboxes and for executing scripts -in them. - -### Create a sandbox ### - -For the starting point you need to create a sandbox: - - const { sandbox, evaluate, load } = require("api-utils/sandbox"); - let scope = sandbox('http://example.com'); - -Argument passed to the sandbox defines it's privileges. Argument may be an URL -string, in which case sandbox will get exact same privileges as a scripts -loaded from that URL. Argument also could be a DOM window object, to inherit -privileges from the window being passed. Finally if argument is omitted or is -`null` sandbox will have a chrome privileges giving it access to all the XPCOM -components. Optionally `sandbox` function can be passed a second optional -argument (See [sandbox documentation on MDN](https://developer.mozilla.org/en/Components.utils.Sandbox#Optional_parameter) -for details). - -### Evaluate code ### - -Module provides `evaluate` function that allows executing code in the given -sandbox: - - evaluate(scope, 'var a = 5;'); - evaluate(scope, 'a + 2;'); //=> 7 - -More details about evaluated script may be passed via optional arguments that -may improve an exception reporting: - - // Evaluate code as if it was loaded from 'http://foo.com/bar.js' and - // start from 2nd line. - evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); - -Version of JavaScript can be also specified via optional argument: - - evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); - // throws cause `let` is not defined in JS 1.5. - -### Loading scripts ### - -API provides limited API for loading scripts right form the local URLs, -but data: URLs are supported. - - load(scope, 'resource://path/to/my/script.js'); - load(scope, 'file:///path/to/script.js'); - load(scope, 'data:,var a = 5;');
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md b/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md deleted file mode 100644 index 295fcc7..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md +++ /dev/null @@ -1,140 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Dietrich Ayala [dietrich@mozilla.com] --> - -The `tab-browser` module is a low-level API that provides privileged -access to browser tab events and actions. - -Introduction ------------- - -The `tab-browser` module contains helpers for tracking tabbrowser elements -and tabs, as well as a few utilities for actions such as opening a new -tab, and catching all tab content loads. - -This is a low-level API that has full privileges, and is intended to be used -by SDK internal modules. If you just need easy access to tab events for your -add-on, use the Tabs module (JEP 110). - -<api name="activeTab"> -@property {element} -The XUL tab element of the currently active tab. -</api> - -<api name="addTab"> -@function -Adds a new tab. - -**Example** - - var tabBrowser = require("tab-browser"); - tabBrowser.addTab("http://google.com"); - - var tabBrowser = require("tab-browser"); - tabBrowser.addTab("http://google.com", { - inBackground: true - }); - - var tabBrowser = require("tab-browser"); - tabBrowser.addTab("http://google.com", { - inNewWindow: true, - onLoad: function(tab) { - console.log("tab is open."); - } - }); - -@returns {element} -The XUL tab element of the newly created tab. - -@param URL {string} -The URL to be opened in the new tab. - -@param options {object} -Options for how and where to open the new tab. - -@prop [inNewWindow] {boolean} -An optional parameter whose key can be set in `options`. -If true, the tab is opened in a new window. Default is false. - -@prop [inBackground] {boolean} -An optional parameter whose key can be set in `options`. -If true, the tab is opened adjacent to the active tab, but not -switched to. Default is false. - -@prop [onLoad] {function} -An optional parameter whose key can be set in `options`. -A callback function that is called once the tab has loaded. -The XUL element for the tab is passed as a parameter to -this function. -</api> - -<api name="Tracker"> -@function -Register a delegate object to be notified when tabbrowsers are created -and destroyed. - -The onTrack method will be called once per pre-existing tabbrowser, upon -tracker registration. - -**Example** - - var tabBrowser = require("tab-browser"); - let tracker = { - onTrack: function(tabbrowser) { - console.log("A new tabbrowser is being tracked."); - }, - onUntrack: function(tabbrowser) { - console.log("A tabbrowser is no longer being tracked."); - } - }; - tabBrowser.Tracker(tracker); - -@param delegate {object} -Delegate object to be notified each time a tabbrowser is created or destroyed. -The object should contain the following methods: - -@prop [onTrack] {function} -Method of delegate that is called when a new tabbrowser starts to be tracked. -The tabbrowser element is passed as a parameter to this method. - -@prop [onUntrack] {function} -Method of delegate that is called when a tabbrowser stops being tracked. -The tabbrowser element is passed as a parameter to this method. -</api> - -<api name="TabTracker"> -@function -Register a delegate object to be notified when tabs are opened and closed. - - -The onTrack method will be called once per pre-existing tab, upon -tracker registration. - -**Example** - - var tabBrowser = require("tab-browser"); - let tracker = { - onTrack: function(tab) { - console.log("A new tab is being tracked."); - }, - onUntrack: function(tab) { - console.log("A tab is no longer being tracked."); - } - }; - tabBrowser.TabTracker(tracker); - -@param delegate {object} -Delegate object to be notified each time a tab is opened or closed. -The object should contain the following methods: - -@prop [onTrack] {function} -Method of delegate that is called when a new tab starts to be tracked. -The tab element is passed as a parameter to this method. - -@prop [onUntrack] {function} -Method of delegate that is called when a tab stops being tracked. -The tab element is passed as a parameter to this method. -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md b/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md deleted file mode 100644 index 55f177c..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md +++ /dev/null @@ -1,102 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `text-streams` module provides streams for reading and writing text using -particular character encodings. - -<api name="TextReader"> -@class -<api name="TextReader"> -@constructor - Creates a buffered input stream that reads text from a backing stream using a - given text encoding. -@param inputStream {stream} - The backing stream, an [`nsIInputStream`](http://mxr.mozilla.org/mozilla-central/source/xpcom/io/nsIInputStream.idl). - It must already be opened. -@param [charset] {string} - `inputStream` is expected to be in the character encoding named by this value. - If not specified, "UTF-8" is assumed. See [`nsICharsetConverterManager.idl`](http://mxr.mozilla.org/mozilla-central/source/intl/uconv/idl/nsICharsetConverterManager.idl) - for documentation on how to determine other valid values for this. -</api> - -<api name="closed"> -@property {boolean} - True if the stream is closed. -</api> - -<api name="close"> -@method - Closes both the stream and its backing stream. -</api> - -<api name="read"> -@method - Reads and returns a string from the stream. If the stream is closed, an - exception is thrown. -@param [numChars] {number} - The number of characters to read. If not given, the remainder of the stream - is read. -@returns {string} - The string read. If the stream is at the end, the empty string is returned. -</api> - -</api> - - -<api name="TextWriter"> -@class -<api name="TextWriter"> -@constructor - Creates a buffered output stream that writes text to a backing stream using a - given text encoding. -@param outputStream {stream} - The backing stream, an [`nsIOutputStream`](http://mxr.mozilla.org/mozilla-central/source/xpcom/io/nsIOutputStream.idl). - It must already be opened. -@param [charset] {string} - Text will be written to `outputStream` using the character encoding named by - this value. If not specified, "UTF-8" is assumed. See [`nsICharsetConverterManager.idl`](http://mxr.mozilla.org/mozilla-central/source/intl/uconv/idl/nsICharsetConverterManager.idl) - for documentation on how to determine other valid values for this. -</api> - -<api name="closed"> -@property {boolean} - True if the stream is closed. -</api> - -<api name="close"> -@method - Flushes the backing stream's buffer and closes both the stream and the backing - stream. If the stream is already closed, an exception is thrown. -</api> - -<api name="flush"> -@method - Flushes the backing stream's buffer. -</api> - -<api name="write"> -@method - Writes a string to the stream. If the stream is closed, an exception is - thrown. -@param str {string} - The string to write. -</api> - -<api name="writeAsync"> -@method - Writes a string on a background thread. After the write completes, the - backing stream's buffer is flushed, and both the stream and the backing stream - are closed, also on the background thread. If the stream is already closed, - an exception is thrown immediately. -@param str {string} - The string to write. -@param [callback] {callback} - *`callback`*, if given, must be a function. It's called as `callback(error)` - when the write completes. `error` is an `Error` object or undefined if there - was no error. Inside *`callback`*, `this` is the `TextWriter` object. -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md b/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md deleted file mode 100644 index b52c183..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md +++ /dev/null @@ -1,66 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - - -The `traceback` module contains functionality similar to -Python's [traceback](http://docs.python.org/library/traceback.html) module. - -## JSON Traceback Objects ## - -Tracebacks are stored in JSON format. The stack is represented as an -array in which the most recent stack frame is the last element; each -element thus represents a stack frame and has the following keys: - -<table> - <tr> - <td><code>filename</code></td> - <td>The name of the file that the stack frame takes place in.</td> - </tr> - <tr> - <td><code>lineNo</code></td> - <td>The line number is being executed at the stack frame.</td> - </tr> - <tr> - <td><code>funcName</code></td> - <td>The name of the function being executed at the stack frame, or - <code>null</code> if the function is anonymous or the stack frame is - being executed in a top-level script or module.</td> - </tr> -</table> - -<api name="fromException"> -@function - Attempts to extract the traceback from *`exception`*. - -@returns {traceback} - JSON representation of the traceback or `null` if not found. - -@param exception {exception} - exception where exception is an `nsIException`. -</api> - -See [nsIException](https://developer.mozilla.org/en/NsIException) for more -information. - -<api name="get"> -@function - -@returns {JSON} - Returns the JSON representation of the stack at the point that this - function is called. -</api> - -<api name="format"> -@function -Given a JSON representation of the stack or an exception instance, -returns a formatted plain text representation of it, similar to -Python's formatted stack tracebacks. If no argument is provided, the -stack at the point this function is called is used. - -@param [tbOrException] {object} -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md b/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md deleted file mode 100644 index 910cd9a..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md +++ /dev/null @@ -1,244 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Irakli Gozalishvil [gozala@mozilla.com] --> - -The `traits` module provides base building blocks for secure object -composition. It exports base trait / constructor function that -constructs an instance of `Trait`. - -[Traits](http://en.wikipedia.org/wiki/Trait_%28computer_science%29) are a -simple composition mechanism for structuring object-oriented programs. Traits -are similar to -[interfaces](http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29), -except that they often define only a part of an object's data and behavior and -are intended to be used in conjunction with other traits to completely define -the object. - -Traits are also considered to be a more robust alternative to -[mixins](http://en.wikipedia.org/wiki/Mixins) because, name conflicts have to -be resolved explicitly by composer & because trait composition is -order-independent (hence more declarative). - - -There are some other implementations of traits in JavaScript & some ideas / -APIs are borrowed from them: - -- [traitsjs](http://www.traitsjs.org/) -- [joose](http://code.google.com/p/joose-js/) - -Object-capability security model --------------------------------- - -Implementation uses an -[object-capability security model](http://en.wikipedia.org/wiki/Object-capability_model) -to allow protection of private APIs. At the same private APIs can be shared -between among trait composition parties. To put it simply: All the properties -whose names start with `"_"` are considered to be **private**, and are -unaccessible from anywhere except other **public** methods / accessors of the -instance that had been defined during composition. - -<api name="Trait"> -@class -<api name="Trait"> -@constructor -Creates an instance of Trait and returns it if it has no `constructor` method -defined. If instance has `constructor` method, then it is called with all the -arguments passed to this function and returned value is returned instead, -unless it's `undefined`. In that case instance is returned. - -`Trait` function represents a base trait. As with any other trait it represents -a constructor function for creating instances of its own & a placeholder -for a trait compositions functions. -</api> - -<api name="compose"> -@method -Composes new trait out of itself and traits / property maps passed as an -arguments. If two or more traits / property maps have properties with the same -name, the new trait will contain a "conflict" property for that name (see -examples in Examples section to find out more about "conflict" properties). -This is a commutative and associative operation, and the order of its -arguments is not significant. - -**Examples:** - -Let's say we want to define a reusable piece of code for a lists of elements. - - var { Trait } = require('traits'); - var List = Trait.compose({ - // private API: - _list: null, - // public API - constructor: function List() { - this._list = []; - }, - get length() this._list.length, - add: function add(item) this._list.push(item), - remove: function remove(item) { - let list = this._list; - let index = list.indexOf(item); - if (0 <= index) list.splice(index, 1); - } - }); - -Instances of `List` can be created by calling `List` function with or without -`new` keyword. - - let l1 = List(); - l1 instanceof List; // true - let l2 = new List(); - l2 instanceof List; // true - -As you can see `add` and `remove` functions are capable of accessing private -`_list` property, but thats about it, there's nothing else that will be able -to access this property: - - '_list' in l1; // false - '_list' in l2; // false - '_list' in List.protoype; // false - l1.has = function(name) name in this - l1.has('_list'); // false - l1.length; // 0 - l1.add('test') - l1.length // 1 - -@param trait1 {Object|Function} - Trait or property map to compose new trait from. -@param trait2 {Object|Function} - Trait or property map to compose new trait from. -@param ... {Object|Function} - Traits or property maps to compose new trait from. - -@returns {Function} - New trait containing the combined properties of all the traits. -</api> - -<api name="required"> -@property {Object} -Singleton, used during trait composition to define "required" properties. - -**Example:** - - var Enumerable = Trait.compose({ - list: Trait.required, - forEach: function forEach(consumer) { - return this.list.forEach(consumer); - } - }); - - let c1 = Enumerable(); // Error: Missing required property: list - - var EnumerableList = List.compose({ - get list() this._list.slice(0) - }, Enumerable); - - let c2 = EnumerableList(); - c2.add('test') - c2.length // 1 - c2.list[0] // 'test' - c2.forEach(console.log) // > info: 'test 0 test' - -</api> - - -<api name="resolve"> -@method -Composes a new trait that has all the same properties -as the trait on which it is called, except that each property listed -in the `resolutions` argument will be renamed from the name -of the property in the `resolutions` argument to its value. -And if its value is `null`, the property will become required. - -**Example:** - - var Range = List.resolve({ - constructor: null, - add: '_add', - }).compose({ - min: null, - max: null, - get list() this._list.slice(0), - constructor: function Range(min, max) { - this.min = min; - this.max = max; - this._list = []; - }, - add: function(item) { - if (item <= this.max && item >= this.min) - this._add(item) - } - }); - - - let r = Range(0, 10); - r.min; // 0 - r.max; // 10 - r.length; // 0; - r.add(5); - r.length; // 1 - r.add(12); - r.length; // 1 (12 was not in a range) - -@param resolutions {Object} -@returns {Function} - New resolved trait. -</api> - -<api name="override"> -@method -Composes a new trait with all of the combined properties of `this` and the -argument traits. In contrast to `compose`, `override` immediately resolves -all conflicts resulting from this composition by overriding the properties of -later traits. Trait priority is from left to right. I.e. the properties of -the leftmost trait are never overridden. - -**Example:** - - // will compose trait with conflict property 'constructor' - var ConstructableList = List.compose({ - constructor: function List() this._list = Array.slice(arguments) - }); - // throws error with message 'Remaining conflicting property: constructor' - ConstructableList(1, 2, 3); - - var ConstructableList = List.override({ - constructor: function List() this._list = Array.slice(arguments) - }); - ConstructableList(1, 2, 3).length // 3 - -@param trait1 {Object|Function} - Trait or property map to compose new trait from. -@param trait2 {Object|Function} - Trait or property map to compose new trait from. -@param ... {Object|Function} - Traits or property maps to compose new trait from. - -@returns {Function} - New trait containing the combined properties of all the traits. -</api> - -<api name="_public"> -@property {Object} -Internal property of instance representing public API that is exposed to the -consumers of an instance. -</api> - -<api name='toString'> -@method -Textual representation of an object. All the traits will return: -`'[object Trait]'` string, unless they have `constructor` property, in that -case string `'Trait'` is replaced with the name of `constructor` property. - -**Example:** - - var MyTrait = Trait.compose({ - constructor: function MyTrait() { - // do your initialization here - } - }); - MyTrait().toString(); // [object MyTrait] - -</api> -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md b/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md deleted file mode 100644 index 6962c41..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md +++ /dev/null @@ -1,393 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> -<!-- edited by Shane Tomlinson[stomlinson@mozilla.com] --> - -The `unit-test` module makes it easy to find and run unit tests. - -<api name="test"> -@class -Each function which represents a test case is passed a single argument -`test`, which represents the test runner. - -<api name="pass"> -@method - Marks a test as passing, with the given optional message. - -@param [message] {string} - Optional passing message. -</api> - - -<api name="fail"> -@method - Marks a test as failing, with the given optional message. - -@param [message] {string} - Optional failure message. -</api> - -<api name="expectFail"> -@method - *experimental* Expect the test enclosed within `func` to fail. - -@param func {function} - A function that should contain a test that is expected to fail. -</api> - -<api name="exception"> -@method - Marks a test as failing due to the given exception having been thrown. - This can be put in a `catch` clause. - -@param e {exception} - An exception. -</api> - -<api name="assert"> -@method - Ensures that `a` has a truthy value. - -@param a {value} - Value to verify. -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - -<api name="assertEqual"> -@method - Ensures that `a == b` without recursing into `a` or `b`. - -@param a {value} - A value. - -@param b {value} - Another value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - -<api name="assertNotEqual"> -@method - Ensures that `a != b` without recursing into `a` or `b`. - -@param a {value} - A value. - -@param b {value} - Another value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - -<api name="assertStrictEqual"> -@method - Ensures that `a === b` without recursing into `a` or `b`. - -@param a {value} - A value. - -@param b {value} - Another value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - -<api name="assertNotStrictEqual"> -@method - Ensures that `a !== b` without recursing into `a` or `b`. - -@param a {value} - A value. - -@param b {value} - Another value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - -<api name="assertMatches"> -@method - Ensures that the given string matches the given regular expression. - If it does, marks a test as passing, otherwise marks a test as - failing. - -@param string {string} - The string to test. - -@param regexp {regexp} - The string should match this regular expression. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - -<api name="assertRaises"> -@method - Calls the function `func` with no arguments, expecting an exception - to be raised. If nothing is raised, marks the test as failing. If an - exception is raised, the exception's `message` property is - compared with `predicate`: if `predicate` is a string, then a - simple equality comparison is done with `message`. Otherwise, - if `predicate` is a regular expression, `message` is tested - against it. - -@param func {function} - A function that should raise an exception when called. - -@param predicate {string,regexp} - A string or regular expression to compare to the exception's message. - -@param [message] {string} - Depending on the outcome, a test is marked as passing or failing, and - *message* is logged. -</api> - - -<api name="assertFunction"> -@method - Ensures that `a` is a function. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertUndefined"> -@method - Ensures that `a` is `undefined`. `null`, `0`, and `false` will all fail. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertNotUndefined"> -@method - Ensures that `a` is not `undefined`. `null`, `0`, and `false` will all pass. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertNull"> -@method - Ensures that `a` is `null`. `undefined`, `0`, and `false` will all fail. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertNotNull"> -@method - Ensures that `a` is not `null`. `undefined`, `0`, and `false` will all pass. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertObject"> -@method - Ensures that `a` is an object. A function, string, or number will fail. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertString"> -@method - Ensures that `a` is a string. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertArray"> -@method - Ensures that `a` is an array. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="assertNumber"> -@method - Ensures that `a` is a number. - -@param a {value} - A value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. - -</api> - - -<api name="waitUntilDone"> -@method - Puts the test runner into asynchronous testing mode, waiting up to - *timeout* milliseconds for `test.done()` to be called. This - is intended for use in situations where a test suite schedules a - callback, calls `test.waitUntilDone()`, and then calls - `test.done()` in the callback. - -@param [timeout] {integer} - If this number of milliseconds elapses and `test.done()` has not yet been - called, the test is marked as failing. -</api> - - -<api name="done"> -@method - Marks a test as being complete. Assumes a previous call to - `test.waitUntilDone()`. -</api> - -</api> - - -<api name="waitUntil"> -@method - Ensures that `a` returns a truthy value within a reasonable amount of time. - -@param a {function} - Function that returns the value to verify. -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - -<api name="waitUntilEqual"> -@method - Ensures that `a == b` returned values or values without without recursing - into `a` or `b`. - -@param a {Function} - A value, or a function that returns a value. - -@param b {value} - Another value, or a function that returns value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - -<api name="waitUntilNotEqual"> -@method - Ensures that `a != b` without recursing into `a` or `b`. - -@param a {Function} - A value, or a function that returns a value. - -@param b {value} - Another value, or a function that returns another value. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - -<api name="waitUntilMatches"> -@method - Ensures that the given string matches the given regular expression. - If it does, marks the test as passing, otherwise marks the test as - failing. - -@param string {Function} - A function that returns the string to test. - -@param regexp {regexp} - The string should match this regular expression. - -@param [message] {string} - The test is marked as passing or failing depending on the result, logging - *message* with it. -</api> - - - -<api name="findAndRunTests"> -@function - The list of directories is searched for SecurableModules that start - with the prefix `test-`. Each module matching this criteria is - expected to export functions that are test cases or a suite of test - cases; each is called with a single argument, which is a Test Runner - Object. - -@param options {object} - An object with the following properties: - @prop dirs {string} - A list of absolute paths representing directories to search - for tests in. It's assumed that all of these directories are also - in the module search path, i.e. any JS files found in them are - SecurableModules that can be loaded via a call to - `require()`. - @prop onDone {function} - A function to call when testing is complete. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md b/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md deleted file mode 100644 index 8a76b3f..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md +++ /dev/null @@ -1,61 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `unload` module allows modules to register callbacks that are called -when they are unloaded. It is similar to the CommonJS module of the same -name in the [Narwhal][] platform. - -[Narwhal]: http://narwhaljs.org/ - -<api name="ensure"> -@function - Calling `ensure()` on an object does two things: - - 1. It replaces a destructor method with a wrapper method that will never call - the destructor more than once. - 2. It ensures that this wrapper method is called when `send()` is - called. - - Therefore, when you register an object with `ensure()`, you can call its - destructor method yourself, you can let it happen for you, or you can do both. - - The destructor will be called with a single argument describing the reason - for the unload; see `when()`. If `object` does not have the expected - destructor method, then an exception is thrown when `ensure()` is called. - -@param object {object} - An object that defines a destructor method. -@param [name] {string} - Optional name of the destructor method. Default is `unload`. -</api> - -<api name="when"> -@function - Registers a function to be called when `send()` is called. - -@param callback {function} - A function that will be called when `send()` is called. It is called with a - single argument, one of the following strings describing the reason for - unload: `"uninstall"`, `"disable"`, `"shutdown"`, `"upgrade"`, or - `"downgrade"`. (On Gecko 1.9.2-based applications such as Firefox 3.6, - `"upgrade"` and `"downgrade"` are not available, and `"shutdown"` will be sent - in their place.) If a reason could not be determined, `undefined` will be - passed instead. Note that if an add-on is unloaded with reason `"disable"`, - it will not be notified about `"uninstall"` while it is disabled. A solution - to this issue is being investigated; see bug 571049. -</api> - -<api name="send"> -@function - Sends an "unload signal", thereby triggering all callbacks registered via - `when()`. In general, this function need not be manually called; it is - automatically triggered by the embedder. - -@param [reason] {string} - An optional string describing the reason for unload; see `unload.when()`. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/url.md b/tools/addon-sdk-1.7/packages/api-utils/docs/url.md deleted file mode 100644 index 2974797..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/url.md +++ /dev/null @@ -1,85 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - - -The `url` module provides functionality for the parsing and retrieving of URLs. - -<api name="URL"> -@class -<api name="URL"> -@constructor - The URL constructor creates an object that represents a URL, verifying that - the provided string is a valid URL in the process. Any API in the SDK which - has a URL parameter will accept `URL` objects, not raw strings, unless - otherwise noted. - -@param source {string} - A string to be converted into a URL. If `source` is not a valid URI, this - constructor will throw an exception. - -@param [base] {string} - An optional string used to resolve relative `source` URLs into absolute ones. -</api> - -<api name="scheme"> -@property {string} - The name of the protocol in the URL. -</api> - -<api name="userPass"> -@property {string} - The username:password part of the URL, `null` if not present. -</api> - -<api name="host"> -@property {string} - The host of the URL, `null` if not present. -</api> - -<api name="port"> -@property {integer} - The port number of the URL, `null` if none was specified. -</api> - -<api name="path"> -@property {string} - The path component of the URL. -</api> - -<api name="toString"> -@method - Returns a string representation of the URL. -@returns {string} - The URL as a string. -</api> -</api> - -<api name="toFilename"> -@function - Attempts to convert the given URL to a native file path. This function will - automatically attempt to resolve non-file protocols, such as the `resource:` - protocol, to their place on the file system. An exception is raised if the URL - can't be converted; otherwise, the native file path is returned as a string. - -@param url {string} - The URL, as a string, to be converted. - -@returns {string} - The converted native file path as a string. -</api> - -<api name="fromFilename"> -@function - Converts the given native file path to a `file:` URL. - -@param path {string} - The native file path, as a string, to be converted. - -@returns {string} - The converted URL as a string. -</api> - diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md b/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md deleted file mode 100644 index 429e3a0..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md +++ /dev/null @@ -1,27 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Module `uuid` provides low level API for generating / parsing UUID, that may -be necessary when hacking on internals of the platform. - - -## Generate UUID - -Module exports `uuid` function. When called without arguments it will uses -platform-specific methods to obtain a `nsID` that can be considered to be -globally unique. - - let uuid = require('api-utils/uuid').uuid() - -## Parsing UUID - -Sometimes one might need to create `nsID` from an existing UUID string. Same -`uuid` function may be used to parse such UUID strings into an `nsID`: - - let { uuid } = require('api-utils/uuid'); - let firefoxUUID = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); - -For more details about UUID representations and what they are used for by the -platform see MDN documentation for -[JSID](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIJSID) diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md deleted file mode 100644 index 1435fd2..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md +++ /dev/null @@ -1,88 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> -<!-- edited by Erik Vold [erikvvold@gmail.com] --> - -The `window-utils` module provides helpers for accessing and tracking -application windows. These windows implement the [`nsIDOMWindow`][nsIDOMWindow] -interface. - -[nsIDOMWindow]: http://mxr.mozilla.org/mozilla-central/source/dom/interfaces/base/nsIDOMWindow.idl - -<api name="WindowTracker"> -@class -`WindowTracker` objects make it easy to "monkeypatch" windows when a program is -loaded and "un-monkeypatch" those windows when the program is unloaded. For -example, if a Firefox add-on needs to add a status bar icon to all browser -windows, it can use a single `WindowTracker` object to gain access to windows -when they are opened and closed and also when the add-on is loaded and unloaded. - -When a window is opened or closed, a `WindowTracker` notifies its delegate -object, which is passed to the constructor. The delegate is also notified of -all windows that are open at the time that the `WindowTracker` is created and -all windows that are open at the time that the `WindowTracker` is unloaded. The -caller can therefore use the same code to act on all windows, regardless of -whether they are currently open or are opened in the future, or whether they are -closed while the parent program is loaded or remain open when the program is -unloaded. - -When a window is opened or when a window is open at the time that the -`WindowTracker` is created, the delegate's `onTrack()` method is called and -passed the window. - -When a window is closed or when a window is open at the time that the -`WindowTracker` is unloaded, the delegate's `onUntrack()` method is called and -passed the window. (The `WindowTracker` is unloaded when its its `unload()` -method is called, or when its parent program is unloaded, disabled, or -uninstalled, whichever comes first.) - -**Example** - - var delegate = { - onTrack: function (window) { - console.log("Tracking a window: " + window.location); - // Modify the window! - }, - onUntrack: function (window) { - console.log("Untracking a window: " + window.location); - // Undo your modifications! - } - }; - var winUtils = require("window-utils"); - var tracker = new winUtils.WindowTracker(delegate); - -<api name="WindowTracker"> -@constructor - A `WindowTracker` object listens for openings and closings of application - windows. -@param delegate {object} - An object that implements `onTrack()` and `onUntrack()` methods. -@prop onTrack {function} - A function to be called when a window is open or loads, with the window as the - first and only argument. -@prop [onUntrack] {function} - A function to be called when a window unloads, with the window as the first - and only argument. -</api> -</api> - -<api name="windowIterator"> -@function - An iterator for windows currently open in the application. - -**Example** - - var winUtils = require("window-utils"); - for (window in winUtils.windowIterator()) - console.log("An open window! " + window.location); - -</api> - -<api name="closeOnUnload"> -@function - Marks an application window to be closed when the program is unloaded. -@param window {window} - The window to close. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md deleted file mode 100644 index 276a17a..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md +++ /dev/null @@ -1,90 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -The `window/utils` module provides helper functions for working with -application windows. - -### getInnerId - -Returns the ID of the given window's current inner window. - -### getOuterId - -Returns the ID of the given window's outer window. - -### getXULWindow - -Module provides `getXULWindow` function that can be used get access -[nsIXULWindow](https://developer.mozilla.org/en/nsIDOMWindow) for the given -[nsIDOMWindow](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIXULWindow): - - let { Ci } = require('chrome'); - let utils = require('api-utils/window-utils'); - let active = utils.activeBrowserWindow; - active instanceof Ci.nsIXULWindow // => false - utils.getXULWindow(active) instanceof Ci.nsIXULWindow // => true - -### getBaseWindow - -Module provides `getBaseWindow` function that can be used get access -[nsIBaseWindow](http://mxr.mozilla.org/mozilla-central/source/widget/nsIBaseWindow.idl) -for the given [nsIDOMWindow](https://developer.mozilla.org/en/nsIDOMWindow): - - let { Ci } = require('chrome'); - let utils = require('api-utils/window-utils'); - let active = utils.activeBrowserWindow; - active instanceof Ci.nsIBaseWindow // => false - utils.getBaseWindow(active) instanceof Ci.nsIBaseWindow // => true - -### open - -Module exports `open` function that may be used to open top level -(application) windows. Function takes `uri` of the window document as a first -argument and optional hash of `options` as second argument. - - let { open } = require('api-utils/window-utils'); - let window = open('data:text/html,Hello Window'); - -Following options may be provided to configure created window behavior: - -- `parent` -If provided must be `nsIDOMWindow` and will be used as parent for the created -window. - -- `name` -Optional name that will be assigned to the window. - -- `features` -Hash of options that will be serialized to features string. See -[features documentation](https://developer.mozilla.org/en/DOM/window.open#Position_and_size_features) -for more details. - - let { open } = require('api-utils/window/utils'); - let window = open('data:text/html,Hello Window', { - name: 'jetpack window', - features: { - width: 200, - height: 50, - popup: true - } - }); - -### backgroundify - -Module exports `backgroundify` function that takes `nsIDOMWindow` and -removes it from the application's window registry, so that they won't appear -in the OS specific window lists for the application. - - let { backgroundify, open } = require('api-utils/window/utils'); - let bgwin = backgroundify(open('data:text/html,Hello backgroundy')); - -Optionally more configuration options via second `options` argument. If -`options.close` is `false` unregistered window won't automatically -be closed on application quit, preventing application from quitting. While this -is possible you should make sure to close all such windows manually: - - let { backgroundify, open } = require('api-utils/window-utils'); - let bgwin = backgroundify(open('data:text/html,Foo'), { - close: false - }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md deleted file mode 100644 index d0381c0..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md +++ /dev/null @@ -1,95 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Atul Varma [atul@mozilla.com] --> -<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> - -The `xhr` module provides access to `XMLHttpRequest` functionality, also known -as AJAX. - -## Limitations ## - -The `XMLHttpRequest` object is currently fairly limited, and does not -yet implement the `addEventListener()` or `removeEventListener()` -methods. It also doesn't yet implement the `upload` property. - -Furthermore, the `XMLHttpRequest` object does not currently support -the `mozBackgroundRequest` property. All security UI, such as -username/password prompts, are automatically suppressed, so if -required authentication information isn't passed to the `open()` -method, the request will fail. - -## Resource Use ## - -Whenever this module is unloaded, all in-progress requests are immediately -aborted. - -## Security Concerns ## - -By default, the `XMLHttpRequest` object grants full access to any -protocol scheme, which means that it can be used to read from (but not -write to) the host system's entire filesystem. It also has unfettered -access to any local area networks, VPNs, and the internet. - -### Threat Model ### - -The `XMLHttpRequest` object can be used by an add-on to "phone -home" and transmit potentially sensitive user data to third -parties. - -If access to the filesystem isn't prevented, it could easily be used -to access sensitive user data, though this may be inconsequential if -the client can't access the network. - -If access to local area networks isn't prevented, malicious code could access -sensitive data. - -If transmission of cookies isn't prevented, malicious code could access -sensitive data. - -Attenuating access based on a regular expression may be ineffective if -it's easy to write a regular expression that *looks* safe but contains -a special character or two that makes it far less secure than it seems -at first glance. - -### Possible Attenuations ### - -<span class="aside"> -We may also want to consider attenuating further based on domain name -and possibly even restricting the protocol to `https:` only, to reduce -risk. -</span> - -Before being exposed to unprivileged code, this object needs -to be attenuated in such a way that, at the very least, it can't -access the user's filesystem. This can probably be done most securely -by white-listing the protocols that can be used in the URL passed to -the `open()` method, and limiting them to `http:`, `https:`, and -possibly a special scheme that can be used to access the add-on's -packaged, read-only resources. - -Finally, we need to also consider attenuating http/https requests such -that they're "sandboxed" and don't communicate potentially sensitive -cookie information. - -<api name="XMLHttpRequest"> -@class - -<api name="XMLHttpRequest"> -@constructor - Creates an `XMLHttpRequest`. This is a constructor, so its use should always - be preceded by the `new` operator. For more information about - `XMLHttpRequest` objects, see the MDC page on - [Using XMLHttpRequest](https://developer.mozilla.org/En/Using_XMLHttpRequest) - and the Limitations section in this page. -</api> -</api> - -<api name="getRequestCount"> -@function - Returns the number of `XMLHttpRequest` objects that are alive (i.e., currently - active or about to be). -@returns {integer} - The number of live `XMLHttpRequest` objects. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md deleted file mode 100644 index 6d96650..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md +++ /dev/null @@ -1,216 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -Module `xpcom` provides low level API for implementing and registering / -unregistering various XCOM interfaces. - -## Implementing XPCOM interfaces - -Module exports `Unknow` exemplar object, that may be extended to implement -specific XCOM interface(s). For example [nsIObserver] -(https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIObserver) may be -implemented as follows: - - const { Unknown } = require('api-utils/xpcom'); - const { Cc, Ci } = require('chrome') - const observerService = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); - - // Create my observer exemplar - const SleepObserver = Unknown.extend({ - interfaces: [ 'nsIObserver' ], // Interfaces component implements - topic: 'sleep_notification', - initialize: function(fn) { this.fn = fn }, - register: function register() { - observerService.addObserver(this, this.topic, false); - }, - unregister: function() { - addObserver.removeObserver(this, this.topic, false); - }, - observe: function observe(subject, topic, data) { - this.fn({ - subject: subject, - type: topic, - data: data - }); - } - }); - - // create instances of observers - let observer = SleepObserver.new(function(event) { - console.log('Going to sleep!') - }); - // register observer - observer.register(); - -## Implementing XCOM factories - -Module exports `Factory` exemplar, object that may be used to create objects -implementing -[nsIFactory](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIFactory) -interface: - - const { Factory } = require('api-utils/xpcom'); - let Request = Unknown.extend({ - interfaces: [ 'nsIRequest' ], - initialize: function initialize() { - this.pending = false; - // Do some initialization - }, - isPending: function() { return this.pending }, - resume: function() { /* Implementation */ }, - suspend: function() { /* Implementation */ }, - cancel: function() { /* Implementation */ }, - initiate: function() { - this.pending = true; - /* Implementation */ - } - }); - - let requestFactory = Factory.new({ component: Request }); - -Factories registered into a runtime may be accessed from the rest of the -application via standard XPCOM API using factory's auto generated `id` -(optionally you could specify specific `id` by passing it as an option): - - let request = Components.classesByID[requestFactory.id]. - createInstance(Ci.nsIRequest); - request.isPending() // => false - -Be aware that traditional XPCOM API will always return a wrapped JS objects -exposing only properties defined by a given interface (`nsIRequest`) in our -case: - - request.initiate() // TypeError: request.initiate is not a function - -You still can expose unwrapped JS object, by a special `wrappedJSObject` -property of the component: - - let Request = Unknown.extend({ - get wrappedJSObject() this, - interfaces: [ 'nsIRequest' ], - initialize: function initialize() { - this.pending = false; - // Do some initialization - }, - isPending: function() { return this.pending }, - resume: function() { /* Implementation */ }, - suspend: function() { /* Implementation */ }, - cancel: function() { /* Implementation */ }, - initiate: function() { - this.pending = true; - /* Implementation */ - } - }); - - let requestFactory = Factory.new({ component: Request }); - let request = Components.classesByID[requestFactory.id]. - createInstance(Ci.nsIRequest); - request.isPending(); // => false - request.wrappedJSObject.initiate(); - request.isPending(); // => true - -Optionally `Factory.new` may be passed globally unique string in a format of: -`'@domain.com/unique/identifier;1'` as a `contract` option in order to -associate it with it: - - let namedFactory = Factory.new({ - contract: '@examples.com/request/factory;1', - component: Request - }); - -Such factories when registered can be accessed form rest of the application by -human readable `contract` strings: - - let request = Components.classes['@examples.com/request/factory;1']. - createInstance(Components.interfaces.nsIRequest); - -In addition factories associated with a given `contract` may be replaced at -runtime: - - let renewedFactory = Factory.new({ - contract: '@examples.com/request/factory;1', - component: Unknown.extend({ /* Implementation */ }) - }) - -Unfortunately commonly used `Components.classes` won't get updated at runtime -but there is an alternative, more verbose way to access last registered factory -for a given `contract`: - - let id = Components.manager.QueryInterface(Ci.nsIComponentRegistrar). - contractIDToCID('@examples.com/request/factory;1'); - Components.classesByID[requestFactory.id]. - createInstance(Ci.nsISupports); - -Module also exports `factoryByContract` function to simplify this: - - factoryByContract('@examples.com/request/factory;1'). - createInstance(Ci.nsISupports); - -It's also recommended to construct factories with an optional `description` -property, providing human readable description of it: - - let factory = Factory.new({ - contract: '@examples.com/request/factory;1', - description: 'Super duper request factory', - component: Request - }); - -## Registering / Unregistering factories - -All factories created using `Factory.new` get automatically registered into -runtime unless explicitly specified otherwise by setting `register` option to -`false`: - - var factoryToRegister = Factory.new({ - register: false, - component: Unknown.extend({ /* Implementation */ }) - }); - -Such factories still may be registered manually using exported `register` -function: - - const { register } = require('api-utils/xpcom'); - register(factoryToRegister); - -All factories created using `Factory.new` also get unregistered automatically -when add-on is unloaded. This also can be disabled by setting `unregister` -option to `false`. - - var factoryToUnregister = Service.new({ - unregister: false, - component: Unknown.extend({ /* Implementation */ }) - }); - -All registered services may be unregistered at any time using exported -`unregister` function: - - unregister(factoryToUnregister); - -## Implementing XCOM services - -Module exports `Service` exemplar object, that has exact same API as `Factory` -and can be used to register services: - - const { Service } = require('api-utils/xpcom'); - let service = Service.new({ - contract: '@examples/demo/service;1', - description: 'My demo service', - component: Unknown.extend({ - // Implementation - get wrappedJSObject() this - }) - }); - -Registered services can be accessed through the rest of the application via -standard XPCOM API: - - let s = Components.classes['@examples/demo/service;1']. - getService(Components.interfaces.nsISupports); - -In contrast to factories, services do not create instances of enclosed -components, they expose component itself. Also please note that idiomatic way -to work with a service is via `getService` method: - - s.wrappedJSObject === service.component // => true diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md deleted file mode 100644 index 597af56..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md +++ /dev/null @@ -1,76 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> - -The `xul-app` module provides facilities for introspecting the application on -which your program is running. - -With the exception of `ids`, each of these properties exposes the attribute of -the same name on the [`nsIXULAppInfo`][nsIXULAppInfo] interface. For more -information, see the [MDC documentation][]. - -[nsIXULAppInfo]: http://mxr.mozilla.org/mozilla-central/source/xpcom/system/nsIXULAppInfo.idl -[MDC documentation]: https://developer.mozilla.org/en/nsIXULAppInfo - -<api name="ID"> -@property {string} - The GUID of the host application. For example, for Firefox this value is - `"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"`. -</api> - -<api name="name"> -@property {string} - The host application name. For example, `"Firefox"`. -</api> - -<api name="version"> -@property {string} - The host application version. -</api> - -<api name="platformVersion"> -@property {string} - The Gecko/XULRunner platform version. -</api> - -<api name="ids"> -@property {object} - A mapping of application names to their IDs. For example, - `ids["Firefox"] == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"`. -</api> - -<api name="is"> -@function - Checks whether the host application is the given application. -@param name {string} - A host application name. -@returns {boolean} - True if the host application is `name` and false otherwise. -</api> - -<api name="isOneOf"> -@function - Checks whether the host application is one of the given applications. -@param names {array} - An array of host application names. -@returns {boolean} - True if the host application is one of the `names` and false otherwise. -</api> - -<api name="versionInRange"> -@function - Compares a given version to a version range. See the [MDC documentation](https://developer.mozilla.org/en/Toolkit_version_format#Comparing_versions) - for details on version comparisons. -@param version {string} - The version to compare. -@param lowInclusive {string} - The lower bound of the version range to compare. The range includes this - bound. -@param highExclusive {string} - The upper bound of the version range to compare. The range does not include - this bound. -@returns {boolean} - True if `version` falls in the given range and false otherwise. -</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/base.js b/tools/addon-sdk-1.7/packages/api-utils/lib/base.js deleted file mode 100644 index 63acabc..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/base.js +++ /dev/null @@ -1,177 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// Instead of inheriting from `Object.prototype` we copy all interesting -// properties from it and then freeze. This way we can guarantee integrity -// of components build on top. -exports.Base = Object.freeze(Object.create(null, { - toString: { value: Object.prototype.toString }, - toLocaleString: { value: Object.prototype.toLocaleString }, - toSource: { value: Object.prototype.toSource }, - valueOf: { value: Object.prototype.valueOf }, - isPrototypeOf: { value: Object.prototype.isPrototypeOf }, - /** - * Creates an object that inherits from `this` object (Analog of - * `new Object()`). - * @examples - * - * var Dog = Base.extend({ - * bark: function bark() { - * return 'Ruff! Ruff!' - * } - * }); - * var dog = Dog.new(); - */ - new: { value: function create() { - var object = Object.create(this); - object.initialize.apply(object, arguments); - return object; - }}, - /** - * When new instance of the this prototype is created it's `initialize` - * method is called with all the arguments passed to the `new`. You can - * override `initialize` to set up an instance. - */ - initialize: { value: function initialize() { - }}, - /** - * Merges all the properties of the passed objects into `this` instance (This - * method can be used on instances only as prototype objects are frozen). - * - * If two or more argument objects have own properties with the same name, - * the property is overridden, with precedence from right to left, implying, - * that properties of the object on the left are overridden by a same named - * property of the object on the right. - * - * @examples - * - * var Pet = Dog.extend({ - * initialize: function initialize(options) { - * // this.name = options.name -> would have thrown (frozen prototype) - * this.merge(options) // will override all properties. - * }, - * call: function(name) { - * return this.name === name ? this.bark() : '' - * }, - * name: null - * }) - * var pet = Pet.new({ name: 'Benzy', breed: 'Labrador' }) - * pet.call('Benzy') // 'Ruff! Ruff!' - */ - merge: { value: function merge() { - var descriptor = {}; - Array.prototype.forEach.call(arguments, function (properties) { - Object.getOwnPropertyNames(properties).forEach(function(name) { - descriptor[name] = Object.getOwnPropertyDescriptor(properties, name); - }); - }); - Object.defineProperties(this, descriptor); - return this; - }}, - /** - * Takes any number of argument objects and returns frozen, composite object - * that inherits from `this` object and combines all of the own properties of - * the argument objects. (Objects returned by this function are frozen as - * they are intended to be used as types). - * - * If two or more argument objects have own properties with the same name, - * the property is overridden, with precedence from right to left, implying, - * that properties of the object on the left are overridden by a same named - * property of the object on the right. - * @examples - * - * // ## Object composition ## - * - * var HEX = Base.extend({ - * hex: function hex() { - * return '#' + this.color; - * } - * }) - * - * var RGB = Base.extend({ - * red: function red() { - * return parseInt(this.color.substr(0, 2), 16); - * }, - * green: function green() { - * return parseInt(this.color.substr(2, 2), 16); - * }, - * blue: function blue() { - * return parseInt(this.color.substr(4, 2), 16); - * } - * }) - * - * var CMYK = Base.extend(RGB, { - * black: function black() { - * var color = Math.max(Math.max(this.red(), this.green()), this.blue()); - * return (1 - color / 255).toFixed(4); - * }, - * cyan: function cyan() { - * var K = this.black(); - * return (((1 - this.red() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - * }, - * magenta: function magenta() { - * var K = this.black(); - * return (((1 - this.green() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - * }, - * yellow: function yellow() { - * var K = this.black(); - * return (((1 - this.blue() / 255).toFixed(4) - K) / (1 - K)).toFixed(4); - * } - * }) - * - * var Color = Base.extend(HEX, RGB, CMYK, { - * initialize: function Color(color) { - * this.color = color; - * } - * }); - * - * // ## Prototypal inheritance ## - * - * var Pixel = Color.extend({ - * initialize: function Pixel(x, y, hex) { - * Color.initialize.call(this, hex); - * this.x = x; - * this.y = y; - * }, - * toString: function toString() { - * return this.x + ':' + this.y + '@' + this.hex(); - * } - * }); - * - * var pixel = Pixel.new(11, 23, 'CC3399') - * pixel.toString(); // 11:23@#CC3399 - * - * pixel.red(); // 204 - * pixel.green(); // 51 - * pixel.blue(); // 153 - * - * pixel.cyan(); // 0.0000 - * pixel.magenta(); // 0.7500 - * pixel.yellow(); // 0.2500 - * - */ - extend: { value: function extend() { - return Object.freeze(this.merge.apply(Object.create(this), arguments)); - }} -})); - -/** - * Function takes prototype object that implements `initialize` method, and - * returns `constructor` function (with correct prototype property), that can - * be used for simulating classes for given prototypes. - */ -exports.Class = Object.freeze(function Class(prototype) { - function constructor() { - var instance = Object.create(prototype); - prototype.initialize.apply(instance, arguments); - return instance; - } - return Object.freeze(Object.defineProperties(constructor, { - prototype: { value: prototype }, - new: { value: constructor } - })); -}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/channel.js b/tools/addon-sdk-1.7/packages/api-utils/lib/channel.js deleted file mode 100644 index a888af8..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/channel.js +++ /dev/null @@ -1,46 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const { jetpackID } = require('@packaging'); -const { when } = require('./unload'); - -// TODO: Create a bug report and remove this workaround once it's fixed. -// Only function needs defined in the context of the message manager window -// can be registered via `addMessageListener`. -function listener(callee) { - return function listener() { return callee.apply(this, arguments); }; -} -function messageListener(scope, callee) { - return scope ? scope.eval('(' + listener + ')')(callee) : callee -} - -exports.channel = function channel(scope, messageManager, address, raw) { - address = jetpackID + ':' + address - return { - input: function input(next, stop) { - let listener = messageListener(scope, function onMessage(message) { - if (false === next(raw ? message : message.json) && listener) { - messageManager.removeMessageListener(address, listener); - listener = null; - } - }); - messageManager.addMessageListener(address, listener); - - // Bug 724433: do not leak `listener` on addon disabling - when(function () { - if (listener) { - messageManager.removeMessageListener(address, listener); - listener = null; - } - }); - }, - output: function output(data) { - messageManager.sendAsyncMessage(address, data); - }, - sync: !messageManager.sendSyncMessage ? null : function sync(data) { - messageManager.sendSyncMessage(address, data); - } - }; -}; - diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/cuddlefish.js b/tools/addon-sdk-1.7/packages/api-utils/lib/cuddlefish.js deleted file mode 100644 index ac01aee..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/cuddlefish.js +++ /dev/null @@ -1,302 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var EXPORTED_SYMBOLS = [ 'Loader' ]; - -!function(exports) { - -"use strict"; - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, - results: Cr, manager: Cm } = Components; -const systemPrincipal = CC('@mozilla.org/systemprincipal;1', 'nsIPrincipal')(); -const scriptLoader = Cc['@mozilla.org/moz/jssubscript-loader;1']. - getService(Ci.mozIJSSubScriptLoader); - -const Sandbox = { - new: function ({ principal, prototype, name, existingSandbox }) { - let options = { sandboxPrototype: prototype || Sandbox.prototype, - wantXrays: Sandbox.wantXrays }; - if (name) - options.sandboxName = name; - if (existingSandbox) - options.sameGroupAs = existingSandbox.sandbox; - let sandbox = Object.create(Sandbox, { - sandbox: { value: Cu.Sandbox(principal || Sandbox.principal, options) } - }); - // There are few properties (dump, Iterator) that by default appear in - // sandboxes shadowing properties provided by a prototype. To workaround - // this we override all such properties by copying them directly to the - // sandbox. - Object.keys(prototype).forEach(function onEach(key) { - if (sandbox.sandbox[key] !== prototype[key]) - sandbox.sandbox[key] = prototype[key]; - }); - return sandbox; - }, - evaluate: function evaluate(source, uri, lineNumber) { - return Cu.evalInSandbox( - source, - this.sandbox, - this.version, - uri, - lineNumber || this.lineNumber - ); - }, - load: function load(uri) { - scriptLoader.loadSubScript(uri, this.sandbox, 'UTF-8'); - }, - merge: function merge(properties) { - Object.getOwnPropertyNames(properties).forEach(function(name) { - Object.defineProperty(this.sandbox, name, - Object.getOwnPropertyDescriptor(properties, name)); - }, this); - }, - principal: systemPrincipal, - version: '1.8', - lineNumber: 1, - wantXrays: false, - prototype: {} -}; - -// the Module object made available to CommonJS modules when they are -// evaluated, along with 'exports' and 'uri' -const Module = { - new: function(id, path, uri) { - let module = Object.create(this); - - module.id = id; - module.path = path; - module.uri = uri; - module.exports = {}; - - return module; - }, - // TODO: I'd like to remove this, it's not used adds complexity and does - // not has much adoption in commonjs either. - setExports: function setExports(exports) { - this.exports = exports; - } -}; - -const Loader = { - new: function (options) { - let loader = Object.create(Loader, { - // Manifest generated by a linker, containing map of module url's mapped - // to it's requirements, comes from harness-options.json - manifest: { value: options.manifest || {} }, - - // Following property may be passed in (usually for mocking purposes) in - // order to override default modules cache. - modules: { value: options.modules || Object.create(Loader.modules) }, - globals: { value: options.globals || {} }, - - uriPrefix: { value: options.uriPrefix }, - - sandboxes: { value: {} } - }); - loader.require = this.require.bind(loader, options.loader); - - // some 'magic' modules, that have no corresponding .js file - loader.modules['@packaging'] = Object.freeze({ - id: '@packaging', - exports: JSON.parse(JSON.stringify(options)) - }); - loader.modules['@loader'] = Object.freeze({ - exports: Object.freeze({ Loader: Loader }), - id: '@loader' - }); - - // This special module defines globals which will be added to every - // module this loader creates - let globals = loader.require('api-utils/globals!'); - Object.getOwnPropertyNames(globals).forEach(function(name) { - Object.defineProperty(loader.globals, name, - Object.getOwnPropertyDescriptor(globals, name)); - }); - // Freeze globals so that modules won't have a chance to mutate scope of - // other modules. - Object.freeze(globals); - - // Override global `dump` so that it behaves same as in any other module ( - // currently we override dump to write to a file instead of `stdout` so that - // python can read it on windows). - dump = globals.dump; - - return Object.freeze(loader); - }, - modules: { - 'chrome': Object.freeze({ - exports: Object.freeze({ - Cc: Cc, - CC: CC, - Ci: Ci, - Cu: Cu, - Cr: Cr, - Cm: Cm, - components: Components, - messageManager: 'addMessageListener' in exports ? exports : null - }), - id: 'chrome' - }), - 'self': function self(loader, requirer) { - return loader.require('api-utils/self!').create(requirer.path); - }, - }, - - // populate a Module by evaluating the CommonJS module code in the sandbox - load: function load(module) { - let require = Loader.require.bind(this, module.path); - require.main = this.main; - - // Get an existing module sandbox, if any, so we can reuse its compartment - // when creating the new one to reduce memory consumption. - let existingSandbox = [this.sandboxes[p] for (p in this.sandboxes)][0]; - - // XXX Always set "principal" to work around bug 705795, which generates - // 'reference to undefined property "principal"' warnings when the argument - // is deconstructed in the "new" function's parameter list. - // FIXME: stop setting "principal" once bug 705795 is fixed. - let sandbox = this.sandboxes[module.path] = - Sandbox.new({ principal: null, - prototype: this.globals, - name: module.uri, - existingSandbox: existingSandbox }); - sandbox.merge({ - require: require, - module: module, - exports: module.exports - }); - - sandbox.load(module.uri); - - // Workaround for bug 674195. Freezing objects from other sandboxes fail, - // so we create descendant and freeze it instead. - if (typeof(module.exports) === 'object') { - module.exports = Object.prototype.isPrototypeOf(module.exports) ? - Object.freeze(module.exports) : - Object.freeze(Object.create(module.exports)); - } - }, - - // this require() is the main entry point for regular CommonJS modules. The - // bind() in load (above) causes those modules to get a very restricted - // form of this require(): one which can only ever reference this one - // loader, and which always uses their URI as a "base" (so they're limited - // to their own manifest entries, and can't import anything off the - // manifest). - require: function require(base, id) { - let module, manifest = this.manifest[base], requirer = this.modules[base]; - - if (!id) - throw Error("you must provide a module name when calling require() from " - + (requirer && requirer.id), base, id); - - // If we have a manifest for requirer, then all it's requirements have been - // registered by linker and we should have a `path` to the required module. - // Even pseudo-modules like 'chrome', 'self', '@packaging', and '@loader' - // have pseudo-paths: exactly those same names. - // details see: Bug-697422. - let requirement = manifest && manifest.requirements[id]; - if (!requirement) - throw Error("Module: " + (requirer && requirer.id) + ' located at ' + - base + " has no authority to load: " + id); - let path = requirement.path; - - if (path in this.modules) { - module = this.modules[path]; - } - else { - let uri = this.uriPrefix + path; - module = this.modules[path] = Module.new(id, path, uri); - this.load(module); - Object.freeze(module); - } - - // "magic" modules which have contents that depend upon who imports them - // (like "self") are expressed in the Loader's pre-populated 'modules' - // table as callable functions, which are given the reference to this - // Loader and a copy of the importer's URI - // - // TODO: Find a better way to implement `self`. - // Maybe something like require('self!path/to/data') - if (typeof(module) === 'function') - module = module(this, requirer); - - return module.exports; - }, - - // process.process() will eventually cause a call to main() to be evaluated - // in the addon's context. This function loads and executes the addon's - // entry point module. - main: function main(id, path) { - try { - let uri = this.uriPrefix + path; - let module = this.modules[path] = Module.new(id, path, uri); - this.load(module); // this is where the addon's main.js finally runs - let program = Object.freeze(module).exports; - - if (typeof(program.onUnload) === 'function') - this.require('api-utils/unload').when(program.onUnload); - - if (program.main) { - let { exit, staticArgs } = this.require('api-utils/system'); - let { loadReason } = this.require('@packaging'); - program.main({ loadReason: loadReason, staticArgs: staticArgs }, - { print: function($) dump($ + '\n'), quit: exit }); - } - } catch (error) { - Cu.reportError(error); - if (this.globals.console) this.globals.console.exception(error); - throw error; - } - }, - - // This is the main entry-point: bootstrap.js calls this when the add-on is - // installed. The order of calls is a bit confusing, but here's what - // happens (in temporal order): - // * process.spawn creates a new XUL 'browser' element which will house the - // main addon code. When e10s is active, this uses a real separate OS - // process. When e10s is disabled, this element lives in the one original - // process. Either way, its API is the same. - // * Grab the channel named "require!" and attach a handler which will load - // modules (in the chrome process) when requested to by the addon - // process. This handler uses Loader.require to import the module, then - // calls the module's .initialize() function to connect a new channel. - // The remote caller winds up with a channel reference, which they can - // use to send messages to the newly loaded module. This is for e10s. - // * After the channel handler is attached, process.process() (invoked by - // process.spawn()) will use loadScript() to evaluate code in the - // 'browser' element (which is where the main addon code starts running), - // to do the following: - // * create a Loader, initialized with the same manifest and - // harness-options.json that we've got - // * invoke it's main() method, with the name and path of the addon's - // entry module (which comes from linker via harness-options.js, and is - // usually main.js). That executes main(), above. - // * main() loads the addon's main.js, which executes all top-level - // forms. If the module defines an "exports.main=" function, we invoke - // that too. This is where the addon finally gets to run. - spawn: function spawn(id, path) { - let loader = this; - let process = this.require('api-utils/process'); - process.spawn(id, path)(function(addon) { - // Listen to `require!` channel's input messages from the add-on process - // and load modules being required. - addon.channel('require!').input(function({ requirer: { path }, id }) { - try { - Loader.require.call(loader, path, id).initialize(addon.channel(id)); - } catch (error) { - this.globals.console.exception(error); - } - }); - }); - }, - unload: function unload(reason, callback) { - this.require('api-utils/unload').send(reason, callback); - } -}; -exports.Loader = Loader; - -}(this); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/env!.js b/tools/addon-sdk-1.7/packages/api-utils/lib/env!.js deleted file mode 100644 index f7144ad..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/env!.js +++ /dev/null @@ -1,20 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const { messageManager } = require("chrome"); -const { channel } = require("./channel"); - -module.exports = function load(module) { - return { - require: function require(id) { - // Load required module on the chrome process. - channel(messageManager, messageManager, 'require!').sync({ - requirer: module, - id: id - }); - return channel(messageManager, messageManager, id); - } - }; -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/globals!.js b/tools/addon-sdk-1.7/packages/api-utils/lib/globals!.js deleted file mode 100644 index 01e85b7..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/globals!.js +++ /dev/null @@ -1,93 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -let { Cc, Ci } = require('chrome'); -let { PlainTextConsole } = require('./plain-text-console'); -let options = require('@packaging'); -let consoleService = Cc['@mozilla.org/consoleservice;1'].getService(). - QueryInterface(Ci.nsIConsoleService); - -// On windows dump does not writes into stdout so cfx can't read thous dumps. -// To workaround this issue we write to a special file from which cfx will -// read and print to the console. -// For more details see: bug-673383 -exports.dump = (function define(global) { - const PR_WRONLY = 0x02; - const PR_CREATE_FILE = 0x08; - const PR_APPEND = 0x10; - let print = Object.getPrototypeOf(global).dump - if (print) return print; - if ('logFile' in options) { - let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); - file.initWithPath(options.logFile); - let stream = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); - stream.init(file, PR_WRONLY|PR_CREATE_FILE|PR_APPEND, -1, 0); - - return function print(message) { - message = String(message); - stream.write(message, message.length); - stream.flush(); - }; - } - return dump; -})(this); - -// Override the default Iterator function with one that passes -// a second argument to custom iterator methods that identifies -// the call as originating from an Iterator function so the custom -// iterator method can return [key, value] pairs just like default -// iterators called via the default Iterator function. -exports.Iterator = (function(DefaultIterator) { - return function Iterator(obj, keysOnly) { - if ("__iterator__" in obj && !keysOnly) - return obj.__iterator__.call(obj, false, true); - return DefaultIterator(obj, keysOnly); - }; -})(Iterator); - -// Bug 718230: We need to send console messages to stdout and JS Console -function forsakenConsoleDump(msg, level) { - exports.dump(msg); - - if (level === "error") { - let err = Cc["@mozilla.org/scripterror;1"]. - createInstance(Ci.nsIScriptError); - msg = msg.replace(/^error: /, ""); - err.init(msg, null, null, 0, 0, 0, "Add-on SDK"); - consoleService.logMessage(err); - } - else - consoleService.logStringMessage(msg); -}; -exports.console = new PlainTextConsole(forsakenConsoleDump); - -// Provide CommonJS `define` to allow authoring modules in a format that can be -// loaded both into jetpack and into browser via AMD loaders. -Object.defineProperty(exports, 'define', { - // `define` is provided as a lazy getter that binds below defined `define` - // function to the module scope, so that require, exports and module - // variables remain accessible. - configurable: true, - get: (function() { - function define(factory) { - factory = Array.slice(arguments).pop(); - factory.call(this, this.require, this.exports, this.module); - } - - return function getter() { - // Redefine `define` as a static property to make sure that module - // gets access to the same function so that `define === define` is - // `true`. - Object.defineProperty(this, 'define', { - configurable: false, - value: define.bind(this) - }); - return this.define; - } - })() -}); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/message-manager.js b/tools/addon-sdk-1.7/packages/api-utils/lib/message-manager.js deleted file mode 100644 index 235586f..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/message-manager.js +++ /dev/null @@ -1,203 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const BAD_LISTENER = "The event listener must be a function."; - -const { Cc, Ci, Cu, CC } = require("chrome"); -const { setTimeout } = require("./timer"); - -const { ns } = require("./namespace"); - -const { curry, invoke } = require("./functional"); - -const Sandbox = require("./sandbox"); - -// JSON.stringify is buggy with cross-sandbox values, -// it may return "{}" on functions. Use a replacer to match them correctly. -const jsonFixer = function (k, v) typeof v === "function" ? undefined : v; - -/** - * Defers invoking the function until the current call stack has cleared. - * - * @param {Function} fn - * The function to defer. - * - * @returns {Function} - * The deferred function - */ -const defer = function(fn) function() { - setTimeout(invoke, 0, fn, arguments, this) -}; - -/** - * Adds a message listener. - * This listener will receive messages sent from the remote frame. - * - * @param {String} name - * The name of the message for which to add a listener. - * @param {Function} listener - * The listener function called when the message is received. - */ -function addMessageListener(name, listener) { - if (typeof listener !== "function") - throw new Error(BAD_LISTENER); - - let listeners = frame(this).listeners; - - if (name in listeners) { - if (~listeners[name].indexOf(listener)) - return; - } else { - listeners[name] = []; - } - - listeners[name].push(listener); -} - -/** - * Removes a message listener previously added by calling addMessageListener. - * - * @param {String} name - * The name of the message for which to remove a listener. - * @param {Function} listener - * The listener function has to be removed. - */ -function removeMessageListener(name, listener) { - if (typeof listener !== "function") - throw new Error(BAD_LISTENER); - - let listeners = frame(this).listeners; - - if (!(name in listeners)) - return; - - let index = listeners[name].indexOf(listener); - - if (~index) { - listeners[name].splice(index, 1); - } -} - -/** - * Sends a message to the listeners. - * - * @param {Boolean} sync - * Indicates if the call is synchronous or asynchronous - * @param {String} name - * The name of the message to send to the listeners. - * @param {Object} [data=null] - * A JSON object containing data to be delivered to the listeners. - * - * @returns {Array|undefined} - * An array with the return values of the listeners if `sync` is `true`, - * otherwise `undefined`. - */ -function sendMessage(sync, name, data) { - typeof data === "undefined" && (data = null); - - let listeners = frame(frame(this).receiver).listeners; - - let responses = []; - - let returnValue = sync ? responses : undefined; - - if (!(name in listeners)) - return returnValue; - - let json = JSON.parse(JSON.stringify(data, jsonFixer)); - - for each(let listener in listeners[name]) { - try { - let response = listener.call(null, { - sync : sync, - name : name, - json : json, - target : null - }); - - if (sync) { - if (typeof response === "undefined") - responses.push(response); - else - responses.push(JSON.parse(JSON.stringify(response, jsonFixer))); - } - - } catch (e) { - console.exception(e); - } - } - return returnValue; -}; - -let sendSyncMessage = curry(sendMessage, true); -let sendAsyncMessage = curry(defer(sendMessage), false); - -let frame = ns({receiver: null, listeners: null}); - -/** - * The MessageManager object emulates the Message Manager API, without creating - * new processes. It useful in mono process context, like Fennec. - * - * @see - * https://developer.mozilla.org/en/The_message_manager - */ -function MessageManager() { - - let sandbox = Sandbox.sandbox(null, { wantXrays : false }); - - Object.defineProperties(sandbox, { - addMessageListener: {value: addMessageListener.bind(sandbox)}, - - removeMessageListener: { value: removeMessageListener.bind(sandbox)}, - - sendAsyncMessage: {value: sendAsyncMessage.bind(sandbox)}, - - sendSyncMessage: { value: sendSyncMessage.bind(sandbox) } - }); - - frame(this).receiver = sandbox; - frame(sandbox).receiver = this; - - frame(this).listeners = {}; - frame(sandbox).listeners = {}; -} - -MessageManager.prototype = { - constructor: MessageManager, - - addMessageListener : addMessageListener, - - removeMessageListener : removeMessageListener, - - sendAsyncMessage : sendAsyncMessage, - - /** - * Loads a script into the remote frame. - * - * @param {String} uri - * The URL of the script to load into the frame; this must be an absolute - * local URL, but data: URLs are supported. - * @param {Boolean} allowDelayedLoad - * Not used. - */ - loadFrameScript: function loadFrameScript(uri, async) { - if (arguments.length < loadFrameScript.length) - throw new Error("Not enough arguments"); - - let sandbox = frame(this).receiver; - - try { - Sandbox.load(sandbox, uri); - } catch (e) { - console.exception(e) - } - } -} - -Object.freeze(MessageManager); -Object.freeze(MessageManager.prototype); - -exports.MessageManager = MessageManager; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/namespace.js b/tools/addon-sdk-1.7/packages/api-utils/lib/namespace.js deleted file mode 100644 index 612910d..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/namespace.js +++ /dev/null @@ -1,43 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// This is a temporary workaround until bug 673468 is fixed, which causes -// entries associated with `XPCWrappedNative` wrapped keys to be GC-ed. To -// workaround that we create a cross reference with an object from the same -// compartment as `WeakMap` and use that as a key. Cross reference prevents -// wrapper to be GC-ed until reference to it's value is kept. -function handle(target) { - return target[handle.key] || Object.defineProperty(target, handle.key, { - value: { '::': target }, - enumerable: false, - configurable: false, - writable: false - })[handle.key]; -} -handle.key = '::ns::' + Math.round(Math.random() * 100000000000000000); - -/** - * Function creates a new namespace. Optionally `prototype` object may be - * passed, in which case namespace objects will inherit from it. Returned value - * is a function that can be used to get access to the namespaced properties - * for the passed object. - * @examples - * const ns = Namespace(); - * ns(myObject).secret = secret; - */ -exports.Namespace = function Namespace(prototype) { - prototype = prototype || Object.prototype; - const map = new WeakMap(); - return function namespace(target) { - let key = handle(target); - return map.get(key) || - map.set(key, Object.create(prototype)), map.get(key); - }; -}; - -// `Namespace` is a e4x function in the scope, so we export the function also as -// `ns` as alias to avoid clashing. -exports.ns = exports.Namespace; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/observer-service.js b/tools/addon-sdk-1.7/packages/api-utils/lib/observer-service.js deleted file mode 100644 index 04222c7..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/observer-service.js +++ /dev/null @@ -1,175 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Cc, Ci } = require("chrome"); -const { Unknown } = require("./xpcom"); -const { when: unload } = require("./unload"); -const memory = require("./memory"); - - -/** - * A service for adding, removing and notifying observers of notifications. - * Wraps the nsIObserverService interface. - * - * @version 0.2 - */ - -var service = Cc["@mozilla.org/observer-service;1"]. - getService(Ci.nsIObserverService); - -/** - * A cache of observers that have been added. - * - * We use this to remove observers when a caller calls |Observers.remove|. - */ -var cache = []; - -/** - * Topics specifically available to Jetpack-generated extensions. - * - * Using these predefined consts instead of the platform strings is good: - * - allows us to scope topics specifically for Jetpacks - * - addons aren't dependent on strings nor behavior of core platform topics - * - the core platform topics are not clearly named - * - */ -exports.topics = { - /** - * A topic indicating that the application is in a state usable - * by add-ons. - */ - get APPLICATION_READY() packaging.jetpackID + "_APPLICATION_READY" -}; - -/** - * Register the given callback as an observer of the given topic. - * - * @param topic {String} - * the topic to observe - * - * @param callback {Object} - * the callback; an Object that implements nsIObserver or a Function - * that gets called when the notification occurs - * - * @param target {Object} [optional] - * the object to use as |this| when calling a Function callback - * - * @returns the observer - */ -var add = exports.add = function add(topic, callback, target) { - var observer = Observer.new(topic, callback, target); - service.addObserver(observer, topic, true); - cache.push(observer); - - return observer; -}; - -/** - * Unregister the given callback as an observer of the given topic. - * - * @param topic {String} - * the topic being observed - * - * @param callback {Object} - * the callback doing the observing - * - * @param target {Object} [optional] - * the object being used as |this| when calling a Function callback - */ -var remove = exports.remove = function remove(topic, callback, target) { - // This seems fairly inefficient, but I'm not sure how much better - // we can make it. We could index by topic, but we can't index by callback - // or target, as far as I know, since the keys to JavaScript hashes - // (a.k.a. objects) can apparently only be primitive values. - let observers = cache.filter(function(v) { - return (v.topic == topic && - v.callback == callback && - v.target == target); - }); - - if (observers.length) { - service.removeObserver(observers[0], topic); - cache.splice(cache.indexOf(observers[0]), 1); - } -}; - -/** - * Notify observers about something. - * - * @param topic {String} - * the topic to notify observers about - * - * @param subject {Object} [optional] - * some information about the topic; can be any JS object or primitive - * - * @param data {String} [optional] [deprecated] - * some more information about the topic; deprecated as the subject - * is sufficient to pass all needed information to the JS observers - * that this module targets; if you have multiple values to pass to - * the observer, wrap them in an object and pass them via the subject - * parameter (i.e.: { foo: 1, bar: "some string", baz: myObject }) - */ -var notify = exports.notify = function notify(topic, subject, data) { - subject = (typeof subject == "undefined") ? null : Subject.new(subject); - data = (typeof data == "undefined") ? null : data; - service.notifyObservers(subject, topic, data); -}; - -const Observer = Unknown.extend({ - initialize: function initialize(topic, callback, target) { - memory.track(this); - this.topic = topic; - this.callback = callback; - this.target = target; - }, - interfaces: [ 'nsIObserver', 'nsISupportsWeakReference' ], - observe: function(subject, topic, data) { - // Extract the wrapped object for subjects that are one of our - // wrappers around a JS object. This way we support both wrapped - // subjects created using this module and those that are real - // XPCOM components. - if (subject && typeof subject == "object" && - ("wrappedJSObject" in subject) && - ("observersModuleSubjectWrapper" in subject.wrappedJSObject)) - subject = subject.wrappedJSObject.object; - - try { - if (typeof this.callback == "function") { - if (this.target) - this.callback.call(this.target, subject, data); - else - this.callback(subject, data); - } else // typeof this.callback == "object" (nsIObserver) - this.callback.observe(subject, topic, data); - } catch (e) { - console.exception(e); - } - } -}); - -const Subject = Unknown.extend({ - initialize: function initialize(object) { - // Double-wrap the object and set a property identifying the - // wrappedJSObject as one of our wrappers to distinguish between - // subjects that are one of our wrappers (which we should unwrap - // when notifying our observers) and those that are real JS XPCOM - // components (which we should pass through unaltered). - this.wrappedJSObject = { - observersModuleSubjectWrapper: true, - object: object - }; - }, - getHelperForLanguage: function() {}, - getInterfaces: function() {} -}); - -unload(function() { - // Make a copy of cache first, since cache will be changing as we - // iterate through it. - cache.slice().forEach(function({ topic, callback, target }) { - remove(topic, callback, target); - }); -}) diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/process.js b/tools/addon-sdk-1.7/packages/api-utils/lib/process.js deleted file mode 100644 index 68ef2f9..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/process.js +++ /dev/null @@ -1,76 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Cc, Ci } = require("chrome"); -const { createRemoteBrowser } = require("api-utils/window-utils"); -const { channel } = require("./channel"); -const packaging = require('@packaging'); -const { when } = require('./unload'); -const { MessageManager } = require('./message-manager'); - -const addonService = '@mozilla.org/addon/service;1' in Cc ? - Cc['@mozilla.org/addon/service;1'].getService(Ci.nsIAddonService) : null - -const ENABLE_E10S = packaging.enable_e10s; - -const isFennec = require("./xul-app").is("Fennec"); - -function loadScript(target, uri, sync) { - return 'loadScript' in target ? target.loadScript(uri, sync) - : target.loadFrameScript(uri, sync) -} - -function process(target, id, path, scope) { - // Please note that even though `loadScript`, is executed before channel is - // returned, users still are able to subscribe for messages before any message - // will be sent. That's because `loadScript` queues script execution on the - // other process, which means they will execute async (on the next turn of - // event loop), while the channel for messages is returned immediately (in - // the same turn of event loop). - - let load = loadScript.bind(null, target); - - load(packaging.uriPrefix + packaging.loader, false); - load('data:,' + encodeURIComponent( - 'let loader = Loader.new(' + JSON.stringify(packaging) + ');\n' + - 'loader.main("' + id + '", "' + path + '");'), false); - - when(function (reason) { - // Please note that it's important to unload remote loader - // synchronously (using synchronous frame script), to make sure that we - // don't stop during unload. - // Bug 724433: Take care to nullify all globals set by `cuddlefish.js` - // otherwise, we will leak any still defined global. - // `dump` is set in Loader.new method, `dump = globals.dump;` - load('data:,loader.unload("' + reason + '");' + - 'loader = null; Loader = null; dump = null;', true); - }); - - return { - channel: channel.bind(null, scope, target), - loadScript: load - }; -} - -exports.spawn = function spawn(id, path) { - return function promise(deliver) { - // If `nsIAddonService` is available we use it to create an add-on process, - // otherwise we fallback to the remote browser's message manager. - if (ENABLE_E10S && addonService) { - console.log('!!!!!!!!!!!!!!!!!!!! Using addon process !!!!!!!!!!!!!!!!!!'); - deliver(process(addonService.createAddon(), id, path)); - } else if (isFennec) { - deliver(process(new MessageManager(), id, path)); - } else { - createRemoteBrowser(ENABLE_E10S)(function(browser) { - let messageManager = browser.QueryInterface(Ci.nsIFrameLoaderOwner). - frameLoader.messageManager - let window = browser.ownerDocument.defaultView; - deliver(process(messageManager, id, path, window)); - }); - } - }; -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/self!.js b/tools/addon-sdk-1.7/packages/api-utils/lib/self!.js deleted file mode 100644 index fd69f9a..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/self!.js +++ /dev/null @@ -1,48 +0,0 @@ -/* vim:st=2:sts=2:sw=2: - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { CC } = require('chrome'); -const { jetpackID, name, manifest, metadata, uriPrefix } = require('@packaging'); - -const XMLHttpRequest = CC('@mozilla.org/xmlextras/xmlhttprequest;1', - 'nsIXMLHttpRequest'); - -// Utility function that synchronously reads local resource from the given -// `uri` and returns content string. -function readURI(uri) { - let request = XMLHttpRequest(); - request.open('GET', uri, false); - request.overrideMimeType('text/plain'); - request.send(); - return request.responseText; -} - -// Some XPCOM APIs require valid URIs as an argument for certain operations (see -// `nsILoginManager` for example). This property represents add-on associated -// unique URI string that can be used for that. -const uri = 'addon:' + jetpackID - -function url(root, path) root + (path || "") -function read(root, path) readURI(url(root, path)) - -exports.create = function create(base) { - let moduleData = manifest[base] && manifest[base].requirements['self']; - let root = uriPrefix + moduleData.dataURIPrefix; - return Object.freeze({ - id: 'self', - exports: Object.freeze({ - id: jetpackID, - uri: uri, - name: name, - version: metadata[name].version, - data: { - url: url.bind(null, root), - load: read.bind(null, root) - } - }) - }); -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/utils.js b/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/utils.js deleted file mode 100644 index 1c411dc..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/tabs/utils.js +++ /dev/null @@ -1,59 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -function getTabContainer(tabBrowser) { - return tabBrowser.tabContainer; -} -exports.getTabContainer = getTabContainer; - -function getTabBrowsers(window) { - return Array.slice(window.document.getElementsByTagName("tabbrowser")); -} -exports.getTabBrowsers = getTabBrowsers; - -function getTabContainers(window) { - return getTabBrowsers(window).map(getTabContainer); -} -exports.getTabContainers = getTabContainers; - -function getTabs(window) { - return getTabContainers(window).reduce(function (tabs, container) { - tabs.push.apply(tabs, container.children); - return tabs; - }, []); -} -exports.getTabs = getTabs; - -function getActiveTab(window) { - return window.gBrowser.selectedTab; -} -exports.getActiveTab = getActiveTab; - -function getOwnerWindow(tab) { - return tab.ownerDocument.defaultView; -} -exports.getOwnerWindow = getOwnerWindow; - -function openTab(window, url) { - return window.gBrowser.addTab(url); -} -exports.openTab = openTab; - -function isTabOpen(tab) { - return !!tab.linkedBrowser; -} -exports.isTabOpen = isTabOpen; - -function closeTab(tab) { - return getOwnerWindow(tab).gBrowser.removeTab(tab); -} -exports.closeTab = closeTab; - -function activateTab(tab) { - getOwnerWindow(tab).gBrowser.selectedTab = tab; -} -exports.activateTab = activateTab; diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/timer.js b/tools/addon-sdk-1.7/packages/api-utils/lib/timer.js deleted file mode 100644 index 55654a8..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/timer.js +++ /dev/null @@ -1,78 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { CC } = require("chrome"); -const { Unknown } = require("./xpcom"); -const { when: unload } = require("./unload"); - -const Timer = CC('@mozilla.org/timer;1', 'nsITimer'); - -// Registry for all timers. -const timers = (function(map, id) { - return Object.defineProperties(function registry(key, fallback) { - return key in map ? map[key] : fallback; - }, { - register: { value: function(value) (map[++id] = value, id) }, - unregister: { value: function(key) delete map[key] }, - forEach: { value: function(callback) Object.keys(map).forEach(callback) } - }); -})(Object.create(null), 0); - -const TimerCallback = Unknown.extend({ - interfaces: [ 'nsITimerCallback' ], - initialize: function initialize(id, callback, rest) { - this.id = id; - this.callback = callback; - this.arguments = rest; - } -}); - -const TimeoutCallback = TimerCallback.extend({ - type: 0, // nsITimer.TYPE_ONE_SHOT - notify: function notify() { - try { - timers.unregister(this.id); - this.callback.apply(null, this.arguments); - } - catch (error) { - console.exception(error); - } - } -}); - -const IntervalCallback = TimerCallback.extend({ - type: 1, // nsITimer.TYPE_REPEATING_SLACK - notify: function notify() { - try { - this.callback.apply(null, this.arguments); - } - catch (error) { - console.exception(error); - } - } -}); - -function setTimer(TimerCallback, listener, delay) { - let timer = Timer(); - let id = timers.register(timer); - let callback = TimerCallback.new(id, listener, Array.slice(arguments, 3)); - timer.initWithCallback(callback, delay || 0, TimerCallback.type); - return id; -} - -function unsetTimer(id) { - let timer = timers(id); - timers.unregister(id); - if (timer) - timer.cancel(); -} - -exports.setTimeout = setTimer.bind(null, TimeoutCallback); -exports.setInterval = setTimer.bind(null, IntervalCallback); -exports.clearTimeout = unsetTimer; -exports.clearInterval = unsetTimer; - -unload(function() { timers.forEach(unsetTimer); }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/lib/window-utils.js b/tools/addon-sdk-1.7/packages/api-utils/lib/window-utils.js deleted file mode 100644 index bd2f2d5..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/lib/window-utils.js +++ /dev/null @@ -1,278 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Cc, Ci } = require("chrome"); -const { EventEmitter } = require('./events'), - { Trait } = require('./traits'); -const { when } = require('./unload'); -const { getInnerId, getOuterId } = require('./window-utils'); -const errors = require("./errors"); - -const windowWatcher = Cc["@mozilla.org/embedcomp/window-watcher;1"]. - getService(Ci.nsIWindowWatcher); -const appShellService = Cc["@mozilla.org/appshell/appShellService;1"]. - getService(Ci.nsIAppShellService); -const observers = require('api-utils/observer-service'); - - -const XUL = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; - -/** - * An iterator for XUL windows currently in the application. - * - * @return A generator that yields XUL windows exposing the - * nsIDOMWindow interface. - */ -function windowIterator() { - let winEnum = windowWatcher.getWindowEnumerator(); - while (winEnum.hasMoreElements()) - yield winEnum.getNext().QueryInterface(Ci.nsIDOMWindow); -}; -exports.windowIterator = windowIterator; - -/** - * An iterator for browser windows currently open in the application. - * @returns {Function} - * A generator that yields browser windows exposing the `nsIDOMWindow` - * interface. - */ -function browserWindowIterator() { - for each (let window in windowIterator()) { - if (isBrowser(window)) - yield window; - } -} -exports.browserWindowIterator = browserWindowIterator; - -function WindowTracker(delegate) { - if (!(this instanceof WindowTracker)) { - return new WindowTracker(delegate); - } - - this._delegate = delegate; - this._loadingWindows = []; - - for (let window in windowIterator()) - this._regWindow(window); - windowWatcher.registerNotification(this); - - require("./unload").ensure(this); - - return this; -}; - -WindowTracker.prototype = { - _regLoadingWindow: function _regLoadingWindow(window) { - this._loadingWindows.push(window); - window.addEventListener("load", this, true); - }, - - _unregLoadingWindow: function _unregLoadingWindow(window) { - var index = this._loadingWindows.indexOf(window); - - if (index != -1) { - this._loadingWindows.splice(index, 1); - window.removeEventListener("load", this, true); - } - }, - - _regWindow: function _regWindow(window) { - if (window.document.readyState == "complete") { - this._unregLoadingWindow(window); - this._delegate.onTrack(window); - } else - this._regLoadingWindow(window); - }, - - _unregWindow: function _unregWindow(window) { - if (window.document.readyState == "complete") { - if (this._delegate.onUntrack) - this._delegate.onUntrack(window); - } else { - this._unregLoadingWindow(window); - } - }, - - unload: function unload() { - windowWatcher.unregisterNotification(this); - for (let window in windowIterator()) - this._unregWindow(window); - }, - - handleEvent: errors.catchAndLog(function handleEvent(event) { - if (event.type == "load" && event.target) { - var window = event.target.defaultView; - if (window) - this._regWindow(window); - } - }), - - observe: errors.catchAndLog(function observe(subject, topic, data) { - var window = subject.QueryInterface(Ci.nsIDOMWindow); - if (topic == "domwindowopened") - this._regWindow(window); - else - this._unregWindow(window); - }) -}; -exports.WindowTracker = WindowTracker; - -const WindowTrackerTrait = Trait.compose({ - _onTrack: Trait.required, - _onUntrack: Trait.required, - constructor: function WindowTrackerTrait() { - WindowTracker({ - onTrack: this._onTrack.bind(this), - onUntrack: this._onUntrack.bind(this) - }); - } -}); -exports.WindowTrackerTrait = WindowTrackerTrait; - -var gDocsToClose = []; - -function onDocUnload(event) { - var index = gDocsToClose.indexOf(event.target); - if (index == -1) - throw new Error("internal error: unloading document not found"); - var document = gDocsToClose.splice(index, 1)[0]; - // Just in case, let's remove the event listener too. - document.defaultView.removeEventListener("unload", onDocUnload, false); -} - -onDocUnload = require("./errors").catchAndLog(onDocUnload); - -exports.closeOnUnload = function closeOnUnload(window) { - window.addEventListener("unload", onDocUnload, false); - gDocsToClose.push(window.document); -}; - -Object.defineProperties(exports, { - activeWindow: { - enumerable: true, - get: function() { - return Cc["@mozilla.org/appshell/window-mediator;1"] - .getService(Ci.nsIWindowMediator) - .getMostRecentWindow(null); - }, - set: function(window) { - try { window.focus(); } catch (e) { } - } - }, - activeBrowserWindow: { - enumerable: true, - get: function() { - return Cc["@mozilla.org/appshell/window-mediator;1"] - .getService(Ci.nsIWindowMediator) - .getMostRecentWindow("navigator:browser"); - } - } -}); - - -/** - * Returns the ID of the window's current inner window. - */ -exports.getInnerId = function(window) { - console.warn('require("window-utils").getInnerId is deprecated, ' + - 'please use require("window/utils").getInnerId instead'); - return getInnerId(window); -}; - -exports.getOuterId = function(window) { - console.warn('require("window-utils").getOuterId is deprecated, ' + - 'please use require("window/utils").getOuterId instead'); - return getOuterId(window); -}; - -function isBrowser(window) { - return window.document.documentElement.getAttribute("windowtype") === - "navigator:browser"; -}; -exports.isBrowser = isBrowser; - -exports.hiddenWindow = appShellService.hiddenDOMWindow; - -function createHiddenXULFrame() { - return function promise(deliver) { - let window = appShellService.hiddenDOMWindow; - - // Ensuring waiting for hidden window end of loading - // (The hidden window is still loading on windows/thunderbird) - if (window.document.readyState != "complete") { - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, false); - // We recurse with same arguments, when the window is ready - promise(deliver); - }, false); - return; - } - - let document = window.document; - let isXMLDoc = (document.contentType == "application/xhtml+xml" || - document.contentType == "application/vnd.mozilla.xul+xml") - - if (isXMLDoc) { - deliver(window) - } - else { - let frame = document.createElement('iframe'); - // This is ugly but we need window for XUL document in order to create - // browser elements. - - // See bug 725323: hiddenWindow URL is different on each mozilla product - let prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefBranch); - let hiddenWindowURL = prefs.getCharPref("browser.hiddenWindowChromeURL", ""); - - frame.src = hiddenWindowURL; - frame.setAttribute('src', hiddenWindowURL); - frame.addEventListener('DOMContentLoaded', function onLoad(event) { - frame.removeEventListener('DOMContentLoaded', onLoad, false); - deliver(frame.contentWindow); - }, false); - document.documentElement.appendChild(frame); - } - } -}; -exports.createHiddenXULFrame = createHiddenXULFrame; - -function createRemoteBrowser(remote) { - return function promise(deliver) { - createHiddenXULFrame()(function(hiddenWindow) { - let document = hiddenWindow.document; - let browser = document.createElementNS(XUL, "browser"); - // Remote="true" enable everything here: - // http://mxr.mozilla.org/mozilla-central/source/content/base/src/nsFrameLoader.cpp#1347 - if (remote !== false) - browser.setAttribute("remote","true"); - // Type="content" is mandatory to enable stuff here: - // http://mxr.mozilla.org/mozilla-central/source/content/base/src/nsFrameLoader.cpp#1776 - browser.setAttribute("type","content"); - // We remove XBL binding to avoid execution of code that is not going to work - // because browser has no docShell attribute in remote mode (for example) - browser.setAttribute("style","-moz-binding: none;"); - // Flex it in order to be visible (optional, for debug purpose) - browser.setAttribute("flex", "1"); - document.documentElement.appendChild(browser); - - // Bug 724433: do not leak this <browser> DOM node - when(function () { - document.documentElement.removeChild(browser); - }); - - // Return browser - deliver(browser); - }); - }; -}; -exports.createRemoteBrowser = createRemoteBrowser; - -require("./unload").when( - function() { - gDocsToClose.slice().forEach( - function(doc) { doc.defaultView.close(); }); - }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/package.json b/tools/addon-sdk-1.7/packages/api-utils/package.json deleted file mode 100644 index 1e777fe..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "api-utils", - "description": "Foundational infrastructure and utilities.", - "keywords": ["javascript", "engine", "platform", "xulrunner", - "jetpack-low-level"], - "author": "Atul Varma (http://toolness.com/) <atul@mozilla.com>", - "contributors": [ - "Myk Melez (http://melez.com/) <myk@mozilla.org>", - "Daniel Aquino <mr.danielaquino@gmail.com>" - ], - "license": "MPL 2.0", - "dependencies": ["addon-kit"], - "loader": "lib/cuddlefish.js" -} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/helpers.js b/tools/addon-sdk-1.7/packages/api-utils/tests/helpers.js deleted file mode 100644 index c639849..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/helpers.js +++ /dev/null @@ -1,24 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Loader } = require("@loader"); - -exports.Loader = function(module, globals, packaging) { - var options = packaging || JSON.parse(JSON.stringify(require("@packaging"))); - options.globals = globals; - - let loader = Loader.new(options); - return Object.create(loader, { - require: { value: Loader.require.bind(loader, module.path) }, - sandbox: { value: function sandbox(id) { - let path = options.manifest[module.path].requirements[id].path; - return loader.sandboxes[path].sandbox; - }}, - unload: { value: function unload(reason, callback) { - loader.unload(reason, callback); - }} - }) -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-base.js b/tools/addon-sdk-1.7/packages/api-utils/tests/test-base.js deleted file mode 100644 index e97b8b0..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-base.js +++ /dev/null @@ -1,240 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -var { Base, Class } = require("api-utils/base"); - -exports["test .isPrototypeOf"] = function(assert) { - assert.ok(Base.isPrototypeOf(Base.new()), - "Base is a prototype of Base.new()"); - assert.ok(Base.isPrototypeOf(Base.extend()), - "Base is a prototype of Base.extned()"); - assert.ok(Base.isPrototypeOf(Base.extend().new()), - "Base is a prototoype of Base.extend().new()"); - assert.ok(!Base.extend().isPrototypeOf(Base.extend()), - "Base.extend() in not prototype of Base.extend()"); - assert.ok(!Base.extend().isPrototypeOf(Base.new()), - "Base.extend() is not prototype of Base.new()"); - assert.ok(!Base.new().isPrototypeOf(Base.extend()), - "Base.new() is not prototype of Base.extend()"); - assert.ok(!Base.new().isPrototypeOf(Base.new()), - "Base.new() is not prototype of Base.new()"); -}; - -exports["test inheritance"] = function(assert) { - var Parent = Base.extend({ - name: "parent", - method: function () { - return "hello " + this.name; - } - }); - - assert.equal(Parent.name, "parent", "Parent name is parent"); - assert.equal(Parent.method(), "hello parent", "method works on prototype"); - assert.equal(Parent.new().name, Parent.name, "Parent instance inherits name"); - assert.equal(Parent.new().method(), Parent.method(), - "method behaves same on the prototype"); - assert.equal(Parent.extend({}).name, Parent.name, - "Parent decedent inherits name"); - - var Child = Parent.extend({ name: "child" }); - assert.notEqual(Child.name, Parent.name, "Child overides name"); - assert.equal(Child.new().name, Child.name, "Child intsances inherit name"); - assert.equal(Child.extend().name, Child.name, - "Child decedents inherit name"); - - assert.equal(Child.method, Parent.method, "Child inherits method"); - assert.equal(Child.extend().method, Parent.method, - "Child decedent inherit method"); - assert.equal(Child.new().method, Parent.method, - "Child instances inherit method"); - - assert.equal(Child.method(), "hello child", - "method refers to instance proprety"); - assert.equal(Child.extend({ name: "decedent" }).new().method(), - "hello decedent", "method may be overrided"); -}; - -exports["test prototype immutability"] = function(assert) { - - assert.throws(function() { - var override = function() {}; - Base.extend = override; - if (Base.extend !== override) - throw Error("Property was not set"); - }, "Base prototype is imutable"); - - assert.throws(function() { - Base.foo = "bar"; - if (Base.foo !== "bar") - throw Error("Property was not set"); - }, "Base prototype is non-configurabel"); - - assert.throws(function() { - delete Base.new; - if ('new' in Base) - throw Error('Property was not deleted'); - }, "Can't delete properties on prototype"); - - var Foo = Base.extend({ - name: 'hello', - rename: function rename(name) { - this.name = name; - } - }); - - assert.throws(function() { - var override = function() {}; - Foo.extend = override; - if (Foo.extend !== override) - throw Error("Property was not set"); - }, "Can't change prototype properties"); - - assert.throws(function() { - Foo.foo = "bar"; - if (Foo.foo !== "bar") - throw Error("Property was not set"); - }, "Can't add prototype properties"); - - assert.throws(function() { - delete Foo.name; - if ('new' in Foo) - throw Error('Property was not deleted'); - }, "Can't remove prototype properties"); - - assert.throws(function() { - Foo.rename("new name"); - if (Foo.name !== "new name") - throw Error("Property was not modified"); - }, "Method's can't mutate prototypes"); - - var Bar = Foo.extend({ - rename: function rename() { - return this.name; - } - }); - - assert.equal(Bar.rename(), Foo.name, - "properties may be overided on decedents"); -}; - -exports['test instance mutability'] = function(assert) { - var Foo = Base.extend({ - name: "foo", - init: function init(number) { - this.number = number; - } - }); - var f1 = Foo.new(); - /* V8 does not supports this yet! - assert.throws(function() { - f1.name = "f1"; - }, "can't change prototype properties"); - */ - f1.alias = "f1"; - assert.equal(f1.alias, "f1", "instance is mutable"); - delete f1.alias; - assert.ok(!('alias' in f1), "own properties are deletable"); - f1.init(1); - assert.equal(f1.number, 1, "method can mutate instance's own properties"); -}; - -exports['test super'] = function(assert) { - var Foo = Base.extend({ - initialize: function Foo(options) { - this.name = options.name; - } - }); - - var Bar = Foo.extend({ - initialize: function Bar(options) { - Foo.initialize.call(this, options); - this.type = 'bar'; - } - }); - - var bar = Bar.new({ name: 'test' }); - - assert.ok(Bar.isPrototypeOf(bar), 'Bar is prototype of Bar.new'); - assert.ok(Foo.isPrototypeOf(bar), 'Foo is prototype of Bar.new'); - assert.ok(Base.isPrototypeOf(bar), 'Base is prototype of Bar.new'); - assert.equal(bar.type, 'bar', 'bar initializer was called'); - assert.equal(bar.name, 'test', 'bar initializer called Foo initializer'); -}; - -exports['test class'] = function(assert) { - var Foo = Base.extend({ - type: 'Foo', - initialize: function(options) { - this.name = options.name; - }, - serialize: function serialize() { - return '<' + this.name + ':' + this.type + '>'; - } - }); - var CFoo = Class(Foo); - var f1 = CFoo({ name: 'f1' }); - var f2 = new CFoo({ name: 'f2' }); - var f3 = CFoo.new({ name: 'f3' }); - var f4 = Foo.new({ name: 'f4' }); - - assert.ok(f1 instanceof CFoo, 'correct instanceof'); - assert.equal(f1.name, 'f1', 'property initialized'); - assert.equal(f1.serialize(), '<f1:Foo>', 'method works'); - - assert.ok(f2 instanceof CFoo, 'correct instanceof when created with new') - assert.equal(f2.name, 'f2', 'property initialized'); - assert.equal(f2.serialize(), '<f2:Foo>', 'method works'); - - assert.ok(f3 instanceof CFoo, 'correct instanceof when created with .new') - assert.equal(f3.name, 'f3', 'property initialized'); - assert.equal(f3.serialize(), '<f3:Foo>', 'method works'); - - assert.ok(f4 instanceof CFoo, 'correct instanceof when created from prototype') - assert.equal(f4.name, 'f4', 'property initialized'); - assert.equal(f4.serialize(), '<f4:Foo>', 'method works'); - - var Bar = Foo.extend({ - type: 'Bar', - initialize: function(options) { - this.size = options.size; - Foo.initialize.call(this, options); - } - }); - var CBar = Class(Bar); - - - var b1 = CBar({ name: 'b1', size: 1 }); - var b2 = new CBar({ name: 'b2', size: 2 }); - var b3 = CBar.new({ name: 'b3', size: 3 }); - var b4 = Bar.new({ name: 'b4', size: 4 }); - - assert.ok(b1 instanceof CFoo, 'correct instanceof'); - assert.ok(b1 instanceof CBar, 'correct instanceof'); - assert.equal(b1.name, 'b1', 'property initialized'); - assert.equal(b1.size, 1, 'property initialized'); - assert.equal(b1.serialize(), '<b1:Bar>', 'method works'); - - assert.ok(b2 instanceof CFoo, 'correct instanceof when created with new'); - assert.ok(b2 instanceof CBar, 'correct instanceof when created with new'); - assert.equal(b2.name, 'b2', 'property initialized'); - assert.equal(b2.size, 2, 'property initialized'); - assert.equal(b2.serialize(), '<b2:Bar>', 'method works'); - - assert.ok(b3 instanceof CFoo, 'correct instanceof when created with .new'); - assert.ok(b3 instanceof CBar, 'correct instanceof when created with .new'); - assert.equal(b3.name, 'b3', 'property initialized'); - assert.equal(b3.size, 3, 'property initialized'); - assert.equal(b3.serialize(), '<b3:Bar>', 'method works'); - - assert.ok(b4 instanceof CFoo, 'correct instanceof when created from prototype'); - assert.ok(b4 instanceof CBar, 'correct instanceof when created from prototype'); - assert.equal(b4.name, 'b4', 'property initialized'); - assert.equal(b4.size, 4, 'property initialized'); - assert.equal(b4.serialize(), '<b4:Bar>', 'method works'); -}; - -require("test").run(exports); - diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-worker.js b/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-worker.js deleted file mode 100644 index d5e95a1..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-content-worker.js +++ /dev/null @@ -1,465 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use stirct"; - -const { Cc, Ci } = require('chrome'); -const timer = require('timer'); -const { Loader } = require("@loader"); - -function makeWindow(contentURL) { - let content = - '<?xml version="1.0"?>' + - '<window ' + - 'xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">' + - '<iframe id="content" type="content" src="' + - encodeURIComponent(contentURL) + '"/>' + - '<script>var documentValue=true;</script>' + - '</window>'; - var url = "data:application/vnd.mozilla.xul+xml," + - encodeURIComponent(content); - var features = ["chrome", "width=10", "height=10"]; - - return Cc["@mozilla.org/embedcomp/window-watcher;1"]. - getService(Ci.nsIWindowWatcher). - openWindow(null, url, null, features.join(","), null); -} - -const { Worker } = require('content/worker'); -exports['test:sample'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - // As window has just being created, its document is still loading, - // and we have about:blank document before the expected one - test.assertEqual(window.document.location.href, "about:blank", - "window starts by loading about:blank"); - - // We need to wait for the load/unload of temporary about:blank - // or our worker is going to be automatically destroyed - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - test.assertNotEqual(window.document.location.href, "about:blank", - "window is now on the right document"); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - // window is accessible - let myLocation = window.location.toString(); - self.on('message', function(data) { - if (data == 'hi!') - self.postMessage('bye!'); - }); - }, - contentScriptWhen: 'ready', - onMessage: function(msg) { - test.assertEqual('bye!', msg); - test.assertEqual(worker.url, window.document.location.href, - "worker.url still works"); - test.done(); - } - }); - - test.assertEqual(worker.url, window.document.location.href, - "worker.url works"); - worker.postMessage('hi!'); - - }, true); - -} - -exports['test:emit'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - // Validate self.on and self.emit - self.port.on('addon-to-content', function (data) { - self.port.emit('content-to-addon', data); - }); - - // Check for global pollution - //if (typeof on != "undefined") - // self.postMessage("`on` is in globals"); - if (typeof once != "undefined") - self.postMessage("`once` is in globals"); - if (typeof emit != "undefined") - self.postMessage("`emit` is in globals"); - - }, - onMessage: function(msg) { - test.fail("Got an unexpected message : "+msg); - } - }); - - // Validate worker.port - worker.port.on('content-to-addon', function (data) { - test.assertEqual(data, "event data"); - test.done(); - }); - worker.port.emit('addon-to-content', 'event data'); - -} - -exports['test:emit hack message'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - // Validate self.port - self.port.on('message', function (data) { - self.port.emit('message', data); - }); - // We should not receive message on self, but only on self.port - self.on('message', function (data) { - self.postMessage('message', data); - }); - }, - onError: function(e) { - test.fail("Got exception: "+e); - } - }); - - worker.port.on('message', function (data) { - test.assertEqual(data, "event data"); - test.done(); - }); - worker.on('message', function (data) { - test.fail("Got an unexpected message : "+msg); - }); - worker.port.emit('message', 'event data'); - -} - -exports['test:n-arguments emit'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - // Validate self.on and self.emit - self.port.on('addon-to-content', function (a1, a2, a3) { - self.port.emit('content-to-addon', a1, a2, a3); - }); - } - }); - - // Validate worker.port - worker.port.on('content-to-addon', function (arg1, arg2, arg3) { - test.assertEqual(arg1, "first argument"); - test.assertEqual(arg2, "second"); - test.assertEqual(arg3, "third"); - test.done(); - }); - worker.port.emit('addon-to-content', 'first argument', 'second', 'third'); -} - -exports['test:post-json-values-only'] = function(test) { - let window = makeWindow("data:text/html,"); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = Worker({ - window: window.document.getElementById("content").contentWindow, - contentScript: 'new ' + function WorkerScope() { - self.on('message', function (message) { - self.postMessage([ message.fun === undefined, - typeof message.w, - message.w && "port" in message.w, - message.w.url, - Array.isArray(message.array), - JSON.stringify(message.array)]); - }); - } - }); - - // Validate worker.onMessage - let array = [1, 2, 3]; - worker.on('message', function (message) { - test.assert(message[0], "function becomes undefined"); - test.assertEqual(message[1], "object", "object stays object"); - test.assert(message[2], "object's attributes are enumerable"); - test.assertEqual(message[3], "about:blank", "jsonable attributes are accessible"); - // See bug 714891, Arrays may be broken over compartements: - test.assert(message[4], "Array keeps being an array"); - test.assertEqual(message[5], JSON.stringify(array), - "Array is correctly serialized"); - test.done(); - }); - worker.postMessage({ fun: function () {}, w: worker, array: array }); - - }, true); - -}; - - -exports['test:emit-json-values-only'] = function(test) { - let window = makeWindow("data:text/html,"); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let win = window.document.getElementById("content").contentWindow; - let worker = Worker({ - window: win, - contentScript: 'new ' + function WorkerScope() { - // Validate self.on and self.emit - self.port.on('addon-to-content', function (fun, w, obj, array) { - self.port.emit('content-to-addon', [ - fun === null, - typeof w, - "port" in w, - w.url, - "fun" in obj, - Object.keys(obj.dom).length, - Array.isArray(array), - JSON.stringify(array) - ]); - }); - } - }); - - // Validate worker.port - let array = [1, 2, 3]; - worker.port.on('content-to-addon', function (result) { - test.assert(result[0], "functions become null"); - test.assertEqual(result[1], "object", "objects stay objects"); - test.assert(result[2], "object's attributes are enumerable"); - test.assertEqual(result[3], "about:blank", "json attribute is accessible"); - test.assert(!result[4], "function as object attribute is removed"); - test.assertEqual(result[5], 0, "DOM nodes are converted into empty object"); - // See bug 714891, Arrays may be broken over compartments: - test.assert(result[6], "Array keeps being an array"); - test.assertEqual(result[7], JSON.stringify(array), - "Array is correctly serialized"); - test.done(); - }); - - let obj = { - fun: function () {}, - dom: window.document.createElement("div") - }; - worker.port.emit("addon-to-content", function () {}, worker, obj, array); - - }, true); -} - -exports['test:content is wrapped'] = function(test) { - let contentURL = 'data:text/html,<script>var documentValue=true;</script>'; - let window = makeWindow(contentURL); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = Worker({ - window: window.document.getElementById("content").contentWindow, - contentScript: 'new ' + function WorkerScope() { - self.postMessage(!window.documentValue); - }, - contentScriptWhen: 'ready', - onMessage: function(msg) { - test.assert(msg, - "content script has a wrapped access to content document"); - test.done(); - } - }); - - }, true); - -} - -exports['test:chrome is unwrapped'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - self.postMessage(window.documentValue); - }, - contentScriptWhen: 'ready', - onMessage: function(msg) { - test.assert(msg, - "content script has an unwrapped access to chrome document"); - test.done(); - } - }); - - }, true); - -} - -exports['test:nothing is leaked to content script'] = function(test) { - let window = makeWindow(); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - self.postMessage([ - "ContentWorker" in window, - "UNWRAP_ACCESS_KEY" in window, - "getProxyForObject" in window - ]); - }, - contentScriptWhen: 'ready', - onMessage: function(list) { - test.assert(!list[0], "worker API contrustor isn't leaked"); - test.assert(!list[1], "Proxy API stuff isn't leaked 1/2"); - test.assert(!list[2], "Proxy API stuff isn't leaked 2/2"); - test.done(); - } - }); - - }, true); - -} - -exports['test:ensure console.xxx works in cs'] = function(test) { - test.waitUntilDone(5000); - - // Create a new module loader in order to be able to create a `console` - // module mockup: - let sandbox = Loader.new(require("@packaging")); - let sandboxRequire = Loader.require.bind(sandbox, module.path); - Object.defineProperty(sandbox.globals, 'console', { - value: { - log: hook.bind("log"), - info: hook.bind("info"), - warn: hook.bind("warn"), - error: hook.bind("error"), - debug: hook.bind("debug"), - exception: hook.bind("exception") - } - }); - - // Intercept all console method calls - let calls = []; - function hook(msg) { - test.assertEqual(this, msg, - "console.xxx(\"xxx\"), i.e. message is equal to the " + - "console method name we are calling"); - calls.push(msg); - } - - // Finally, create a worker that will call all console methods - let window = makeWindow(); - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = sandboxRequire('content/worker').Worker({ - window: window, - contentScript: 'new ' + function WorkerScope() { - console.log("log"); - console.info("info"); - console.warn("warn"); - console.error("error"); - console.debug("debug"); - console.exception("exception"); - self.postMessage(); - }, - onMessage: function() { - // Ensure that console methods are called in the same execution order - test.assertEqual(JSON.stringify(calls), - JSON.stringify(["log", "info", "warn", "error", "debug", "exception"]), - "console has been called successfully, in the expected order"); - test.done(); - } - }); - }, true); - -} - - -exports['test:setTimeout can\'t be cancelled by content'] = function(test) { - let contentURL = 'data:text/html,<script>var documentValue=true;</script>'; - let window = makeWindow(contentURL); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let worker = Worker({ - window: window.document.getElementById("content").contentWindow, - contentScript: 'new ' + function WorkerScope() { - let id = setTimeout(function () { - self.postMessage("timeout"); - }, 100); - unsafeWindow.eval("clearTimeout("+id+");"); - }, - contentScriptWhen: 'ready', - onMessage: function(msg) { - test.assert(msg, - "content didn't managed to cancel our setTimeout"); - test.done(); - } - }); - - }, true); - -} - -exports['test:setTimeout are unregistered on content unload'] = function(test) { - let contentURL = 'data:text/html,foo'; - let window = makeWindow(contentURL); - test.waitUntilDone(); - - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - let iframe = window.document.getElementById("content"); - let originalDocument = iframe.contentDocument; - let worker = Worker({ - window: iframe.contentWindow, - contentScript: 'new ' + function WorkerScope() { - document.title = "ok"; - let i = 0; - setInterval(function () { - document.title = i++; - }, 10); - }, - contentScriptWhen: 'ready' - }); - - // Change location so that content script is destroyed, - // and all setTimeout/setInterval should be unregistered. - // Wait some cycles in order to execute some intervals. - timer.setTimeout(function () { - // Bug 689621: Wait for the new document load so that we are sure that - // previous document cancelled its intervals - iframe.addEventListener("load", function onload() { - iframe.removeEventListener("load", onload, true); - let titleAfterLoad = originalDocument.title; - // Wait additional cycles to verify that intervals are really cancelled - timer.setTimeout(function () { - test.assertEqual(iframe.contentDocument.title, "final", - "New document has not been modified"); - test.assertEqual(originalDocument.title, titleAfterLoad, - "Nor previous one"); - test.done(); - }, 100); - }, true); - iframe.setAttribute("src", "data:text/html,<title>final</title>"); - }, 100); - - }, true); - -} diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-loader.js b/tools/addon-sdk-1.7/packages/api-utils/tests/test-loader.js deleted file mode 100644 index 82d97ba..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-loader.js +++ /dev/null @@ -1,35 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -const { Loader } = require("./helpers"); - -exports.testLoader = function(test) { - var prints = []; - function print(message) { - prints.push(message); - } - - var loader = Loader(module, { dump: print, foo: 1 }); - - var fixture = loader.require('./loader/fixture'); - - test.assertEqual(fixture.foo, 1, "custom globals must work."); - - test.assertEqual(prints[0], "info: testing 1 2,3,4\n", - "global console must work."); - - var unloadsCalled = ''; - - loader.require("unload").when(function() { - unloadsCalled += 'a'; - }); - loader.require("unload.js").when(function() { - unloadsCalled += 'b'; - }); - - loader.unload(); - - test.assertEqual(unloadsCalled, 'ba', - "loader.unload() must call cb's in LIFO order."); -}; diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-message-manager.js b/tools/addon-sdk-1.7/packages/api-utils/tests/test-message-manager.js deleted file mode 100644 index 386d3bd..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-message-manager.js +++ /dev/null @@ -1,600 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Loader } = require('./helpers'); - -function createMessageManager() { - let loader = Loader(module); - let { MessageManager } = loader.require("api-utils/message-manager"); - let frame = loader.sandbox("api-utils/message-manager").frame; - - return [new MessageManager, frame]; -} - - -exports["test MessageManager addMessageListener"] = - function(assert) { - let [mm, frame] = createMessageManager(); - let remoteFrame = frame(mm).receiver; - - let listeners = frame(mm).listeners; - let remoteListeners = frame(remoteFrame).listeners; - - let topic = "message-topic"; - - let listener = function () {}; - - assert.equal(topic in listeners, false, - "No listeners for MessageManager"); - assert.equal(topic in remoteListeners, false, - "No listeners for Remote Frame"); - - mm.addMessageListener(topic, listener); - - assert.deepEqual(listeners[topic], [listener], - "Listener is added properly"); - assert.equal(topic in remoteListeners, false, - "No listeners for Remote Frame"); - } - - -exports["test MessageManager addMessageListener with duplicates"] = - function(assert) { - let [mm, frame] = createMessageManager(); - let topic = "message-topic"; - let listeners = frame(mm).listeners; - - let listener = function () {}; - - mm.addMessageListener(topic, listener); - mm.addMessageListener(topic, listener); - mm.addMessageListener(topic, listener); - - assert.deepEqual(listeners[topic], [listener], - "Same listener is added only once"); - } - - -exports["test MessageManager addMessageListener exceptions"] = - function(assert) { - const BAD_LISTENER = "The event listener must be a function."; - - let [mm, frame] = createMessageManager(); - let listeners = frame(mm).listeners; - let topic = "message-topic"; - - assert.throws( - function() mm.addMessageListener(), - BAD_LISTENER - ); - - assert.throws( - function() mm.addMessageListener(topic), - BAD_LISTENER - ); - - assert.throws( - function() mm.addMessageListener(topic, "something-else"), - BAD_LISTENER - ); - } - -exports["test MessageManager removeMessageListener"] = - function(assert) { - let [mm, frame] = createMessageManager(); - let topic = "message-topic"; - let listeners = frame(mm).listeners; - - let listenerA = function () {}; - let listenerB = function () {}; - let listenerC = function () {}; - - mm.removeMessageListener(topic, listenerA); - - assert.deepEqual(listeners, {}, - "No listeners yet"); - - mm.addMessageListener(topic, listenerA); - mm.addMessageListener(topic, listenerB); - mm.addMessageListener(topic, listenerC); - - mm.removeMessageListener(topic, listenerB); - - assert.deepEqual(listeners[topic], [listenerA, listenerC], - "Listener is removed properly"); - } - - -exports["test MessageManager loadFrameScript with data URL"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - assert.equal("TEST_VALUE" in remoteFrame, false, - "TEST_VALUE is not defined in Remote Frame"); - - mm.loadFrameScript("data:, const TEST_VALUE = 77;", true); - - assert.equal(remoteFrame.TEST_VALUE, 77, - "TEST_VALUE is properly defined in Remote Frame"); - } - - -exports["test MessageManager loadFrameScript with a File"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - assert.equal("TEST_VALUE" in remoteFrame, false, - "TEST_VALUE is not defined in Remote Frame"); - - mm.loadFrameScript(require("self").data.url("test-message-manager.js"), true); - - assert.equal(remoteFrame.TEST_VALUE, 11, - "TEST_VALUE is properly defined in Remote Frame"); - } - -exports["test MessageManager loadFrameScript exception"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - - assert.throws( - function() mm.loadFrameScript("data:, const TEST_VALUE = 77;"), - "Not enough arguments" - ); - - } - -exports["test Remote Frame addMessageListener"] = - function(assert) { - let [mm, frame] = createMessageManager(); - let remoteFrame = frame(mm).receiver; - - let listeners = frame(remoteFrame).listeners; - let managerListeners = frame(mm).listeners; - - let topic = "message-topic"; - - let listener = function () {}; - - assert.equal(topic in listeners, false, - "No listeners for Remote Frame"); - assert.equal(topic in managerListeners, false, - "No listeners for MessageManager"); - - remoteFrame.addMessageListener(topic, listener); - - assert.deepEqual(listeners[topic], [listener], - "Listener is added properly"); - assert.equal(topic in managerListeners, false, - "No listeners for MessageManager"); - } - - -exports["test Remote Frame addMessageListener with duplicates"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let listeners = frame(remoteFrame).listeners; - let topic = "message-topic"; - - let listener = function () {}; - - assert.equal(topic in listeners, false, - "No listeners in Remote Frame"); - - remoteFrame.addMessageListener(topic, listener); - remoteFrame.addMessageListener(topic, listener); - remoteFrame.addMessageListener(topic, listener); - - assert.deepEqual(listeners[topic], [listener], - "Listener is added properly"); - } - - -exports["test Remote Frame addMessageListener exceptions"] = - function(assert) { - const BAD_LISTENER = "The event listener must be a function."; - - let [mm, frame] = createMessageManager(); - let remoteFrame = frame(mm).receiver; - let listeners = frame(remoteFrame).listeners; - let topic = "message-topic"; - - assert.throws( - function() mm.addMessageListener(), - BAD_LISTENER - ); - - assert.throws( - function() mm.addMessageListener(topic), - BAD_LISTENER - ); - - assert.throws( - function() mm.addMessageListener(topic, "something-else"), - BAD_LISTENER - ); - } - - -exports["test Remote Frame removeMessageListener"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let listeners = frame(remoteFrame).listeners; - - let topic = "message-topic"; - - let listenerA = function () {}; - let listenerB = function () {}; - let listenerC = function () {}; - - remoteFrame.removeMessageListener(topic, listenerA); - - assert.deepEqual(listeners, {}, - "No listeners yet"); - - remoteFrame.addMessageListener(topic, listenerA); - remoteFrame.addMessageListener(topic, listenerB); - remoteFrame.addMessageListener(topic, listenerC); - - remoteFrame.removeMessageListener(topic, listenerB); - - assert.deepEqual(listeners[topic], [listenerA, listenerC], - "Listener is removed properly"); - } - - -exports["test MessageManager sendAsyncMessage"] = - function(assert, done) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let calls = 0; - - let topic = "message-topic"; - - let listener = function(data) { - calls++; - - assert.deepEqual(data, { - sync : false, - name : topic, - json : {foo : "bar"}, - target : null - }, "Data received as expected"); - - assert.equal(calls, 1, - "Listener called once"); - - done(); - } - - remoteFrame.addMessageListener(topic, listener); - - let response = mm.sendAsyncMessage(topic, {foo : "bar"}); - - assert.strictEqual(response, undefined, - "No response for async messages"); - - assert.equal(calls, 0, - "Listener not called yet"); - } - -exports["test MessageManager sendAsyncMessage without listeners"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - let topic = "message-topic"; - - let response = mm.sendAsyncMessage(topic, {foo : "bar"}); - - assert.strictEqual(response, undefined, - "No response for async messages"); - } - - -exports["test MessageManager sendAsyncMessage without arguments"] = - function(assert, done) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let calls = 0; - - let topic = "message-topic"; - - let listener = function(data) { - calls++; - - assert.deepEqual(data, { - sync : false, - name : topic, - json : null, - target : null - }, "Data received as expected"); - - assert.equal(calls, 1, - "Listener called once"); - - done(); - } - - remoteFrame.addMessageListener(topic, listener); - - mm.sendAsyncMessage(); - - mm.sendAsyncMessage(topic); - - assert.equal(calls, 0, - "Listener not called yet"); - } - - -exports["test Remote Frame sendAsyncMessage"] = - function(assert, done) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let calls = 0; - - let topic = "message-topic"; - - let listener = function(data) { - calls++; - - assert.deepEqual(data, { - sync : false, - name : topic, - json : {foo : "bar"}, - target : null - }, "Data received as expected"); - - assert.equal(calls, 1, - "Listener called once"); - - done(); - } - - mm.addMessageListener(topic, listener); - - let response = remoteFrame.sendAsyncMessage(topic, {foo : "bar"}); - - assert.strictEqual(response, undefined, - "No response for async messages"); - - assert.equal(calls, 0, - "Listener not called yet"); - } - - -exports["test Remote Frame sendAsyncMessage without arguments"] = - function(assert, done) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let calls = 0; - - let topic = "message-topic"; - - let listener = function(data) { - calls++; - - assert.deepEqual(data, { - sync : false, - name : topic, - json : null, - target : null - }, "Data received as expected"); - - assert.equal(calls, 1, - "Listener called once"); - - done(); - } - - mm.addMessageListener(topic, listener); - - remoteFrame.sendAsyncMessage(); - - remoteFrame.sendAsyncMessage(topic); - - assert.equal(calls, 0, - "Listener not called yet"); - } - -exports["test Remote Frame sendAsyncMessage without listeners"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - let topic = "message-topic"; - - let response = remoteFrame.sendAsyncMessage(topic, {foo : "bar"}); - - assert.strictEqual(response, undefined, - "No response for async messages"); - } - -exports["test Remote Frame sendSyncMessage"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - let topic = "message-topic"; - - let expectedData = { - sync : true, - name : topic, - json : {foo : "bar"}, - target : null - } - - let listenerA = function(data) { - assert.deepEqual(data, expectedData, - "Data received as expected"); - - return "my value"; - } - - let listenerB = function(data) { - assert.deepEqual(data, expectedData, - "Data received as expected"); - - return {complex : "object", method : function() "not allowed"}; - } - - let listenerC = function(data) { - assert.deepEqual(data, expectedData, - "Data received as expected"); - } - - mm.addMessageListener(topic, listenerA); - mm.addMessageListener(topic, listenerB); - mm.addMessageListener(topic, listenerC); - - let response = remoteFrame.sendSyncMessage(topic, {foo : "bar"}); - - assert.deepEqual(response, ["my value", {complex : "object"}, undefined], - "Response from sync messages as expected"); - } - -exports["test Remote Frame sendSyncMessage without arguments"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - - let topic = "message-topic"; - - let expectedData = { - sync : true, - name : topic, - json : null, - target : null - } - - let listener = function(data) { - assert.deepEqual(data, expectedData, - "Data received as expected"); - } - - mm.addMessageListener(topic, listener); - - let response = remoteFrame.sendSyncMessage(); - - assert.deepEqual(response, [], - "Empty response as expected"); - - let response = remoteFrame.sendSyncMessage(topic); - - assert.deepEqual(response, [undefined], - "Response from sync messages as expected"); - } - -exports["test Remote Frame sendSyncMessage without listeners"] = - function(assert) { - let [mm, frame] = createMessageManager(); - - let remoteFrame = frame(mm).receiver; - let obj = {foo : "bar"}; - - let topic = "message-topic"; - - let response = remoteFrame.sendSyncMessage(topic, obj); - - assert.deepEqual(response, [], - "Response from sync messages as expected"); - } - - -exports["test Message Manager / Remote Frame async pipeline"] = - function(assert, done) { - let [mm] = createMessageManager(); - - let expectedMessages = ["alpha:remote", "alpha", "omega:remote", "omega"]; - - mm.addMessageListener("handshake", function (data) { - let messages = data.json.concat("alpha"); - - mm.sendAsyncMessage("shutdown", messages); - }); - - mm.addMessageListener("shutdown", function (data) { - let messages = data.json.concat("omega"); - - assert.deepEqual(messages, expectedMessages, - "messages delivered in the expected order"); - - done(); - }); - - mm.loadFrameScript( - "data:, \ - addMessageListener('handshake', function (data) {\ - let messages = data.json.concat('alpha:remote');\ - sendAsyncMessage('handshake', messages);\ - });\ - addMessageListener('shutdown', function (data) {\ - let messages = data.json.concat('omega:remote');\ - sendAsyncMessage('shutdown', messages);\ - });\ - ", true); - - mm.sendAsyncMessage("handshake", []); - } - - -exports["test Message Manager / Remote Frame async / sync pipeline"] = - function(assert, done) { - let [mm] = createMessageManager(); - - let expectedMessages = ["alpha:remote", "alpha", "omega:remote", "omega"]; - - mm.addMessageListener("handshake", - function (data) data.json.concat("alpha") - ); - - mm.addMessageListener("shutdown", - function (data) data.json.concat("omega") - ); - - mm.addMessageListener("verify", function (data) { - - assert.deepEqual(data.json, expectedMessages, - "messages delivered in the expected order"); - - done(); - }); - - mm.loadFrameScript( - "data:, \ - addMessageListener('handshake', function (data) {\ - let messages = data.json.concat('alpha:remote');\ - \ - messages = sendSyncMessage('handshake', messages)[0];\ - messages.push('omega:remote');\ - messages = sendSyncMessage('shutdown', messages)[0];\ - \ - sendSyncMessage('verify', messages);\ - });\ - ", true); - - mm.sendAsyncMessage("handshake", []); - } - -require("test").run(exports); diff --git a/tools/addon-sdk-1.7/packages/api-utils/tests/test-process.js b/tools/addon-sdk-1.7/packages/api-utils/tests/test-process.js deleted file mode 100644 index 43d0864..0000000 --- a/tools/addon-sdk-1.7/packages/api-utils/tests/test-process.js +++ /dev/null @@ -1,36 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { Loader } = require("./helpers"); -const { jetpackID } = require('@packaging'); - -// bug 707562: '#' char in packaging was causing loader to be undefined -exports.testBug707562 = function(test) { - test.waitUntilDone(); - - let packaging = JSON.parse(JSON.stringify(require("@packaging"))); - packaging.metadata["api-utils"].author = "###"; - - let loader = Loader(module, {}, packaging); - let process = loader.require("process"); - - // has spawn? - test.assert(process.spawn, "'process' module exports 'spawn' method."); - - let promise = process.spawn("testID", ""); - test.assertFunction(promise, "spawn makes a promise."); - - promise(function(addon) { - addon.channel("TEST:LOADED").input(function(data) { - test.assert(data, "The loader was successfully created!"); - loader.unload(); - test.done(); - }); - - addon.loadScript('data:,sendAsyncMessage("'+jetpackID+':TEST:LOADED", !!this.loader);', false); - test.pass("spawn's promise was delivered! (which means a addon process object is available))."); - }); -}; diff --git a/tools/addon-sdk-1.7/packages/test-harness/README.md b/tools/addon-sdk-1.7/packages/test-harness/README.md deleted file mode 100644 index b22824b..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/README.md +++ /dev/null @@ -1,12 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<span class="aside"> -For more information on testing in the Add-on SDK, see the -[Unit Testing](dev-guide/tutorials/unit-testing.html) -tutorial. -</span> - -This package contains a program that finds and runs tests. It is -automatically used whenever the `cfx test` command is executed. diff --git a/tools/addon-sdk-1.7/packages/test-harness/docs/harness.md b/tools/addon-sdk-1.7/packages/test-harness/docs/harness.md deleted file mode 100644 index 45218ec..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/docs/harness.md +++ /dev/null @@ -1,6 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -This module contains the bulk of the test harness setup and execution -implementation. diff --git a/tools/addon-sdk-1.7/packages/test-harness/docs/run-tests.md b/tools/addon-sdk-1.7/packages/test-harness/docs/run-tests.md deleted file mode 100644 index 155b809..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/docs/run-tests.md +++ /dev/null @@ -1,13 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -<span class="aside"> -For more information on testing in the Add-on SDK, see the -[Unit Testing](dev-guide/tutorials/unit-testing.html) -tutorial. -</span> - -This module contains the package's main program, which does a -bit of high-level setup and then delegates test finding and running to -the `harness` module. diff --git a/tools/addon-sdk-1.7/packages/test-harness/lib/run-tests.js b/tools/addon-sdk-1.7/packages/test-harness/lib/run-tests.js deleted file mode 100644 index 4eb8570..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/lib/run-tests.js +++ /dev/null @@ -1,101 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -var obsvc = require("api-utils/observer-service"); -var system = require("api-utils/system"); -var options = require('@packaging'); -var {Cc,Ci} = require("chrome"); - -function runTests(iterations, filter, profileMemory, stopOnError, verbose, exit, print) { - var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"] - .getService(Ci.nsIWindowWatcher); - - let ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; - let msg = 'Running tests...'; - let markup = '<?xml version="1.0"?><window xmlns="' + ns + - '" windowtype="test:runner"><label>' + msg + '</label></window>'; - let url = "data:application/vnd.mozilla.xul+xml," + escape(markup); - - - var window = ww.openWindow(null, url, "harness", "centerscreen", null); - - var harness = require("./harness"); - - function onDone(tests) { - window.close(); - if (tests.failed == 0) { - if (tests.passed === 0) - print("No tests were run\n"); - exit(0); - } else { - printFailedTests(tests, verbose, print); - exit(1); - } - }; - - // We have to wait for this window to be fully loaded *and* focused - // in order to avoid it to mess with our various window/focus tests. - // We are first waiting for our window to be fully loaded before ensuring - // that it will take the focus, and then we wait for it to be focused. - window.addEventListener("load", function onload() { - window.removeEventListener("load", onload, true); - - window.addEventListener("focus", function onfocus() { - window.removeEventListener("focus", onfocus, true); - // Finally, we have to run test on next cycle, otherwise XPCOM components - // are not correctly updated. - // For ex: nsIFocusManager.getFocusedElementForWindow may throw - // NS_ERROR_ILLEGAL_VALUE exception. - require("timer").setTimeout(function () { - harness.runTests({iterations: iterations, - filter: filter, - profileMemory: profileMemory, - stopOnError: stopOnError, - verbose: verbose, - print: print, - onDone: onDone}); - }, 0); - }, true); - window.focus(); - }, true); -} - -function printFailedTests(tests, verbose, print) { - if (!verbose) - return; - - let iterationNumber = 0; - let singleIteration = tests.testRuns.length == 1; - let padding = singleIteration ? "" : " "; - - print("\nThe following tests failed:\n"); - - for each (let testRun in tests.testRuns) { - iterationNumber++; - - if (!singleIteration) - print(" Iteration " + iterationNumber + ":\n"); - - for each (let test in testRun) { - if (test.failed > 0) { - print(padding + " " + test.name + ": " + test.errors +"\n"); - } - } - print("\n"); - } -} - -exports.main = function main() { - var testsStarted = false; - - if (!testsStarted) { - testsStarted = true; - runTests(options.iterations, options.filter, - options.profileMemory, options.stopOnError, options.verbose, - system.exit, - dump); - } -}; diff --git a/tools/addon-sdk-1.7/packages/test-harness/package.json b/tools/addon-sdk-1.7/packages/test-harness/package.json deleted file mode 100644 index b44fb06..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "test-harness", - "description": "A harness for running Jetpack tests.", - "author": "Atul Varma (http://toolness.com/)", - "keywords": ["jetpack-low-level"], - "license": "MPL 2.0", - "dependencies": ["api-utils"] -} diff --git a/tools/addon-sdk-1.7/packages/test-harness/tests/test-packaging.js b/tools/addon-sdk-1.7/packages/test-harness/tests/test-packaging.js deleted file mode 100644 index 0628af2..0000000 --- a/tools/addon-sdk-1.7/packages/test-harness/tests/test-packaging.js +++ /dev/null @@ -1,18 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -var url = require("url"); -var file = require("file"); -var {Cm,Ci} = require("chrome"); -var options = require("@packaging"); - -exports.testPackaging = function(test) { - test.assertEqual(options.main, - 'test-harness/run-tests', - "main program should be the test harness"); - - test.assertEqual(options.metadata['test-harness'].author, - 'Atul Varma (http://toolness.com/)', - "packaging metadata should be available"); -}; diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/bootstrap.js b/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/bootstrap.js deleted file mode 100644 index 661f2bb..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/app-extension/bootstrap.js +++ /dev/null @@ -1,216 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// @see http://mxr.mozilla.org/mozilla-central/source/js/src/xpconnect/loader/mozJSComponentLoader.cpp - -"use strict"; - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, - results: Cr, manager: Cm } = Components; -const ioService = Cc['@mozilla.org/network/io-service;1']. - getService(Ci.nsIIOService); -const resourceHandler = ioService.getProtocolHandler('resource') - .QueryInterface(Ci.nsIResProtocolHandler); -const XMLHttpRequest = CC('@mozilla.org/xmlextras/xmlhttprequest;1', - 'nsIXMLHttpRequest'); -const prefs = Cc["@mozilla.org/preferences-service;1"]. - getService(Ci.nsIPrefService). - QueryInterface(Ci.nsIPrefBranch2); -const mozIJSSubScriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); - -const REASON = [ 'unknown', 'startup', 'shutdown', 'enable', 'disable', - 'install', 'uninstall', 'upgrade', 'downgrade' ]; - -let loader = null; -let loaderUri = null; - -const URI = __SCRIPT_URI_SPEC__.replace(/bootstrap\.js$/, ""); - -// Initializes default preferences -function setDefaultPrefs() { - let branch = prefs.getDefaultBranch(""); - let prefLoaderScope = { - pref: function(key, val) { - switch (typeof val) { - case "boolean": - branch.setBoolPref(key, val); - break; - case "number": - if (val % 1 == 0) // number must be a integer, otherwise ignore it - branch.setIntPref(key, val); - break; - case "string": - branch.setCharPref(key, val); - break; - } - } - }; - - let uri = ioService.newURI( - "defaults/preferences/prefs.js", - null, - ioService.newURI(URI, null, null)); - - // if there is a prefs.js file, then import the default prefs - try { - // setup default prefs - mozIJSSubScriptLoader.loadSubScript(uri.spec, prefLoaderScope); - } - // errors here should not kill addon - catch (e) { - Cu.reportError(e); - } -} - -// Gets the topic that fit best as application startup event, in according with -// the current application (e.g. Firefox, Fennec, Thunderbird...) -function getAppStartupTopic() { - // The following mapping of application names to GUIDs was taken - // from `xul-app` module. They should keep in sync, so if you change one, - // change the other too! - let ids = { - Firefox: '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}', - Mozilla: '{86c18b42-e466-45a9-ae7a-9b95ba6f5640}', - Sunbird: '{718e30fb-e89b-41dd-9da7-e25a45638b28}', - SeaMonkey: '{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}', - Fennec: '{aa3c5121-dab2-40e2-81ca-7ea25febc110}', - Thunderbird: '{3550f703-e582-4d05-9a08-453d09bdfdc6}' - }; - - let id = Cc['@mozilla.org/xre/app-info;1'].getService(Ci.nsIXULAppInfo).ID; - - switch (id) { - case ids.Firefox: - case ids.SeaMonkey: - return 'sessionstore-windows-restored'; - case ids.Thunderbird: - return 'mail-startup-done'; - // Temporary, until Fennec Birch will support sessionstore event - case ids.Fennec: - default: - return 'final-ui-startup'; - } -} - -// Utility function that synchronously reads local resource from the given -// `uri` and returns content string. -function readURI(uri) { - let ioservice = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); - let channel = ioservice.newChannel(uri, "UTF-8", null); - let stream = channel.open(); - - let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream); - cstream.init(stream, "UTF-8", 0, 0); - - let str = {}; - let data = ""; - let read = 0; - do { - read = cstream.readString(0xffffffff, str); - data += str.value; - } while (read != 0); - - cstream.close(); - - return data; -} - -// Function takes `topic` to be observer via `nsIObserverService` and returns -// promise that will be delivered once notification is published. -function on(topic) { - return function promise(deliver) { - const observerService = Cc['@mozilla.org/observer-service;1']. - getService(Ci.nsIObserverService); - - observerService.addObserver({ - observe: function observer(subject, topic, data) { - observerService.removeObserver(this, topic); - deliver(subject, topic, data); - } - }, topic, false); - } -} - -// We don't do anything on install & uninstall yet, but in a future -// we should allow add-ons to cleanup after uninstall. -function install(data, reason) {} -function uninstall(data, reason) {} - -function startup(data, reason) { - // TODO: When bug 564675 is implemented this will no longer be needed - // Always set the default prefs, because they disappear on restart - setDefaultPrefs(); - - // TODO: Maybe we should perform read harness-options.json asynchronously, - // since we can't do anything until 'sessionstore-windows-restored' anyway. - let options = JSON.parse(readURI(URI + './harness-options.json')); - options.loadReason = REASON[reason]; - - // URI for the root of the XPI file. - // 'jar:' URI if the addon is packed, 'file:' URI otherwise. - // (Used by l10n module in order to fetch `locale` folder) - options.rootURI = data.resourceURI.spec; - - // Register a new resource "domain" for this addon which is mapping to - // XPI's `resources` folder. - // Generate the domain name by using jetpack ID, which is the extension ID - // by stripping common characters that doesn't work as a domain name: - let uuidRe = - /^\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}$/; - let domain = options.jetpackID.toLowerCase() - .replace(/@/g, "-at-") - .replace(/\./g, "-dot-") - .replace(uuidRe, "$1"); - - let resourcesUri = ioService.newURI(URI + '/resources/', null, null); - resourceHandler.setSubstitution(domain, resourcesUri); - options.uriPrefix = "resource://" + domain + "/"; - - // Import loader module using `Cu.imports` and bootstrap module loader. - loaderUri = options.uriPrefix + options.loader; - loader = Cu.import(loaderUri).Loader.new(options); - - // Creating a promise, that will be delivered once application is ready. - // If application is at startup then promise is delivered on - // the application startup topic, otherwise it's delivered immediately. - let promise = reason === APP_STARTUP ? on(getAppStartupTopic()) : - function promise(deliver) deliver() - - // Once application is ready we spawn a new process with main module of - // on add-on. - promise(function() { - try { - loader.spawn(options.main, options.mainPath); - } catch (error) { - // If at this stage we have an error only thing we can do is report about - // it via error console. Keep in mind that error won't automatically show - // up there when called via observerService. - Cu.reportError(error); - throw error; - } - }); - -}; - -function shutdown(data, reason) { - // If loader is already present unload it, since add-on is disabled. - if (loader) { - reason = REASON[reason]; - let system = loader.require('api-utils/system'); - loader.unload(reason); - - // Bug 724433: We need to unload JSM otherwise it will stay alive - // and keep a reference to this compartment. - Cu.unload(loaderUri); - loader = null; - - // If add-on is lunched via `cfx run` we need to use `system.exit` to let - // cfx know we're done (`cfx test` will take care of exit so we don't do - // anything here). - if (system.env.CFX_COMMAND === 'run' && reason === 'shutdown') - system.exit(0); - } -}; diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/generate.py b/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/generate.py deleted file mode 100644 index 19ef109..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/generate.py +++ /dev/null @@ -1,292 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -import os -import sys -import shutil -import hashlib -import tarfile -import StringIO -import HTMLParser -import urlparse - -from cuddlefish import packaging -from cuddlefish.docs import apiparser -from cuddlefish.docs import apirenderer -from cuddlefish.docs import webdocs -import simplejson as json - -DIGEST = "status.md5" -TGZ_FILENAME = "addon-sdk-docs.tgz" - -def get_sdk_docs_path(env_root): - return os.path.join(env_root, "doc") - -def get_base_url(env_root): - sdk_docs_path = get_sdk_docs_path(env_root).lstrip("/") - return "file://"+"/"+"/".join(sdk_docs_path.split(os.sep))+"/" - -def clean_generated_docs(docs_dir): - status_file = os.path.join(docs_dir, "status.md5") - if os.path.exists(status_file): - os.remove(status_file) - index_file = os.path.join(docs_dir, "index.html") - if os.path.exists(index_file): - os.remove(index_file) - dev_guide_dir = os.path.join(docs_dir, "dev-guide") - if os.path.exists(dev_guide_dir): - shutil.rmtree(dev_guide_dir) - api_doc_dir = os.path.join(docs_dir, "packages") - if os.path.exists(api_doc_dir): - shutil.rmtree(api_doc_dir) - -def generate_static_docs(env_root): - clean_generated_docs(get_sdk_docs_path(env_root)) - generate_docs(env_root, stdout=StringIO.StringIO()) - tgz = tarfile.open(TGZ_FILENAME, 'w:gz') - tgz.add(get_sdk_docs_path(env_root), "doc") - tgz.close() - return TGZ_FILENAME - -def generate_local_docs(env_root): - return generate_docs(env_root, get_base_url(env_root)) - -def generate_named_file(env_root, filename): - web_docs = webdocs.WebDocs(env_root, get_base_url(env_root)) - # next, generate api doc or guide doc - abs_path = os.path.abspath(filename) - if abs_path.startswith(os.path.join(env_root, 'packages')): - doc_html, dest_dir, filename = generate_api_doc(env_root, abs_path, web_docs) - write_file(env_root, doc_html, dest_dir, filename) - elif abs_path.startswith(os.path.join(get_sdk_docs_path(env_root), 'dev-guide-source')): - doc_html, dest_dir, filename = generate_guide_doc(env_root, abs_path, web_docs) - write_file(env_root, doc_html, dest_dir, filename, False) - else: - raise ValueError("Not a valid path to a documentation file") - -def generate_docs(env_root, base_url=None, stdout=sys.stdout): - docs_dir = get_sdk_docs_path(env_root) - # if the generated docs don't exist, generate everything - if not os.path.exists(os.path.join(docs_dir, "dev-guide")): - print >>stdout, "Generating documentation..." - generate_docs_from_scratch(env_root, base_url) - current_status = calculate_current_status(env_root) - open(os.path.join(docs_dir, DIGEST), "w").write(current_status) - else: - current_status = calculate_current_status(env_root) - previous_status_file = os.path.join(docs_dir, DIGEST) - docs_are_up_to_date = False - if os.path.exists(previous_status_file): - docs_are_up_to_date = current_status == open(previous_status_file, "r").read() - # if the docs are not up to date, generate everything - if not docs_are_up_to_date: - print >>stdout, "Regenerating documentation..." - generate_docs_from_scratch(env_root, base_url) - open(os.path.join(docs_dir, DIGEST), "w").write(current_status) - return get_base_url(env_root) + "index.html" - -# this function builds a hash of the name and last modification date of: -# * every file in "packages" which ends in ".md" -# * every file in "static-files" which does not start with "." -def calculate_current_status(env_root): - docs_dir = get_sdk_docs_path(env_root) - current_status = hashlib.md5() - package_src_dir = os.path.join(env_root, "packages") - for (dirpath, dirnames, filenames) in os.walk(package_src_dir): - for filename in filenames: - if filename.endswith(".md"): - current_status.update(filename) - current_status.update(str(os.path.getmtime(os.path.join(dirpath, filename)))) - guide_src_dir = os.path.join(docs_dir, "dev-guide-source") - for (dirpath, dirnames, filenames) in os.walk(guide_src_dir): - for filename in filenames: - if filename.endswith(".md"): - current_status.update(filename) - current_status.update(str(os.path.getmtime(os.path.join(dirpath, filename)))) - base_html_file = os.path.join(docs_dir, "static-files", "base.html") - current_status.update(base_html_file) - current_status.update(str(os.path.getmtime(os.path.join(dirpath, base_html_file)))) - return current_status.digest() - -def generate_docs_from_scratch(env_root, base_url): - docs_dir = get_sdk_docs_path(env_root) - web_docs = webdocs.WebDocs(env_root, base_url) - must_rewrite_links = True - if base_url: - must_rewrite_links = False - clean_generated_docs(docs_dir) - - # py2.5 doesn't have ignore=, so we delete tempfiles afterwards. If we - # required >=py2.6, we could use ignore=shutil.ignore_patterns("*~") - for (dirpath, dirnames, filenames) in os.walk(docs_dir): - for n in filenames: - if n.endswith("~"): - os.unlink(os.path.join(dirpath, n)) - - # generate api docs from all packages - os.mkdir(os.path.join(docs_dir, "packages")) - # create the index file and save that - pkg_cfg = packaging.build_pkg_cfg(env_root) - index = json.dumps(packaging.build_pkg_index(pkg_cfg)) - index_path = os.path.join(docs_dir, "packages", 'index.json') - open(index_path, 'w').write(index) - - # for each package, generate its docs - for pkg_name, pkg in pkg_cfg['packages'].items(): - src_dir = pkg.root_dir - package_dirname = os.path.basename(src_dir) - dest_dir = os.path.join(docs_dir, "packages", package_dirname) - os.mkdir(dest_dir) - - src_readme = os.path.join(src_dir, "README.md") - if os.path.exists(src_readme): - shutil.copyfile(src_readme, - os.path.join(dest_dir, "README.md")) - - # create the package page - package_filename = os.path.join(dest_dir, "index.html") - if not os.path.exists(package_filename): - package_doc_html = web_docs.create_package_page(pkg_name) - replace_file(env_root, package_filename, package_doc_html, must_rewrite_links) - - # generate all the API docs - docs_src_dir = os.path.join(src_dir, "doc") - if os.path.isdir(os.path.join(src_dir, "docs")): - docs_src_dir = os.path.join(src_dir, "docs") - generate_file_tree(env_root, docs_src_dir, web_docs, generate_api_doc, must_rewrite_links) - - # generate all the guide docs - dev_guide_src = os.path.join(docs_dir, "dev-guide-source") - generate_file_tree(env_root, dev_guide_src, web_docs, generate_guide_doc, must_rewrite_links) - - # make /md/dev-guide/welcome.html the top level index file - doc_html, dest_dir, filename = generate_guide_doc(env_root, os.path.join(docs_dir, 'dev-guide-source', 'index.md'), web_docs) - write_file(env_root, doc_html, docs_dir, 'index', False) - -def generate_file_tree(env_root, src_dir, web_docs, generate_file, must_rewrite_links): - for (dirpath, dirnames, filenames) in os.walk(src_dir): - assert dirpath.startswith(src_dir) # what is this for?? - for filename in filenames: - if filename.endswith("~"): - continue - src_path = os.path.join(dirpath, filename) - if src_path.endswith(".md"): - # write the standalone HTML files - doc_html, dest_dir, filename = generate_file(env_root, src_path, web_docs) - write_file(env_root, doc_html, dest_dir, filename, must_rewrite_links) - -def generate_api_doc(env_root, src_dir, web_docs): - doc_html = web_docs.create_module_page(src_dir) - dest_dir, filename = get_api_doc_dest_path(env_root, src_dir) - return doc_html, dest_dir, filename - -def generate_guide_doc(env_root, src_dir, web_docs): - doc_html = web_docs.create_guide_page(src_dir) - dest_dir, filename = get_guide_doc_dest_path(env_root, src_dir) - return doc_html, dest_dir, filename - -def write_file(env_root, doc_html, dest_dir, filename, must_rewrite_links): - if not os.path.exists(dest_dir): - os.makedirs(dest_dir) - dest_path_html = os.path.join(dest_dir, filename) + ".html" - replace_file(env_root, dest_path_html, doc_html, must_rewrite_links) - return dest_path_html - -def replace_file(env_root, dest_path, file_contents, must_rewrite_links): - if os.path.exists(dest_path): - os.remove(dest_path) - # before we copy the final version, we'll rewrite the links - # I'll do this last, just because we know definitely what the dest_path is at this point - if must_rewrite_links and dest_path.endswith(".html"): - file_contents = rewrite_links(env_root, file_contents, dest_path) - open(dest_path, "w").write(file_contents) - -def rewrite_links(env_root, page, dest_path): - dest_path_depth = len(dest_path.split(os.sep)) -1 # because dest_path includes filename - docs_root_depth = len(get_sdk_docs_path(env_root).split(os.sep)) - relative_depth = dest_path_depth - docs_root_depth - linkRewriter = LinkRewriter("../" * relative_depth) - return linkRewriter.rewrite_links(page) - -# Given the full path to an API source file, and the root, -# return a tuple of: -# 1) the full path to the corresponding HTML file, without the filename -# 2) the filename without the extension -def get_guide_doc_dest_path(env_root, src_dir): - src_dir_relative = src_dir[len(os.path.join(get_sdk_docs_path(env_root), "dev-guide-source")) + 1:] - return os.path.split(os.path.join(get_sdk_docs_path(env_root), "dev-guide", src_dir_relative)[:-3]) - -# Given the full path to a dev guide source file, and the root, -# return a tuple of: -# 1) the full path to the corresponding HTML file, without the filename -# 2) the filename without the extension -def get_api_doc_dest_path(env_root, src_dir): - src_dir_relative = src_dir[len(env_root) + 1:] - src_dir_relative_pieces = src_dir_relative.split(os.sep) - del src_dir_relative_pieces[2] - src_dir_relative = os.sep.join(src_dir_relative_pieces) - return os.path.split(os.path.join(get_sdk_docs_path(env_root), src_dir_relative)[:-3]) - -class LinkRewriter(HTMLParser.HTMLParser): - def __init__(self, link_prefix): - HTMLParser.HTMLParser.__init__(self) - self.stack = [] - self.link_prefix = link_prefix - - def rewrite_links(self, page): - self.feed(page) - self.close() - page = ''.join(self.stack) - self.stack = [] - return page - - def handle_decl(self, decl): - self.stack.append("<!" + decl + ">") - - def handle_comment(self, decl): - self.stack.append("<!--" + decl + "-->") - - def handle_starttag(self, tag, attrs): - self.stack.append(self.__html_start_tag(tag, self._rewrite_link(attrs))) - - def handle_entityref(self, name): - self.stack.append("&" + name + ";") - - def handle_endtag(self, tag): - self.stack.append(self.__html_end_tag(tag)) - - def handle_startendtag(self, tag, attrs): - self.stack.append(self.__html_startend_tag(tag, self._rewrite_link(attrs))) - - def _rewrite_link(self, attrs): - attrs = dict(attrs) - href = attrs.get('href', '') - if href: - parsed = urlparse.urlparse(href) - if not parsed.scheme: - attrs['href'] = self.link_prefix + href - src = attrs.get('src', '') - if src: - parsed = urlparse.urlparse(src) - if not parsed.scheme: - attrs['src'] = self.link_prefix + src - return attrs - - def handle_data(self, data): - self.stack.append(data) - - def __html_start_tag(self, tag, attrs): - return '<%s%s>' % (tag, self.__html_attrs(attrs)) - - def __html_startend_tag(self, tag, attrs): - return '<%s%s/>' % (tag, self.__html_attrs(attrs)) - - def __html_end_tag(self, tag): - return '</%s>' % (tag) - - def __html_attrs(self, attrs): - _attrs = '' - if attrs: - _attrs = ' %s' % (' '.join([('%s="%s"' % (k,v)) for k,v in dict(attrs).iteritems()])) - return _attrs diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/webdocs.py b/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/webdocs.py deleted file mode 100644 index dcecc78..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/docs/webdocs.py +++ /dev/null @@ -1,193 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -import os, re, errno -import markdown -import cgi - -from cuddlefish import packaging -from cuddlefish.docs import apirenderer -from cuddlefish._version import get_versions - -INDEX_PAGE = '/doc/static-files/base.html' -BASE_URL_INSERTION_POINT = '<base ' -VERSION_INSERTION_POINT = '<div id="version">' -THIRD_PARTY_PACKAGE_SUMMARIES = '<ul id="third-party-package-summaries">' -HIGH_LEVEL_PACKAGE_SUMMARIES = '<ul id="high-level-package-summaries">' -LOW_LEVEL_PACKAGE_SUMMARIES = '<ul id="low-level-package-summaries">' -CONTENT_ID = '<div id="main-content">' -TITLE_ID = '<title>' -DEFAULT_TITLE = 'Add-on SDK Documentation' - -def get_documentation(package_name, modules_json, doc_path): - documented_modules = [] - for root, dirs, files in os.walk(doc_path): - subdir_path = root.split(os.sep)[len(doc_path.split(os.sep)):] - for filename in files: - if filename.endswith(".md"): - modname = filename[:-len(".md")] - modpath = subdir_path + [modname] - documented_modules.append(modpath) - return documented_modules - -def tag_wrap(text, tag, attributes={}): - result = '\n<' + tag - for name in attributes.keys(): - result += ' ' + name + '=' + '"' + attributes[name] + '"' - result +='>' + text + '</'+ tag + '>\n' - return result - -def is_third_party(package_json): - return (not is_high_level(package_json)) and \ - (not(is_low_level(package_json))) - -def is_high_level(package_json): - return 'jetpack-high-level' in package_json.get('keywords', []) - -def is_low_level(package_json): - return 'jetpack-low-level' in package_json.get('keywords', []) - -def insert_after(target, insertion_point_id, text_to_insert): - insertion_point = target.find(insertion_point_id) + len(insertion_point_id) - return target[:insertion_point] + text_to_insert + target[insertion_point:] - -class WebDocs(object): - def __init__(self, root, base_url = None): - self.root = root - self.pkg_cfg = packaging.build_pkg_cfg(root) - self.packages_json = packaging.build_pkg_index(self.pkg_cfg) - self.base_page = self._create_base_page(root, base_url) - - def create_guide_page(self, path): - path, ext = os.path.splitext(path) - md_path = path + '.md' - md_content = unicode(open(md_path, 'r').read(), 'utf8') - guide_content = markdown.markdown(md_content) - return self._create_page(guide_content) - - def create_module_page(self, path): - path, ext = os.path.splitext(path) - md_path = path + '.md' - module_content = apirenderer.md_to_div(md_path) - return self._create_page(module_content) - - def create_package_page(self, package_name): - package_content = self._create_package_detail(package_name) - return self._create_page(package_content) - - def _create_page(self, page_content): - page = self._insert_title(self.base_page, page_content) - page = insert_after(page, CONTENT_ID, page_content) - return page.encode('utf8') - - def _create_module_list(self, package_json): - package_name = package_json['name'] - libs = package_json['files'][1]['lib'][1] - doc_path = package_json.get('doc', None) - if not doc_path: - return '' - modules = get_documentation(package_name, libs, doc_path) - modules.sort() - module_items = '' - relative_doc_path = doc_path[len(self.root) + 1:] - relative_doc_path_pieces = relative_doc_path.split(os.sep) - del relative_doc_path_pieces[-1] - relative_doc_URL = "/".join(relative_doc_path_pieces) - for module in modules: - module_link = tag_wrap('/'.join(module), 'a', \ - {'href': relative_doc_URL + '/' + '/'.join(module) + '.html'}) - module_items += module_link - return module_items - - def _create_package_summaries(self, packages_json, include): - packages = '' - for package_name in packages_json.keys(): - package_json = packages_json[package_name] - if not include(package_json): - continue - package_path = self.pkg_cfg["packages"][package_name]["root_dir"] - package_directory = package_path[len(self.root) + 1:] - package_directory = "/".join(package_directory.split(os.sep)) - package_link = tag_wrap(package_name, 'a', {'href': \ - package_directory + "/" \ - + 'index.html'}) - text = tag_wrap(package_link, 'h4') - text += self._create_module_list(package_json) - packages += tag_wrap(text, 'li', {'class':'package-summary', \ - 'style':'display: block;'}) - return packages - - def _create_base_page(self, root, base_url): - base_page = unicode(open(root + INDEX_PAGE, 'r').read(), 'utf8') - if base_url: - base_tag = 'href="' + base_url + '"' - base_page = insert_after(base_page, BASE_URL_INSERTION_POINT, base_tag) - sdk_version = get_versions()["version"] - base_page = insert_after(base_page, VERSION_INSERTION_POINT, "Version " + sdk_version) - third_party_summaries = \ - self._create_package_summaries(self.packages_json, is_third_party) - base_page = insert_after(base_page, \ - THIRD_PARTY_PACKAGE_SUMMARIES, third_party_summaries) - high_level_summaries = \ - self._create_package_summaries(self.packages_json, is_high_level) - base_page = insert_after(base_page, \ - HIGH_LEVEL_PACKAGE_SUMMARIES, high_level_summaries) - low_level_summaries = \ - self._create_package_summaries(self.packages_json, is_low_level) - base_page = insert_after(base_page, \ - LOW_LEVEL_PACKAGE_SUMMARIES, low_level_summaries) - return base_page - - def _create_package_detail_row(self, field_value, \ - field_descriptor, field_name): - meta = tag_wrap(tag_wrap(field_descriptor, 'span', \ - {'class':'meta-header'}), 'td') - value = tag_wrap(tag_wrap(field_value, 'span', \ - {'class':field_name}), 'td') - return tag_wrap(meta + value, 'tr') - - def _create_package_detail_table(self, package_json): - table_contents = '' - if package_json.get('author', None): - table_contents += self._create_package_detail_row(\ - cgi.escape(package_json['author']), 'Author', 'author') - if package_json.get('version', None): - table_contents += self._create_package_detail_row(\ - package_json['version'], 'Version', 'version') - if package_json.get('license', None): - table_contents += self._create_package_detail_row(\ - package_json['license'], 'License', 'license') - if package_json.get('dependencies', None): - table_contents += self._create_package_detail_row(\ - ', '.join(package_json['dependencies']), \ - 'Dependencies', 'dependencies') - table_contents += self._create_package_detail_row(\ - self._create_module_list(package_json), 'Modules', 'modules') - return tag_wrap(tag_wrap(table_contents, 'tbody'), 'table', \ - {'class':'meta-table'}) - - def _create_package_detail(self, package_name): - package_json = self.packages_json.get(package_name, None) - if not package_json: - raise IOError(errno.ENOENT, 'Package not found') - # pieces of the package detail: 1) title, 2) table, 3) description - package_title = tag_wrap(package_name, 'h1') - table = self._create_package_detail_table(package_json) - description = '' - if package_json.get('readme', None): - description += tag_wrap(tag_wrap(\ - markdown.markdown(\ - package_json['readme']), 'p'), 'div', {'class':'docs'}) - return tag_wrap(package_title + table + description, 'div', \ - {'class':'package-detail'}) - - def _insert_title(self, target, content): - match = re.search('<h1>.*</h1>', content) - if match: - title = match.group(0)[len('<h1>'):-len('</h1>')] + ' - ' + \ - DEFAULT_TITLE - else: - title = DEFAULT_TITLE - target = insert_after(target, TITLE_ID, title) - return target diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/bootstrap.js b/tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/bootstrap.js deleted file mode 100644 index 7bf6d84..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/mobile-utils/bootstrap.js +++ /dev/null @@ -1,78 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const Cc = Components.classes; -const Ci = Components.interfaces; -const Cu = Components.utils; -const Cr = Components.results; - -Components.utils.import("resource://gre/modules/Services.jsm"); - -const DEBUG = false; - -let log = DEBUG ? dump : function (){}; - - -function startup(data, reason) { - // This code allow to make all stdIO work - try { - Components.utils.import("resource://gre/modules/ctypes.jsm"); - let libdvm = ctypes.open("libdvm.so"); - let dvmStdioConverterStartup = libdvm.declare("dvmStdioConverterStartup", ctypes.default_abi, ctypes.void_t); - dvmStdioConverterStartup(); - log("MU: console redirected to adb logcat.\n"); - } catch(e) { - Cu.reportError("MU: unable to execute jsctype hack: "+e); - } - - // This code allow to kill firefox from adb - try { - let Watcher = { - window: null, - onOpenWindow: function(window) { - window = window.docShell.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow); - window.addEventListener("keydown", this, true); - }, - onCloseWindow: function (window) {}, - onWindowTitleChange: function () {}, - handleEvent: function(event) { - // This event is dispatched via: abd shell input keycode 19 - // KEYCODE_DPAD_UP = 19, UP can't be fired by virtual keyboard, - // so it should be safe to take this event as a kill signal. - // `adb shell input` and `JS keyCode` values doesn't map to same values - // In JS, KeyUp maps to DOM_VK_UP = 38: - // https://developer.mozilla.org/en/DOM/KeyboardEvent - if (event.keyCode == 38 && event.which == 38) { - Cu.reportError("Mobile killer triggered!"); - let appStartup = Cc['@mozilla.org/toolkit/app-startup;1']. - getService(Ci.nsIAppStartup); - appStartup.quit(Ci.nsIAppStartup.eForceQuit); - } - } - }; - Services.wm.addListener(Watcher); - log("MU: key listener to close firefox set.\n"); - } - catch(e) { - log("MU: Unable to register window watcher: " + e + "\n"); - } - - try { - let QuitObserver = { - observe: function (aSubject, aTopic, aData) { - Services.obs.removeObserver(QuitObserver, "quit-application", false); - dump("MU: APPLICATION-QUIT\n"); - } - }; - Services.obs.addObserver(QuitObserver, "quit-application", false); - log("MU: ready to watch firefox exit.\n"); - } catch(e) { - log("MU: unable to register quit-application observer: " + e + "\n"); - } -} - -function install() {} -function shutdown() {} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/templates.py b/tools/addon-sdk-1.7/python-lib/cuddlefish/templates.py deleted file mode 100644 index a04bb9a..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/templates.py +++ /dev/null @@ -1,83 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -#Template used by main.js -MAIN_JS = '''\ -const widgets = require("widget"); -const tabs = require("tabs"); - -var widget = widgets.Widget({ - id: "mozilla-link", - label: "Mozilla website", - contentURL: "http://www.mozilla.org/favicon.ico", - onClick: function() { - tabs.open("http://www.mozilla.org/"); - } -}); - -console.log("The add-on is running."); -''' - -#Template used by test-main.js -TEST_MAIN_JS = '''\ -const main = require("main"); - -exports.test_test_run = function(test) { - test.pass("Unit test running!"); -}; - -exports.test_id = function(test) { - test.assert(require("self").id.length > 0); -}; - -exports.test_url = function(test) { - require("request").Request({ - url: "http://www.mozilla.org/", - onComplete: function(response) { - test.assertEqual(response.statusText, "OK"); - test.done(); - } - }).get(); - test.waitUntilDone(20000); -}; - -exports.test_open_tab = function(test) { - const tabs = require("tabs"); - tabs.open({ - url: "http://www.mozilla.org/", - onReady: function(tab) { - test.assertEqual(tab.url, "http://www.mozilla.org/"); - test.done(); - } - }); - test.waitUntilDone(20000); -}; -''' - -#Template used by main.md -MAIN_JS_DOC = '''\ -The main module is a program that creates a widget. When a user clicks on -the widget, the program loads the mozilla.org website in a new tab. -''' - -#Template used by README.md -README_DOC = '''\ -This is the %(name)s add-on. It contains: - -* A program (lib/main.js). -* A few tests. -* Some meager documentation. -''' - -#Template used by package.json -PACKAGE_JSON = '''\ -{ - "name": "%(name)s", - "fullName": "%(fullName)s", - "description": "a basic add-on", - "author": "", - "license": "MPL 2.0", - "version": "0.1" -} -''' diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json b/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json deleted file mode 100644 index 1b82728..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/preferences-files/packages/simple-prefs/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "id": "jid1-fZHqN9JfrDBa8A", - "fullName": "Simple Prefs Test", - "author": "Erik Vold", - "preferences": [{ - "name": "test", - "type": "bool", - "title": "tëst", - "value": false - }, - { - "name": "test2", - "type": "string", - "title": "tëst", - "value": "ünicødé" - }], - "loader": "lib/main.js" -} diff --git a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/docs/main.md b/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/docs/main.md deleted file mode 100644 index 54518d3..0000000 --- a/tools/addon-sdk-1.7/python-lib/cuddlefish/tests/static-files/packages/minimal/docs/main.md +++ /dev/null @@ -1,5 +0,0 @@ -<!-- This Source Code Form is subject to the terms of the Mozilla Public - - License, v. 2.0. If a copy of the MPL was not distributed with this - - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> - -minimal docs |